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 	snake_case__ :
	def __init__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=13      ,       lowerCAmelCase__=30      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=32      ,       lowerCAmelCase__=5      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=37      ,       lowerCAmelCase__="gelu"      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=10      ,       lowerCAmelCase__=0.0_2      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=2      ,       )							->				Optional[int]:
							__magic_name__      :       Any       						= parent
							__magic_name__      :       Dict       						= batch_size
							__magic_name__      :       Optional[int]       						= image_size
							__magic_name__      :       Tuple       						= patch_size
							__magic_name__      :       str       						= num_channels
							__magic_name__      :       Any       						= is_training
							__magic_name__      :       List[Any]       						= use_labels
							__magic_name__      :       int       						= hidden_size
							__magic_name__      :       List[Any]       						= num_hidden_layers
							__magic_name__      :       List[str]       						= num_attention_heads
							__magic_name__      :       Tuple       						= intermediate_size
							__magic_name__      :       Dict       						= hidden_act
							__magic_name__      :       Tuple       						= hidden_dropout_prob
							__magic_name__      :       List[Any]       						= attention_probs_dropout_prob
							__magic_name__      :       int       						= type_sequence_label_size
							__magic_name__      :       int       						= initializer_range
							__magic_name__      :       List[Any]       						= scope
							__magic_name__      :       Any       						= encoder_stride

							# in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
							__magic_name__      :       Dict       						= (image_size // patch_size) ** 2
							__magic_name__      :       Tuple       						= num_patches + 1
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       Any       						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							__magic_name__      :       str       						= None
							if self.use_labels:
													__magic_name__      :       Dict       						= ids_tensor([self.batch_size]      ,       self.type_sequence_label_size			)

							__magic_name__      :       str       						= self.get_config()

							return config, pixel_values, labels
	def       __magic_name__    (    self			)							->				List[str]:
							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=lowerCAmelCase__      ,       initializer_range=self.initializer_range      ,       encoder_stride=self.encoder_stride      ,       )
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Union[str, Any]:
							__magic_name__      :       Tuple       						= ViTModel(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       Dict       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.last_hidden_state.shape      ,       (self.batch_size, self.seq_length, self.hidden_size)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				int:
							__magic_name__      :       Optional[Any]       						= ViTForMaskedImageModeling(config=lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       List[str]       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(
							    result.reconstruction.shape      ,       (self.batch_size, self.num_channels, self.image_size, self.image_size)			)

							# test greyscale images
							__magic_name__      :       Tuple       						= 1
							__magic_name__      :       Optional[Any]       						= ViTForMaskedImageModeling(lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()

							__magic_name__      :       Tuple       						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							__magic_name__      :       Any       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.reconstruction.shape      ,       (self.batch_size, 1, self.image_size, self.image_size)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[str]:
							__magic_name__      :       List[Any]       						= self.type_sequence_label_size
							__magic_name__      :       Optional[int]       						= ViTForImageClassification(lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()
							__magic_name__      :       Any       						= model(lowerCAmelCase__      ,       labels=lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)

							# test greyscale images
							__magic_name__      :       Dict       						= 1
							__magic_name__      :       Tuple       						= ViTForImageClassification(lowerCAmelCase__			)
							model.to(lowerCAmelCase__			)
							model.eval()

							__magic_name__      :       Dict       						= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
							__magic_name__      :       List[Any]       						= model(lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.type_sequence_label_size)			)







	def       __magic_name__    (    self			)							->				List[str]:
							__magic_name__      :       Dict       						= self.prepare_config_and_inputs()
							(
							    __magic_name__      
							)      :       int       						= config_and_inputs
							__magic_name__      :       List[Any]       						= {"""pixel_values""": pixel_values}
							return config, inputs_dict





@require_torch
class 	snake_case__ (							__lowercase						,  __lowercase						,  unittest.TestCase				):
	lowercase__						:					Optional[Any]											=   (
	    (
	        ViTModel,
	        ViTForImageClassification,
	        ViTForMaskedImageModeling,
	    )
	    if is_torch_available()
	    else ()
	)
	lowercase__						:					int											=   (
	    {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
	    if is_torch_available()
	    else {}
	)
	lowercase__						:					Dict											=   True

	lowercase__						:					str											=   False
	lowercase__						:					Optional[int]											=   False
	lowercase__						:					Tuple											=   False
	def       __magic_name__    (    self			)							->				List[Any]:
							__magic_name__      :       List[str]       						= ViTModelTester(self			)
							__magic_name__      :       Dict       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       has_text_modality=lowerCAmelCase__      ,       hidden_size=37			)
	def       __magic_name__    (    self			)							->				Any:
							self.config_tester.run_common_tests()
	@unittest.skip(reason="""ViT does not use inputs_embeds"""			)
	def       __magic_name__    (    self			)							->				Any:
							pass
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__magic_name__      :       Union[str, Any]       						= model_class(lowerCAmelCase__			)
													self.assertIsInstance(model.get_input_embeddings()      ,       (nn.Module)			)
													__magic_name__      :       str       						= model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(lowerCAmelCase__      ,       nn.Linear			)			)
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Optional[Any]       						= self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__magic_name__      :       int       						= model_class(lowerCAmelCase__			)
													__magic_name__      :       Optional[Any]       						= inspect.signature(model.forward			)
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													__magic_name__      :       Tuple       						= [*signature.parameters.keys()]

													__magic_name__      :       Optional[int]       						= ["""pixel_values"""]
													self.assertListEqual(arg_names[:1]      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__      :       str       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       List[Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       int       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__			)







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

							for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       str       						= ViTModel.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)



def    UpperCamelCase						(	):






						"""simple docstring"""







						__magic_name__      :       Dict       						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						return image





@require_torch
@require_vision
class 	snake_case__ (							unittest.TestCase				):
	@cached_property
	def       __magic_name__    (    self			)							->				Optional[Any]:
							return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""			) if is_vision_available() else None
	@slow
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Any       						= ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""			).to(lowerCAmelCase__			)

							__magic_name__      :       int       						= self.default_image_processor
							__magic_name__      :       List[str]       						= prepare_img()
							__magic_name__      :       Optional[Any]       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""pt"""			).to(lowerCAmelCase__			)

							# forward pass
							with torch.no_grad():
													__magic_name__      :       str       						= model(**lowerCAmelCase__			)

							# verify the logits
							__magic_name__      :       Dict       						= torch.Size((1, 10_00)			)
							self.assertEqual(outputs.logits.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       List[str]       						= torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]			).to(lowerCAmelCase__			)

							self.assertTrue(torch.allclose(outputs.logits[0, :3]      ,       lowerCAmelCase__      ,       atol=1e-4			)			)
	@slow
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Tuple       						= ViTModel.from_pretrained("""facebook/dino-vits8"""			).to(lowerCAmelCase__			)

							__magic_name__      :       Dict       						= ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""      ,       size=4_80			)
							__magic_name__      :       List[Any]       						= prepare_img()
							__magic_name__      :       Optional[int]       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""pt"""			)
							__magic_name__      :       str       						= inputs.pixel_values.to(lowerCAmelCase__			)

							# forward pass
							with torch.no_grad():
													__magic_name__      :       List[str]       						= model(lowerCAmelCase__      ,       interpolate_pos_encoding=lowerCAmelCase__			)

							# verify the logits
							__magic_name__      :       Optional[Any]       						= torch.Size((1, 36_01, 3_84)			)
							self.assertEqual(outputs.last_hidden_state.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       Optional[int]       						= torch.tensor(
							    [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]]			).to(lowerCAmelCase__			)

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







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

							__magic_name__      :       List[str]       						= prepare_img()
							__magic_name__      :       Optional[Any]       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""pt"""			)
							__magic_name__      :       Any       						= inputs.pixel_values.to(lowerCAmelCase__			)

							# forward pass to make sure inference works in fp16
							with torch.no_grad():
													__magic_name__      :       List[Any]       						= model(lowerCAmelCase__			)








import unittest

from transformers import is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow


if is_flax_available():
		import optax
		from flax.training.common_utils import onehot

		from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration
		from transformers.models.ta.modeling_flax_ta import shift_tokens_right





@require_torch
@require_sentencepiece
@require_tokenizers
@require_flax
class 	snake_case__ (							unittest.TestCase				):
	@slow
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       Any       						= FlaxMTaForConditionalGeneration.from_pretrained("""google/mt5-small"""			)
							__magic_name__      :       Dict       						= AutoTokenizer.from_pretrained("""google/mt5-small"""			)

							__magic_name__      :       Tuple       						= tokenizer("""Hello there"""      ,       return_tensors="""np"""			).input_ids
							__magic_name__      :       List[Any]       						= tokenizer("""Hi I am"""      ,       return_tensors="""np"""			).input_ids

							__magic_name__      :       Any       						= shift_tokens_right(lowerCAmelCase__      ,       model.config.pad_token_id      ,       model.config.decoder_start_token_id			)

							__magic_name__      :       List[Any]       						= model(lowerCAmelCase__      ,       decoder_input_ids=lowerCAmelCase__			).logits
							__magic_name__      :       Tuple       						= optax.softmax_cross_entropy(lowerCAmelCase__      ,       onehot(lowerCAmelCase__      ,       logits.shape[-1]			)			).mean()

							__magic_name__      :       List[Any]       						= -(labels.shape[-1] * loss.item())

							__magic_name__      :       List[Any]       						= -8_4.9_1_2_7
							self.assertTrue(abs(mtf_score - EXPECTED_SCORE			) < 1e-4			)
