'''simple docstring'''



import inspect
import unittest

from transformers import ViTMSNConfig
from transformers.testing_utils import require_torch, 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 ViTMSNForImageClassification, ViTMSNModel
	from transformers.models.vit_msn.modeling_vit_msn import VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
	from PIL import Image

	from transformers import ViTImageProcessor






class 	UpperCamelCase__:




				def __init__(		self      :			Tuple				,   lowerCAmelCase      :			List[Any]				,   lowerCAmelCase      :			List[str]=13				,   lowerCAmelCase      :			str=30				,   lowerCAmelCase      :			Optional[int]=2				,   lowerCAmelCase      :			List[str]=3				,   lowerCAmelCase      :			Tuple=True				,   lowerCAmelCase      :			Any=True				,   lowerCAmelCase      :			List[str]=32				,   lowerCAmelCase      :			Optional[int]=5				,   lowerCAmelCase      :			Dict=4				,   lowerCAmelCase      :			int=37				,   lowerCAmelCase      :			Dict="gelu"				,   lowerCAmelCase      :			int=0.1				,   lowerCAmelCase      :			Optional[int]=0.1				,   lowerCAmelCase      :			Any=10				,   lowerCAmelCase      :			Union[str, Any]=0.02				,   lowerCAmelCase      :			Any=None				,   )->					List[Any]:

										"""simple docstring"""




										UpperCAmelCase					    =     parent
										UpperCAmelCase					    =     batch_size
										UpperCAmelCase					    =     image_size
										UpperCAmelCase					    =     patch_size
										UpperCAmelCase					    =     num_channels
										UpperCAmelCase					    =     is_training
										UpperCAmelCase					    =     use_labels
										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					    =     type_sequence_label_size
										UpperCAmelCase					    =     initializer_range
										UpperCAmelCase					    =     scope

										# in ViT MSN, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
										UpperCAmelCase					    =     (image_size // patch_size) ** 2
										UpperCAmelCase					    =     num_patches + 1




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

										"""simple docstring"""




										UpperCAmelCase					    =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

										UpperCAmelCase					    =     None
										if self.use_labels:
																UpperCAmelCase					    =     ids_tensor([self.batch_size]				,   self.type_sequence_label_size				)

										UpperCAmelCase					    =     self.get_config()

										return config, pixel_values, labels




				def 					a__(		self      :			List[Any]				)->					List[str]:

										"""simple docstring"""




										return ViTMSNConfig(
										    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				,   initializer_range=self.initializer_range				,   )




				def 					a__(		self      :			Optional[int]				,   lowerCAmelCase      :			int				,   lowerCAmelCase      :			Tuple				,   lowerCAmelCase      :			Optional[int]				)->					Optional[Any]:

										"""simple docstring"""




										UpperCAmelCase					    =     ViTMSNModel(config=lowerCAmelCase				)
										model.to(lowerCAmelCase				)
										model.eval()
										UpperCAmelCase					    =     model(lowerCAmelCase				)
										self.parent.assertEqual(result.last_hidden_state.shape				,   (self.batch_size, self.seq_length, self.hidden_size)				)




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

										"""simple docstring"""




										UpperCAmelCase					    =     self.type_sequence_label_size
										UpperCAmelCase					    =     ViTMSNForImageClassification(lowerCAmelCase				)
										model.to(lowerCAmelCase				)
										model.eval()
										UpperCAmelCase					    =     model(lowerCAmelCase				,   labels=lowerCAmelCase				)
										print('''Pixel and labels shape: {pixel_values.shape}, {labels.shape}'''				)
										print('''Labels: {labels}'''				)
										self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.type_sequence_label_size)				)

										# test greyscale images
										UpperCAmelCase					    =     1
										UpperCAmelCase					    =     ViTMSNForImageClassification(lowerCAmelCase				)
										model.to(lowerCAmelCase				)
										model.eval()

										UpperCAmelCase					    =     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]				)
										UpperCAmelCase					    =     model(lowerCAmelCase				)
										self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.type_sequence_label_size)				)





				def 					a__(		self      :			Dict				)->					int:

										"""simple docstring"""




										UpperCAmelCase					    =     self.prepare_config_and_inputs()
										UpperCAmelCase					    =     config_and_inputs
										UpperCAmelCase					    =     {"""pixel_values""": pixel_values}
										return config, inputs_dict







