

'''simple docstring'''

import glob
import os
from typing import Dict, List, Union

import torch

from diffusers.utils import is_safetensors_available


if is_safetensors_available():
						import safetensors.torch

from huggingface_hub import snapshot_download

from diffusers import DiffusionPipeline, __version__
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME







class lowerCamelCase   (    __lowerCAmelCase				):

				def __init__(       self )    ->							List[str]:
					self.register_to_config()
					super().__init__()

				def 					_lowerCamelCase    (       self,						lowercase_,						lowercase_ )    ->							List[str]:
					if dicta == dicta:
						return True
					else:
						snake_case			,			snake_case							=					self._remove_meta_keys(lowercase_ )
						snake_case			,			snake_case							=					self._remove_meta_keys(lowercase_ )
						if configa == configa:
							print(F'''Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.''' )
							return True
					return False

				def 					_lowerCamelCase    (       self,						lowercase_ )    ->							str:
					snake_case							=					[]
					snake_case							=					config_dict.copy()
					for key in config_dict.keys():
						if key.startswith('_' ):
							temp_dict.pop(lowercase_ )
							meta_keys.append(lowercase_ )
					return (temp_dict, meta_keys)

				@torch.no_grad()
				def 					_lowerCamelCase    (       self,						lowercase_,						**lowercase_ )    ->							Any:
					snake_case							=					kwargs.pop('cache_dir',						lowercase_ )
					snake_case							=					kwargs.pop('resume_download',						lowercase_ )
					snake_case							=					kwargs.pop('force_download',						lowercase_ )
					snake_case							=					kwargs.pop('proxies',						lowercase_ )
					snake_case							=					kwargs.pop('local_files_only',						lowercase_ )
					snake_case							=					kwargs.pop('use_auth_token',						lowercase_ )
					snake_case							=					kwargs.pop('revision',						lowercase_ )
					snake_case							=					kwargs.pop('torch_dtype',						lowercase_ )
					snake_case							=					kwargs.pop('device_map',						lowercase_ )

					snake_case							=					kwargs.pop('alpha',						0.5 )
					snake_case							=					kwargs.pop('interp',						lowercase_ )

					print('Received list',						lowercase_ )
					print(F'''Combining with alpha={alpha}, interpolation mode={interp}''' )

					snake_case							=					len(lowercase_ )
					# Ignore result from model_index_json comparision of the two checkpoints
					snake_case							=					kwargs.pop('force',						lowercase_ )

					# If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
					if checkpoint_count > 3 or checkpoint_count < 2:
						raise ValueError(
						    'Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being'
						    ' passed.' )

					print('Received the right number of checkpoints' )
					# chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
					# chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None

					# Validate that the checkpoints can be merged
					# Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
					snake_case							=					[]
					for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
						snake_case							=					DiffusionPipeline.load_config(
						    lowercase_,						cache_dir=lowercase_,						resume_download=lowercase_,						force_download=lowercase_,						proxies=lowercase_,						local_files_only=lowercase_,						use_auth_token=lowercase_,						revision=lowercase_,						)
						config_dicts.append(lowercase_ )

					snake_case							=					True
					for idx in range(1,						len(lowercase_ ) ):
						comparison_result &= self._compare_model_configs(config_dicts[idx - 1],						config_dicts[idx] )
						if not force and comparison_result is False:
							raise ValueError('Incompatible checkpoints. Please check model_index.json for the models.' )
							print(config_dicts[0],						config_dicts[1] )
					print('Compatible model_index.json files found' )
					# Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
					snake_case							=					[]
					for pretrained_model_name_or_path, config_dict in zip(lowercase_,						lowercase_ ):
						snake_case							=					[k for k in config_dict.keys() if not k.startswith('_' )]
						snake_case							=					[os.path.join(lowercase_,						'*' ) for k in folder_names]
						allow_patterns += [
						    WEIGHTS_NAME,
						    SCHEDULER_CONFIG_NAME,
						    CONFIG_NAME,
						    ONNX_WEIGHTS_NAME,
						    DiffusionPipeline.config_name,
						]
						snake_case							=					config_dict.get('_class_name' )
						snake_case							=					{'diffusers': __version__, 'pipeline_class': requested_pipeline_class}

						snake_case							=					(
						    pretrained_model_name_or_path
						    if os.path.isdir(lowercase_ )
						    else snapshot_download(
						        lowercase_,						cache_dir=lowercase_,						resume_download=lowercase_,						proxies=lowercase_,						local_files_only=lowercase_,						use_auth_token=lowercase_,						revision=lowercase_,						allow_patterns=lowercase_,						user_agent=lowercase_,						)
						)
						print('Cached Folder',						lowercase_ )
						cached_folders.append(lowercase_ )

					# Step 3:-
					# Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
					snake_case							=					DiffusionPipeline.from_pretrained(
					    cached_folders[0],						torch_dtype=lowercase_,						device_map=lowercase_ )
					final_pipe.to(self.device )

					snake_case							=					None
					if len(lowercase_ ) > 2:
						snake_case							=					os.path.join(cached_folders[2] )

					if interp == "sigmoid":
						snake_case							=					CheckpointMergerPipeline.sigmoid
					elif interp == "inv_sigmoid":
						snake_case							=					CheckpointMergerPipeline.inv_sigmoid
					elif interp == "add_diff":
						snake_case							=					CheckpointMergerPipeline.add_difference
					else:
						snake_case							=					CheckpointMergerPipeline.weighted_sum

					# Find each module's state dict.
					for attr in final_pipe.config.keys():
						if not attr.startswith('_' ):
							snake_case							=					os.path.join(cached_folders[1],						lowercase_ )
							if os.path.exists(lowercase_ ):
								snake_case							=					[
								    *glob.glob(os.path.join(lowercase_,						'*.safetensors' ) ),
								    *glob.glob(os.path.join(lowercase_,						'*.bin' ) ),
								]
								snake_case							=					files[0] if len(lowercase_ ) > 0 else None
							if len(lowercase_ ) < 3:
								snake_case							=					None
							else:
								snake_case							=					os.path.join(cached_folders[2],						lowercase_ )
								if os.path.exists(lowercase_ ):
									snake_case							=					[
									    *glob.glob(os.path.join(lowercase_,						'*.safetensors' ) ),
									    *glob.glob(os.path.join(lowercase_,						'*.bin' ) ),
									]
									snake_case							=					files[0] if len(lowercase_ ) > 0 else None
                # For an attr if both checkpoint_path_1 and 2 are None, ignore.
                # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
							if checkpoint_path_a is None and checkpoint_path_a is None:
								print(F'''Skipping {attr}: not present in 2nd or 3d model''' )
								continue
							try:
								snake_case							=					getattr(lowercase_,						lowercase_ )
								if isinstance(lowercase_,						lowercase_ ):  # ignore requires_safety_checker boolean
									continue
								snake_case							=					getattr(lowercase_,						'state_dict' )
								snake_case							=					theta_a()

								snake_case							=					getattr(lowercase_,						'load_state_dict' )
								snake_case							=					(
								    safetensors.torch.load_file(lowercase_ )
								    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors' ))
								    else torch.load(lowercase_,						map_location='cpu' )
								)
								snake_case							=					None
								if checkpoint_path_a:
									snake_case							=					(
									    safetensors.torch.load_file(lowercase_ )
									    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors' ))
									    else torch.load(lowercase_,						map_location='cpu' )
									)

								if not theta_a.keys() == theta_a.keys():
									print(F'''Skipping {attr}: key mismatch''' )
									continue
								if theta_a and not theta_a.keys() == theta_a.keys():
									print(F'''Skipping {attr}:y mismatch''' )
							except Exception as e:
								print(F'''Skipping {attr} do to an unexpected error: {str(lowercase_ )}''' )
								continue
							print(F'''MERGING {attr}''' )

							for key in theta_a.keys():
								if theta_a:
									snake_case							=					theta_func(theta_a[key],						theta_a[key],						theta_a[key],						lowercase_ )
								else:
									snake_case							=					theta_func(theta_a[key],						theta_a[key],						lowercase_,						lowercase_ )

							del theta_a
							del theta_a
							update_theta_a(lowercase_ )

							del theta_a
					return final_pipe

				@staticmethod
				def 					_lowerCamelCase    (       lowercase_,						lowercase_,						lowercase_,						lowercase_ )    ->							Dict:
					return ((1 - alpha) * thetaa) + (alpha * thetaa)

				@staticmethod
				def 					_lowerCamelCase    (       lowercase_,						lowercase_,						lowercase_,						lowercase_ )    ->							int:
					snake_case							=					alpha * alpha * (3 - (2 * alpha))
					return thetaa + ((thetaa - thetaa) * alpha)

				@staticmethod
				def 					_lowerCamelCase    (       lowercase_,						lowercase_,						lowercase_,						lowercase_ )    ->							Tuple:
					import math

					snake_case							=					0.5 - math.sin(math.asin(1.0 - 2.0 * alpha ) / 3.0 )
					return thetaa + ((thetaa - thetaa) * alpha)






				@staticmethod
				def 					_lowerCamelCase    (       lowercase_,						lowercase_,						lowercase_,						lowercase_ )    ->							Optional[int]:
					return thetaa + (thetaa - thetaa) * (1.0 - alpha)






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				:






		"""simple docstring"""







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






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



		def 					_a					(      self     :					Tuple ):






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

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

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

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

					_snake_case														=   self.get_config()

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



		def 					_a					(      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 					_a					(      self     :					List[Any]	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[Any]	,       __SCREAMING_SNAKE_CASE     :					Any	,       __SCREAMING_SNAKE_CASE     :					List[Any]	,       __SCREAMING_SNAKE_CASE     :					List[str] ):






					"""simple docstring"""
					_snake_case														=   DPRContextEncoder(config=__SCREAMING_SNAKE_CASE )
					model.to(__SCREAMING_SNAKE_CASE )
					model.eval()
					_snake_case														=   model(__SCREAMING_SNAKE_CASE	,       attention_mask=__SCREAMING_SNAKE_CASE	,       token_type_ids=__SCREAMING_SNAKE_CASE )
					_snake_case														=   model(__SCREAMING_SNAKE_CASE	,       token_type_ids=__SCREAMING_SNAKE_CASE )
					_snake_case														=   model(__SCREAMING_SNAKE_CASE )
					self.parent.assertEqual(result.pooler_output.shape	,       (self.batch_size, self.projection_dim or self.hidden_size) )



		def 					_a					(      self     :					str	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					Dict	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					str ):






					"""simple docstring"""
					_snake_case														=   DPRQuestionEncoder(config=__SCREAMING_SNAKE_CASE )
					model.to(__SCREAMING_SNAKE_CASE )
					model.eval()
					_snake_case														=   model(__SCREAMING_SNAKE_CASE	,       attention_mask=__SCREAMING_SNAKE_CASE	,       token_type_ids=__SCREAMING_SNAKE_CASE )
					_snake_case														=   model(__SCREAMING_SNAKE_CASE	,       token_type_ids=__SCREAMING_SNAKE_CASE )
					_snake_case														=   model(__SCREAMING_SNAKE_CASE )
					self.parent.assertEqual(result.pooler_output.shape	,       (self.batch_size, self.projection_dim or self.hidden_size) )



		def 					_a					(      self     :					List[str]	,       __SCREAMING_SNAKE_CASE     :					int	,       __SCREAMING_SNAKE_CASE     :					List[Any]	,       __SCREAMING_SNAKE_CASE     :					int	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]	,       __SCREAMING_SNAKE_CASE     :					Any	,       __SCREAMING_SNAKE_CASE     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					Any ):






					"""simple docstring"""
					_snake_case														=   DPRReader(config=__SCREAMING_SNAKE_CASE )
					model.to(__SCREAMING_SNAKE_CASE )
					model.eval()
					_snake_case														=   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     :					Any ):






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

