






'''simple docstring'''







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 _lowercase	:




							def __init__(							self:				List[Any]			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				Any=13			,							UpperCamelCase__:				Optional[Any]=30			,							UpperCamelCase__:				Dict=2			,							UpperCamelCase__:				Tuple=3			,							UpperCamelCase__:				Optional[Any]=True			,							UpperCamelCase__:				Optional[Any]=True			,							UpperCamelCase__:				Optional[Any]=32			,							UpperCamelCase__:				Optional[int]=5			,							UpperCamelCase__:				Dict=4			,							UpperCamelCase__:				Optional[Any]=37			,							UpperCamelCase__:				List[str]="gelu"			,							UpperCamelCase__:				str=0.1			,							UpperCamelCase__:				Dict=0.1			,							UpperCamelCase__:				Dict=10			,							UpperCamelCase__:				Tuple=0.02			,							UpperCamelCase__:				Optional[int]=None			,							UpperCamelCase__:				int=2			,							):
														lowerCamelCase__					:	Any         =       parent
														lowerCamelCase__					:	List[str]         =       batch_size
														lowerCamelCase__					:	int         =       image_size
														lowerCamelCase__					:	str         =       patch_size
														lowerCamelCase__					:	Optional[Any]         =       num_channels
														lowerCamelCase__					:	int         =       is_training
														lowerCamelCase__					:	Union[str, Any]         =       use_labels
														lowerCamelCase__					:	Dict         =       hidden_size
														lowerCamelCase__					:	str         =       num_hidden_layers
														lowerCamelCase__					:	List[Any]         =       num_attention_heads
														lowerCamelCase__					:	int         =       intermediate_size
														lowerCamelCase__					:	Union[str, Any]         =       hidden_act
														lowerCamelCase__					:	Optional[Any]         =       hidden_dropout_prob
														lowerCamelCase__					:	List[Any]         =       attention_probs_dropout_prob
														lowerCamelCase__					:	Tuple         =       type_sequence_label_size
														lowerCamelCase__					:	Any         =       initializer_range
														lowerCamelCase__					:	int         =       scope
														lowerCamelCase__					:	Optional[int]         =       encoder_stride

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




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__					:	Optional[int]         =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

														lowerCamelCase__					:	List[str]         =       None
														if self.use_labels:
																					lowerCamelCase__					:	Optional[int]         =       ids_tensor([self.batch_size]			,							self.type_sequence_label_size     )

														lowerCamelCase__					:	Tuple         =       self.get_config()

														return config, pixel_values, labels




							def 		lowerCamelCase_				(							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=UpperCamelCase__			,							initializer_range=self.initializer_range			,							encoder_stride=self.encoder_stride			,							)




							def 		lowerCamelCase_				(							self:				Dict			,							UpperCamelCase__:				int			,							UpperCamelCase__:				List[Any]			,							UpperCamelCase__:				Any     ):
														lowerCamelCase__					:	Union[str, Any]         =       ViTModel(config=UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	Dict         =       model(UpperCamelCase__     )
														self.parent.assertEqual(result.last_hidden_state.shape			,							(self.batch_size, self.seq_length, self.hidden_size)     )




							def 		lowerCamelCase_				(							self:				Any			,							UpperCamelCase__:				Tuple			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Any     ):
														lowerCamelCase__					:	Union[str, Any]         =       ViTForMaskedImageModeling(config=UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	List[str]         =       model(UpperCamelCase__     )
														self.parent.assertEqual(
														    result.reconstruction.shape			,							(self.batch_size, self.num_channels, self.image_size, self.image_size)     )

														# test greyscale images
														lowerCamelCase__					:	Dict         =       1
														lowerCamelCase__					:	Optional[int]         =       ViTForMaskedImageModeling(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()

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




							def 		lowerCamelCase_				(							self:				Optional[int]			,							UpperCamelCase__:				Any			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Union[str, Any]     ):
														lowerCamelCase__					:	List[Any]         =       self.type_sequence_label_size
														lowerCamelCase__					:	Tuple         =       ViTForImageClassification(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()
														lowerCamelCase__					:	Optional[int]         =       model(UpperCamelCase__			,							labels=UpperCamelCase__     )
														self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.type_sequence_label_size)     )

														# test greyscale images
														lowerCamelCase__					:	Dict         =       1
														lowerCamelCase__					:	Optional[Any]         =       ViTForImageClassification(UpperCamelCase__     )
														model.to(UpperCamelCase__     )
														model.eval()

														lowerCamelCase__					:	Union[str, Any]         =       floats_tensor([self.batch_size, 1, self.image_size, self.image_size]     )
														lowerCamelCase__					:	str         =       model(UpperCamelCase__     )
														self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.type_sequence_label_size)     )




							def 		lowerCamelCase_				(							self:				List[Any]     ):
														lowerCamelCase__					:	int         =       self.prepare_config_and_inputs()
														(
														    (
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		(
														    lowerCamelCase__
														)  ,		
														)					:	str         =       config_and_inputs
														lowerCamelCase__					:	str         =       {"""pixel_values""": pixel_values}
														return config, inputs_dict



@require_torch
class _lowercase	(				_lowercase				,      _lowercase				,      unittest.TestCase		):
							a				      =       (
							    (
							        ViTModel,
							        ViTForImageClassification,
							        ViTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							a				      =       (
							    {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
							    if is_torch_available()
							    else {}
							)
							a				      =       True

							a				      =       False
							a				      =       False
							a				      =       False




							def 		lowerCamelCase_				(							self:				Tuple     ):
														lowerCamelCase__					:	Any         =       ViTModelTester(self     )
														lowerCamelCase__					:	Optional[int]         =       ConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__			,							hidden_size=37     )




							def 		lowerCamelCase_				(							self:				Any     ):
														self.config_tester.run_common_tests()




							@unittest.skip(reason="""ViT does not use inputs_embeds"""     )
							def 		lowerCamelCase_				(							self:				int     ):
														pass




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	List[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()

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




							def 		lowerCamelCase_				(							self:				str     ):
														lowerCamelCase__  ,		lowerCamelCase__					:	List[Any]         =       self.model_tester.prepare_config_and_inputs_for_common()

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

																					lowerCamelCase__					:	List[str]         =       ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]			,							UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	str         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Tuple     ):
														lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_masked_image_modeling(*UpperCamelCase__     )




							def 		lowerCamelCase_				(							self:				Dict     ):
														lowerCamelCase__					:	Any         =       self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__     )




							@slow
							def 		lowerCamelCase_				(							self:				Union[str, Any]     ):
														for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					lowerCamelCase__					:	List[str]         =       ViTModel.from_pretrained(UpperCamelCase__     )
																					self.assertIsNotNone(UpperCamelCase__     )





def  SCREAMING_SNAKE_CASE_       ()      ->       Optional[int]:
							lowerCamelCase__					:	int         =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
							return image



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




							@cached_property
							def 		lowerCamelCase_				(							self:				Dict     ):
														return ViTImageProcessor.from_pretrained("""google/vit-base-patch16-224"""     ) if is_vision_available() else None




							@slow
							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	List[str]         =       ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""     ).to(UpperCamelCase__     )

														lowerCamelCase__					:	Optional[Any]         =       self.default_image_processor
														lowerCamelCase__					:	Any         =       prepare_img()
														lowerCamelCase__					:	str         =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""     ).to(UpperCamelCase__     )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__					:	Optional[int]         =       model(**UpperCamelCase__     )

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

														lowerCamelCase__					:	Any         =       torch.tensor([-0.2_744, 0.8_215, -0.0_836]     ).to(UpperCamelCase__     )

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




							@slow
							def 		lowerCamelCase_				(							self:				Dict     ):
														# 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.
														lowerCamelCase__					:	List[Any]         =       ViTModel.from_pretrained("""facebook/dino-vits8"""     ).to(UpperCamelCase__     )

														lowerCamelCase__					:	List[str]         =       ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""			,							size=480     )
														lowerCamelCase__					:	Optional[int]         =       prepare_img()
														lowerCamelCase__					:	str         =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""     )
														lowerCamelCase__					:	Optional[int]         =       inputs.pixel_values.to(UpperCamelCase__     )

														# forward pass
														with torch.no_grad():
																					lowerCamelCase__					:	int         =       model(UpperCamelCase__			,							interpolate_pos_encoding=UpperCamelCase__     )

														# verify the logits
														lowerCamelCase__					:	Optional[Any]         =       torch.Size((1, 3_601, 384)     )
														self.assertEqual(outputs.last_hidden_state.shape			,							UpperCamelCase__     )

														lowerCamelCase__					:	int         =       torch.tensor(
														    [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]]     ).to(UpperCamelCase__     )

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




							@slow
							@require_accelerate
							@require_torch_gpu
							def 		lowerCamelCase_				(							self:				int     ):
														lowerCamelCase__					:	str         =       ViTModel.from_pretrained("""facebook/dino-vits8"""			,							torch_dtype=torch.floataa			,							device_map="""auto"""     )
														lowerCamelCase__					:	int         =       self.default_image_processor

														lowerCamelCase__					:	str         =       prepare_img()
														lowerCamelCase__					:	Dict         =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""     )
														lowerCamelCase__					:	Dict         =       inputs.pixel_values.to(UpperCamelCase__     )

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




'''simple docstring'''
lowerCamelCase :      Any					 =     "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"

lowerCamelCase :      int					 =     [{"type": "code", "content": INSTALL_CONTENT}]
lowerCamelCase :      str					 =     {
    "{processor_class}": "FakeProcessorClass",
    "{model_class}": "FakeModelClass",
    "{object_class}": "FakeObjectClass",
}