@require_torch
class 	UpperCamelCase__(       _SCREAMING_SNAKE_CASE						,    _SCREAMING_SNAKE_CASE						,    unittest.TestCase	):
				__magic_name__    :				List[Any]  		=	(ViTMSNModel, ViTMSNForImageClassification) if is_torch_available() else ()
				__magic_name__    :				List[Any]  		=	(
				    {"feature-extraction": ViTMSNModel, "image-classification": ViTMSNForImageClassification}
				    if is_torch_available()
				    else {}
				)

				__magic_name__    :				int  		=	False
				__magic_name__    :				Union[str, Any]  		=	False
				__magic_name__    :				Union[str, Any]  		=	False
				__magic_name__    :				Any  		=	False




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

										"""simple docstring"""




										UpperCAmelCase					    =     ViTMSNModelTester(self				)
										UpperCAmelCase					    =     ConfigTester(self				,   config_class=lowerCAmelCase				,   has_text_modality=lowerCAmelCase				,   hidden_size=37				)




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

										"""simple docstring"""




										self.config_tester.run_common_tests()




				@unittest.skip(reason='''ViTMSN does not use inputs_embeds'''				)
				def 					a__(		self      :			Any				)->					Union[str, Any]:

										"""simple docstring"""




										pass




				def 					a__(		self      :			Dict				)->					str:

										"""simple docstring"""




										UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
																UpperCAmelCase					    =     model_class(lowerCAmelCase				)
																self.assertIsInstance(model.get_input_embeddings()				,   (nn.Module)				)
																UpperCAmelCase					    =     model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(lowerCAmelCase				,   nn.Linear				)				)




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

										"""simple docstring"""




										UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs_for_common()

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

																UpperCAmelCase					    =     ["""pixel_values"""]
																self.assertListEqual(arg_names[:1]				,   lowerCAmelCase				)




				def 					a__(		self      :			Optional[int]				)->					List[str]:

										"""simple docstring"""




										UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowerCAmelCase				)




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

										"""simple docstring"""




										UpperCAmelCase					    =     self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase				)





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

										"""simple docstring"""




										for model_name in VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																UpperCAmelCase					    =     ViTMSNModel.from_pretrained(lowerCAmelCase				)
																self.assertIsNotNone(lowerCAmelCase				)







def 				lowerCamelCase__				(	):




						'''simple docstring'''






						UpperCAmelCase					    =     Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
						return image






@require_torch
@require_vision
class 	UpperCamelCase__(       unittest.TestCase	):




				@cached_property
				def 					a__(		self      :			Any				)->					List[Any]:

										"""simple docstring"""




										return ViTImageProcessor.from_pretrained('''facebook/vit-msn-small'''				) if is_vision_available() else None





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

										"""simple docstring"""




										torch.manual_seed(2				)
										UpperCAmelCase					    =     ViTMSNForImageClassification.from_pretrained('''facebook/vit-msn-small'''				).to(lowerCAmelCase				)

										UpperCAmelCase					    =     self.default_image_processor
										UpperCAmelCase					    =     prepare_img()
										UpperCAmelCase					    =     image_processor(images=lowerCAmelCase				,   return_tensors='''pt'''				).to(lowerCAmelCase				)

										# forward pass
										with torch.no_grad():
																UpperCAmelCase					    =     model(**lowerCAmelCase				)

										# verify the logits
										UpperCAmelCase					    =     torch.Size((1, 1000)				)
										self.assertEqual(outputs.logits.shape				,   lowerCAmelCase				)

										UpperCAmelCase					    =     torch.tensor([-0.0803, -0.4454, -0.2375]				).to(lowerCAmelCase				)

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









'''simple docstring'''



def 				lowerCamelCase__				(	A       :      int				,       A       :      int					):




						'''simple docstring'''






						while a != 0:
												UpperCAmelCase    ,    UpperCAmelCase					    =     b % a, a
						return b




def 				lowerCamelCase__				(	A       :      int				,       A       :      int					):




						'''simple docstring'''






						if gcd(A				,       A					) != 1:
												UpperCAmelCase					    =     f"""mod inverse of {a!r} and {m!r} does not exist"""
												raise ValueError(A					)
						UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase					    =     1, 0, a
						UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase					    =     0, 1, m
						while va != 0:
												UpperCAmelCase					    =     ua // va
												UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase					    =     (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
						return ua % m





