

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

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

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

							def 					_lowerCAmelCase  ( self       :    Tuple    )   ->    Optional[Any]:

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

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

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

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

									lowercase										=							self.get_config()

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

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

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

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

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

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

									"""simple docstring"""
									lowercase										=							DPRReader(config=a    )
									model.to(a    )
									model.eval()
									lowercase										=							model(
									    a ,		attention_mask=a ,		)

									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 					_lowerCAmelCase  ( self       :    Optional[int]    )   ->    int:

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




@require_torch
class 	_lowerCAmelCase    (      __snake_case       ,       __snake_case       ,       unittest.TestCase       ):
							__lowerCAmelCase					:    List[str]     =  (
							    (
							        DPRContextEncoder,
							        DPRQuestionEncoder,
							        DPRReader,
							    )
							    if is_torch_available()
							    else ()
							)
							__lowerCAmelCase					:    Any     =  {'''feature-extraction''': DPRQuestionEncoder} if is_torch_available() else {}

							__lowerCAmelCase					:    Tuple     =  False
							__lowerCAmelCase					:    Dict     =  False  # why?
							__lowerCAmelCase					:    Tuple     =  False
							__lowerCAmelCase					:    List[Any]     =  False

							def 					_lowerCAmelCase  ( self       :    List[Any]    )   ->    Tuple:

									"""simple docstring"""
									lowercase										=							DPRModelTester(self    )
									lowercase										=							ConfigTester(self ,		config_class=a ,		hidden_size=37    )

							def 					_lowerCAmelCase  ( self       :    Union[str, Any]    )   ->    Tuple:

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

							def 					_lowerCAmelCase  ( self       :    List[Any]    )   ->    Optional[int]:

									"""simple docstring"""
									lowercase										=							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_context_encoder(*a    )

							def 					_lowerCAmelCase  ( self       :    Dict    )   ->    Optional[int]:

									"""simple docstring"""
									lowercase										=							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_question_encoder(*a    )

							def 					_lowerCAmelCase  ( self       :    int    )   ->    List[Any]:

									"""simple docstring"""
									lowercase										=							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_reader(*a    )

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

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

									lowercase										=							DPRQuestionEncoder(config=a    )
									model.to(a    )
									model.eval()

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

									self.assertIsNotNone(a    )

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

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

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

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

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




@require_torch
class 	_lowerCAmelCase    (      unittest.TestCase       ):

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

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

									lowercase										=							torch.tensor(
									    [[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]] ,		dtype=torch.long ,		device=a    )  # [CLS] hello, is my dog cute? [SEP]
									lowercase										=							model(a    )[0]  # embedding shape = (1, 768)
									# compare the actual values for a slice.
									lowercase										=							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=a ,		)
									self.assertTrue(torch.allclose(output[:, :10] ,		a ,		atol=1E-4    )    )

							@slow
							def 					_lowerCAmelCase  ( self       :    Tuple    )   ->    Dict:

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

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

									lowercase										=							model(**a    )

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

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


"""simple docstring"""






import warnings

from ...utils import logging
from .image_processing_convnext import ConvNextImageProcessor


__lowerCAmelCase				      =   logging.get_logger(__name__)
class 	_lowerCAmelCase    (      __snake_case       ):

							def __init__( self       :    Dict ,		*a       :    Any ,		**a       :    List[str]    )   ->    None:

									"""simple docstring"""
									warnings.warn(
									    '''The class ConvNextFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
									    ''' Please use ConvNextImageProcessor instead.''' ,		a ,		)
									super().__init__(*a ,		**a    )