

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_gpu,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch
			from torch import nn

			from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
			from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import ViTImageProcessor

class 							UpperCAmelCase_						:
							"""simple docstring"""







							def __init__(     self			,				_a			,				_a=1_3			,				_a=3_0			,				_a=2			,				_a=3			,				_a=True			,				_a=True			,				_a=3_2			,				_a=5			,				_a=4			,				_a=3_7			,				_a="gelu"			,				_a=0.1			,				_a=0.1			,				_a=1_0			,				_a=0.02			,				_a=None			,				_a=2			,				)       ->       List[Any]:
												_a      :       List[Any]   =						parent
												_a      :       Tuple   =						batch_size
												_a      :       Any   =						image_size
												_a      :       Tuple   =						patch_size
												_a      :       List[Any]   =						num_channels
												_a      :       int   =						is_training
												_a      :       List[str]   =						use_labels
												_a      :       List[str]   =						hidden_size
												_a      :       Any   =						num_hidden_layers
												_a      :       Dict   =						num_attention_heads
												_a      :       List[Any]   =						intermediate_size
												_a      :       Optional[int]   =						hidden_act
												_a      :       str   =						hidden_dropout_prob
												_a      :       int   =						attention_probs_dropout_prob
												_a      :       Tuple   =						type_sequence_label_size
												_a      :       int   =						initializer_range
												_a      :       str   =						scope
												_a      :       List[str]   =						encoder_stride

												# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
												_a      :       Optional[Any]   =						(image_size // patch_size) ** 2
												_a      :       Union[str, Any]   =						num_patches + 1


							def 							__lowercase							(     self			)       ->       Any:
												_a      :       Optional[Any]   =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

												_a      :       List[Any]   =						None
												if self.use_labels:
																	_a      :       int   =						ids_tensor([self.batch_size]			,				self.type_sequence_label_size			)

												_a      :       Dict   =						self.get_config()

												return config, pixel_values, labels


							def 							__lowercase							(     self			)       ->       List[Any]:
												return ViTConfig(
												    image_size=self.image_size			,				patch_size=self.patch_size			,				num_channels=self.num_channels			,				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			,				is_decoder=_a			,				initializer_range=self.initializer_range			,				encoder_stride=self.encoder_stride			,				)


							def 							__lowercase							(     self			,				_a			,				_a			,				_a			)       ->       Any:
												_a      :       Optional[int]   =						ViTModel(config=_a			)
												model.to(_a			)
												model.eval()
												_a      :       Dict   =						model(_a			)
												self.parent.assertEqual(result.last_hidden_state.shape			,				(self.batch_size, self.seq_length, self.hidden_size)			)


							def 							__lowercase							(     self			,				_a			,				_a			,				_a			)       ->       Dict:
												_a      :       List[Any]   =						ViTForMaskedImageModeling(config=_a			)
												model.to(_a			)
												model.eval()
												_a      :       Optional[int]   =						model(_a			)
												self.parent.assertEqual(
												    result.reconstruction.shape			,				(self.batch_size, self.num_channels, self.image_size, self.image_size)			)

												# test greyscale images
												_a      :       Tuple   =						1
												_a      :       List[str]   =						ViTForMaskedImageModeling(_a			)
												model.to(_a			)
												model.eval()

												_a      :       Any   =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
												_a      :       Tuple   =						model(_a			)
												self.parent.assertEqual(result.reconstruction.shape			,				(self.batch_size, 1, self.image_size, self.image_size)			)


							def 							__lowercase							(     self			,				_a			,				_a			,				_a			)       ->       List[str]:
												_a      :       List[str]   =						self.type_sequence_label_size
												_a      :       int   =						ViTForImageClassification(_a			)
												model.to(_a			)
												model.eval()
												_a      :       List[str]   =						model(_a			,				labels=_a			)
												self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.type_sequence_label_size)			)

												# test greyscale images
												_a      :       List[Any]   =						1
												_a      :       List[Any]   =						ViTForImageClassification(_a			)
												model.to(_a			)
												model.eval()

												_a      :       str   =						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
												_a      :       Optional[int]   =						model(_a			)
												self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.type_sequence_label_size)			)




							def 							__lowercase							(     self			)       ->       int:
												_a      :       int   =						self.prepare_config_and_inputs()
												(
												    (
												    _a
												) ,   (
												    _a
												) ,   (
												    _a
												) ,   
												)      :       int   =						config_and_inputs
												_a      :       int   =						{'''pixel_values''': pixel_values}
												return config, inputs_dict