@require_torch
class 						_SCREAMING_SNAKE_CASE				(  _lowercase   ,  _lowercase   ,  unittest.TestCase				):






		"""simple docstring"""







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

		A_    			=   False
		A_    			=   False  # why?
		A_    			=   False
		A_    			=   False



		def 					_a					(      self     :					Union[str, Any] ):






					"""simple docstring"""
					_snake_case														=   DPRModelTester(self )
					_snake_case														=   ConfigTester(self	,       config_class=__SCREAMING_SNAKE_CASE	,       hidden_size=37 )



		def 					_a					(      self     :					int ):






					"""simple docstring"""
					self.config_tester.run_common_tests()



		def 					_a					(      self     :					List[str] ):






					"""simple docstring"""
					_snake_case														=   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_context_encoder(*__SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					List[str] ):






					"""simple docstring"""
					_snake_case														=   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_question_encoder(*__SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					Optional[Any] ):






					"""simple docstring"""
					_snake_case														=   self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_reader(*__SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					Optional[Any] ):






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

					_snake_case														=   DPRQuestionEncoder(config=__SCREAMING_SNAKE_CASE )
					model.to(__SCREAMING_SNAKE_CASE )
					model.eval()

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

					self.assertIsNotNone(__SCREAMING_SNAKE_CASE )







		@slow
		def 					_a					(      self     :					List[str] ):






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

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

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

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