@require_torch
class 							UpperCAmelCase_						(     __lowercase							,			__lowercase							,			unittest.TestCase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		List[str]             =       (
							    (
							        ViTModel,
							        ViTForImageClassification,
							        ViTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							UpperCAmelCase__			:		List[str]             =       (
							    {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification}
							    if is_torch_available()
							    else {}
							)
							UpperCAmelCase__			:		str             =       True

							UpperCAmelCase__			:		List[str]             =       False
							UpperCAmelCase__			:		str             =       False
							UpperCAmelCase__			:		Union[str, Any]             =       False


							def 							__lowercase							(     self			)       ->       str:
												_a      :       Dict   =						ViTModelTester(self			)
												_a      :       Optional[int]   =						ConfigTester(self			,				config_class=_a			,				has_text_modality=_a			,				hidden_size=3_7			)


							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												self.config_tester.run_common_tests()


							@unittest.skip(reason='''ViT does not use inputs_embeds'''			)
							def 							__lowercase							(     self			)       ->       Optional[Any]:
												pass


							def 							__lowercase							(     self			)       ->       Tuple:
												_a ,   _a      :       Union[str, Any]   =						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_a      :       Any   =						model_class(_a			)
																	self.assertIsInstance(model.get_input_embeddings()			,				(nn.Module)			)
																	_a      :       Optional[Any]   =						model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(_a			,				nn.Linear			)			)


							def 							__lowercase							(     self			)       ->       Any:
												_a ,   _a      :       Union[str, Any]   =						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																	_a      :       Tuple   =						model_class(_a			)
																	_a      :       Tuple   =						inspect.signature(model.forward			)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	_a      :       List[str]   =						[*signature.parameters.keys()]

																	_a      :       List[Any]   =						['''pixel_values''']
																	self.assertListEqual(arg_names[:1]			,				_a			)


							def 							__lowercase							(     self			)       ->       Optional[Any]:
												_a      :       Any   =						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_a			)


							def 							__lowercase							(     self			)       ->       int:
												_a      :       List[Any]   =						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_image_modeling(*_a			)


							def 							__lowercase							(     self			)       ->       Optional[int]:
												_a      :       Optional[int]   =						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*_a			)




							@slow
							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_a      :       Any   =						ViTModel.from_pretrained(_a			)
																	self.assertIsNotNone(_a			)



def   __UpperCAmelCase					(      )     ->	Optional[Any]:

					"""simple docstring"""

					_a      :       Union[str, Any]   =						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
					return image







@require_torch
@require_vision
class 							UpperCAmelCase_						(     unittest.TestCase  ):
							"""simple docstring"""







							@cached_property
							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224'''			) if is_vision_available() else None


							@slow
							def 							__lowercase							(     self			)       ->       Tuple:
												_a      :       str   =						ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''			).to(_a			)

												_a      :       Optional[int]   =						self.default_image_processor
												_a      :       List[str]   =						prepare_img()
												_a      :       str   =						image_processor(images=_a			,				return_tensors='''pt'''			).to(_a			)

												# forward pass
												with torch.no_grad():
																	_a      :       int   =						model(**_a			)

												# verify the logits
												_a      :       Union[str, Any]   =						torch.Size((1, 1_0_0_0)			)
												self.assertEqual(outputs.logits.shape			,				_a			)

												_a      :       Union[str, Any]   =						torch.tensor([-0.2744, 0.8215, -0.0836]			).to(_a			)

												self.assertTrue(torch.allclose(outputs.logits[0, :3]			,				_a			,				atol=1e-4			)			)


							@slow
							def 							__lowercase							(     self			)       ->       int:
												# ViT models have an `interpolate_pos_encoding` argument in their forward method,
												# allowing to interpolate the pre-trained position embeddings in order to use
												# the model on higher resolutions. The DINO model by Facebook AI leverages this
												# to visualize self-attention on higher resolution images.
												_a      :       Any   =						ViTModel.from_pretrained('''facebook/dino-vits8'''			).to(_a			)

												_a      :       Dict   =						ViTImageProcessor.from_pretrained('''facebook/dino-vits8'''			,				size=4_8_0			)
												_a      :       Optional[Any]   =						prepare_img()
												_a      :       int   =						image_processor(images=_a			,				return_tensors='''pt'''			)
												_a      :       List[Any]   =						inputs.pixel_values.to(_a			)

												# forward pass
												with torch.no_grad():
																	_a      :       List[Any]   =						model(_a			,				interpolate_pos_encoding=_a			)

												# verify the logits
												_a      :       Union[str, Any]   =						torch.Size((1, 3_6_0_1, 3_8_4)			)
												self.assertEqual(outputs.last_hidden_state.shape			,				_a			)

												_a      :       Union[str, Any]   =						torch.tensor(
												    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]			).to(_a			)

												self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]			,				_a			,				atol=1e-4			)			)




							@slow
							@require_accelerate
							@require_torch_gpu
							def 							__lowercase							(     self			)       ->       Union[str, Any]:
												_a      :       str   =						ViTModel.from_pretrained('''facebook/dino-vits8'''			,				torch_dtype=torch.floataa			,				device_map='''auto'''			)
												_a      :       Tuple   =						self.default_image_processor

												_a      :       int   =						prepare_img()
												_a      :       str   =						image_processor(images=_a			,				return_tensors='''pt'''			)
												_a      :       Dict   =						inputs.pixel_values.to(_a			)

												# forward pass to make sure inference works in fp16
												with torch.no_grad():
																	_a      :       Any   =						model(_a			)









"""simple docstring"""






import unittest

from transformers import MPNetConfig, 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 (
			    MPNetForMaskedLM,
			    MPNetForMultipleChoice,
			    MPNetForQuestionAnswering,
			    MPNetForSequenceClassification,
			    MPNetForTokenClassification,
			    MPNetModel,
			)






class lowerCAmelCase__      :






			'''simple docstring'''



			def __init__(    self    , lowercase    , lowercase=13    , lowercase=7    , lowercase=True    , lowercase=True    , lowercase=False    , lowercase=True    , lowercase=99    , lowercase=64    , lowercase=5    , lowercase=4    , lowercase=64    , lowercase="gelu"    , lowercase=0.1    , lowercase=0.1    , lowercase=512    , lowercase=16    , lowercase=2    , lowercase=0.02    , lowercase=3    , lowercase=4    , lowercase=None    , ):
							_lowerCamelCase	:     List[str]       =       parent
							_lowerCamelCase	:     List[str]       =       batch_size
							_lowerCamelCase	:     Tuple       =       seq_length
							_lowerCamelCase	:     List[Any]       =       is_training
							_lowerCamelCase	:     int       =       use_input_mask
							_lowerCamelCase	:     Optional[Any]       =       use_token_type_ids
							_lowerCamelCase	:     List[Any]       =       use_labels
							_lowerCamelCase	:     str       =       vocab_size
							_lowerCamelCase	:     Optional[int]       =       hidden_size
							_lowerCamelCase	:     List[str]       =       num_hidden_layers
							_lowerCamelCase	:     Optional[int]       =       num_attention_heads
							_lowerCamelCase	:     List[str]       =       intermediate_size
							_lowerCamelCase	:     int       =       hidden_act
							_lowerCamelCase	:     Optional[int]       =       hidden_dropout_prob
							_lowerCamelCase	:     List[Any]       =       attention_probs_dropout_prob
							_lowerCamelCase	:     List[str]       =       max_position_embeddings
							_lowerCamelCase	:     List[Any]       =       type_vocab_size
							_lowerCamelCase	:     Optional[int]       =       type_sequence_label_size
							_lowerCamelCase	:     Union[str, Any]       =       initializer_range
							_lowerCamelCase	:     Tuple       =       num_labels
							_lowerCamelCase	:     int       =       num_choices
							_lowerCamelCase	:     int       =       scope
			def    A_       (    self    ):
							return MPNetConfig.from_pretrained('microsoft/mpnet-base'    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       ids_tensor([self.batch_size, self.seq_length]    , self.vocab_size    )

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

							_lowerCamelCase	:     int       =       None
							_lowerCamelCase	:     List[str]       =       None
							_lowerCamelCase	:     Any       =       None
							if self.use_labels:
											_lowerCamelCase	:     List[str]       =       ids_tensor([self.batch_size]    , self.type_sequence_label_size    )
											_lowerCamelCase	:     str       =       ids_tensor([self.batch_size, self.seq_length]    , self.num_labels    )
											_lowerCamelCase	:     Dict       =       ids_tensor([self.batch_size]    , self.num_choices    )

							_lowerCamelCase	:     int       =       self.get_config()
							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
			def    A_       (    self    ):
							return MPNetConfig(
							    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    , initializer_range=self.initializer_range    , )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Optional[Any]       =       MPNetModel(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Tuple       =       model(lowercase    , lowercase    )
							_lowerCamelCase	:     Tuple       =       model(lowercase    )
							self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size)    )
							self.parent.assertEqual(result.pooler_output.shape    , (self.batch_size, self.hidden_size)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     str       =       MPNetForQuestionAnswering(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     str       =       model(
							    lowercase    , attention_mask=lowercase    , start_positions=lowercase    , end_positions=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)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Optional[int]       =       self.num_labels
							_lowerCamelCase	:     int       =       MPNetForSequenceClassification(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Optional[Any]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_labels)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     List[str]       =       self.num_choices
							_lowerCamelCase	:     List[str]       =       MPNetForMultipleChoice(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Union[str, Any]       =       input_ids.unsqueeze(1    ).expand(-1    , self.num_choices    , -1    ).contiguous()
							_lowerCamelCase	:     List[str]       =       input_mask.unsqueeze(1    ).expand(-1    , self.num_choices    , -1    ).contiguous()
							_lowerCamelCase	:     Any       =       model(
							    lowercase    , attention_mask=lowercase    , labels=lowercase    , )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_choices)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Any       =       self.num_labels
							_lowerCamelCase	:     Union[str, Any]       =       MPNetForTokenClassification(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Union[str, Any]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.seq_length, self.num_labels)    )






			def    A_       (    self    ):
							_lowerCamelCase	:     Dict       =       self.prepare_config_and_inputs()
							((_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase))	:     List[Any]       =       config_and_inputs
							_lowerCamelCase	:     str       =       {'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict






@require_torch
class lowerCAmelCase__      (	lowercase,      lowercase,      unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__ =     (
			    (
			        MPNetForMaskedLM,
			        MPNetForMultipleChoice,
			        MPNetForQuestionAnswering,
			        MPNetForSequenceClassification,
			        MPNetForTokenClassification,
			        MPNetModel,
			    )
			    if is_torch_available()
			    else ()
			)
			lowerCamelCase__ =     (
			    {
			        """feature-extraction""": MPNetModel,
			        """fill-mask""": MPNetForMaskedLM,
			        """question-answering""": MPNetForQuestionAnswering,
			        """text-classification""": MPNetForSequenceClassification,
			        """token-classification""": MPNetForTokenClassification,
			        """zero-shot""": MPNetForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase__ =     False
			lowerCamelCase__ =     True
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       MPNetModelTester(self    )
							_lowerCamelCase	:     List[Any]       =       ConfigTester(self    , config_class=lowercase    , hidden_size=37    )
			def    A_       (    self    ):
							self.config_tester.run_common_tests()
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_model(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase    )






			def    A_       (    self    ):
							_lowerCamelCase	:     str       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase    )






@require_torch
class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       MPNetModel.from_pretrained('microsoft/mpnet-base'    )
							_lowerCamelCase	:     Optional[Any]       =       torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]    )
							_lowerCamelCase	:     Any       =       model(lowercase    )[0]
							_lowerCamelCase	:     Dict       =       torch.Size((1, 11, 768)    )
							self.assertEqual(output.shape    , lowercase    )
							_lowerCamelCase	:     List[Any]       =       torch.tensor(
							    [[[-0.05_50, 0.19_43, -0.07_40], [-0.05_62, 0.22_11, -0.05_79], [-0.04_37, 0.33_37, -0.06_41]]]    )
							# compare the actual values for a slice.
							self.assertTrue(torch.allclose(output[:, :3, :3]    , lowercase    , atol=1E-4    )    )