@require_torch
class 						_SCREAMING_SNAKE_CASE				(  unittest.TestCase				):






		"""simple docstring"""







		@slow
		def 					_a					(      self     :					Dict ):






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

					_snake_case														=   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]
					_snake_case														=   model(__SCREAMING_SNAKE_CASE )[0]  # embedding shape = (1, 768)
					# compare the actual values for a slice.
					_snake_case														=   torch.tensor(
					    [
					        [
					            0.0_3_2_3_6_2_5_3,
					            0.1_2_7_5_3_3_3_5,
					            0.1_6_8_1_8_5_0_9,
					            0.0_0_2_7_9_7_8_6,
					            0.3_8_9_6_9_3_3,
					            0.2_4_2_6_4_9_4_5,
					            0.2_1_7_8_9_7_1,
					            -0.0_2_3_3_5_2_2_7,
					            -0.0_8_4_8_1_9_5_9,
					            -0.1_4_3_2_4_1_1_7,
					        ]
					    ]	,       dtype=torch.float	,       device=__SCREAMING_SNAKE_CASE	,       )
					self.assertTrue(torch.allclose(output[:, :10]	,       __SCREAMING_SNAKE_CASE	,       atol=1e-4 ) )







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






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

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

					_snake_case														=   model(**__SCREAMING_SNAKE_CASE )

					# compare the actual values for a slice.
					_snake_case														=   torch.tensor(
					    [[-1_0.3_0_0_5, -1_0.7_7_6_5, -1_1.4_8_7_2, -1_1.6_8_4_1, -1_1.9_3_1_2, -1_0.3_0_0_2, -9.8_5_4_4, -1_1.7_3_7_8, -1_2.0_8_2_1, -1_0.2_9_7_5]]	,       dtype=torch.float	,       device=__SCREAMING_SNAKE_CASE	,       )

					_snake_case														=   torch.tensor(
					    [[-1_1.0_6_8_4, -1_1.7_0_4_1, -1_1.5_3_9_7, -1_0.3_4_6_5, -1_0.8_7_9_1, -6.8_4_4_3, -1_1.9_9_5_9, -1_1.0_3_6_4, -1_0.0_0_9_6, -6.8_4_0_5]]	,       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 ) )

