





'''simple docstring'''






from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


A   : str             =			logging.get_logger(__name__)







class 			lowerCamelCase					(						__UpperCAmelCase  ):
					_SCREAMING_SNAKE_CASE							   =    ["pixel_values"]


					def __init__(					self	:  Optional[Any]       ,     __snake_case	:  bool = True       ,     __snake_case	:  Optional[Dict[str, int]] = None       ,     __snake_case	:  PILImageResampling = PILImageResampling.BILINEAR       ,     __snake_case	:  bool = True       ,     __snake_case	:  Dict[str, int] = None       ,     __snake_case	:  bool = True       ,     __snake_case	:  Union[int, float] = 1 / 2_55       ,     __snake_case	:  bool = True       ,     __snake_case	:  Optional[Union[float, List[float]]] = None       ,     __snake_case	:  Optional[Union[float, List[float]]] = None       ,     **__snake_case	:  Optional[int]       ,     ):





											'''simple docstring'''





											super().__init__(**__snake_case       )
											_snake_case:   Any  					=		size if size is not None else {'shortest_edge': 2_56}
											_snake_case:   int  					=		get_size_dict(__snake_case       ,     default_to_square=__snake_case       )
											_snake_case:   List[str]  					=		crop_size if crop_size is not None else {'height': 2_24, 'width': 2_24}
											_snake_case:   int  					=		get_size_dict(__snake_case       )
											_snake_case:   Dict  					=		do_resize
											_snake_case:   Any  					=		size
											_snake_case:   Union[str, Any]  					=		resample
											_snake_case:   List[Any]  					=		do_center_crop
											_snake_case:   Union[str, Any]  					=		crop_size
											_snake_case:   Dict  					=		do_rescale
											_snake_case:   Optional[int]  					=		rescale_factor
											_snake_case:   Optional[Any]  					=		do_normalize
											_snake_case:   Dict  					=		image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
											_snake_case:   Any  					=		image_std if image_std is not None else IMAGENET_STANDARD_STD


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  np.ndarray       ,     __snake_case	:  Dict[str, int]       ,     __snake_case	:  PILImageResampling = PILImageResampling.BICUBIC       ,     __snake_case	:  Optional[Union[str, ChannelDimension]] = None       ,     **__snake_case	:  Optional[Any]       ,     ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		get_size_dict(__snake_case       ,     default_to_square=__snake_case       )
											if "shortest_edge" not in size:
																	raise ValueError(f'''The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'''       )
											_snake_case:   List[str]  					=		get_resize_output_image_size(__snake_case       ,     size=size['shortest_edge']       ,     default_to_square=__snake_case       )
											return resize(__snake_case       ,     size=__snake_case       ,     resample=__snake_case       ,     data_format=__snake_case       ,     **__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ,     __snake_case	:  np.ndarray       ,     __snake_case	:  Dict[str, int]       ,     __snake_case	:  Optional[Union[str, ChannelDimension]] = None       ,     **__snake_case	:  List[Any]       ,     ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		get_size_dict(__snake_case       )
											return center_crop(__snake_case       ,     size=(size['height'], size['width'])       ,     data_format=__snake_case       ,     **__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ,     __snake_case	:  np.ndarray       ,     __snake_case	:  float       ,     __snake_case	:  Optional[Union[str, ChannelDimension]] = None       ,     **__snake_case	:  Optional[int]       ):





											'''simple docstring'''





											return rescale(__snake_case       ,     scale=__snake_case       ,     data_format=__snake_case       ,     **__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  np.ndarray       ,     __snake_case	:  Union[float, List[float]]       ,     __snake_case	:  Union[float, List[float]]       ,     __snake_case	:  Optional[Union[str, ChannelDimension]] = None       ,     **__snake_case	:  List[str]       ,     ):





											'''simple docstring'''





											return normalize(__snake_case       ,     mean=__snake_case       ,     std=__snake_case       ,     data_format=__snake_case       ,     **__snake_case       )




					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  ImageInput       ,     __snake_case	:  Optional[bool] = None       ,     __snake_case	:  Dict[str, int] = None       ,     __snake_case	:  PILImageResampling = None       ,     __snake_case	:  bool = None       ,     __snake_case	:  Dict[str, int] = None       ,     __snake_case	:  Optional[bool] = None       ,     __snake_case	:  Optional[float] = None       ,     __snake_case	:  Optional[bool] = None       ,     __snake_case	:  Optional[Union[float, List[float]]] = None       ,     __snake_case	:  Optional[Union[float, List[float]]] = None       ,     __snake_case	:  Optional[Union[str, TensorType]] = None       ,     __snake_case	:  Union[str, ChannelDimension] = ChannelDimension.FIRST       ,     **__snake_case	:  str       ,     ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		do_resize if do_resize is not None else self.do_resize
											_snake_case:   str  					=		size if size is not None else self.size
											_snake_case:   Optional[int]  					=		get_size_dict(__snake_case       ,     default_to_square=__snake_case       )
											_snake_case:   Optional[int]  					=		resample if resample is not None else self.resample
											_snake_case:   Tuple  					=		do_center_crop if do_center_crop is not None else self.do_center_crop
											_snake_case:   List[Any]  					=		crop_size if crop_size is not None else self.crop_size
											_snake_case:   Optional[Any]  					=		get_size_dict(__snake_case       )
											_snake_case:   str  					=		do_rescale if do_rescale is not None else self.do_rescale
											_snake_case:   Dict  					=		rescale_factor if rescale_factor is not None else self.rescale_factor
											_snake_case:   Optional[int]  					=		do_normalize if do_normalize is not None else self.do_normalize
											_snake_case:   Optional[int]  					=		image_mean if image_mean is not None else self.image_mean
											_snake_case:   Any  					=		image_std if image_std is not None else self.image_std

											_snake_case:   Optional[int]  					=		make_list_of_images(__snake_case       )

											if not valid_images(__snake_case       ):
																	raise ValueError(
																	    'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
																	    'torch.Tensor, tf.Tensor or jax.ndarray.'       )

											if do_resize and size is None:
																	raise ValueError('Size must be specified if do_resize is True.'       )

											if do_center_crop and crop_size is None:
																	raise ValueError('Crop size must be specified if do_center_crop is True.'       )

											if do_rescale and rescale_factor is None:
																	raise ValueError('Rescale factor must be specified if do_rescale is True.'       )

											if do_normalize and (image_mean is None or image_std is None):
																	raise ValueError('Image mean and std must be specified if do_normalize is True.'       )

											# All transformations expect numpy arrays.
											_snake_case:   List[Any]  					=		[to_numpy_array(__snake_case       ) for image in images]

											if do_resize:
																	_snake_case:   List[Any]  					=		[self.resize(image=__snake_case       ,     size=__snake_case       ,     resample=__snake_case       ) for image in images]

											if do_center_crop:
																	_snake_case:   Any  					=		[self.center_crop(image=__snake_case       ,     size=__snake_case       ) for image in images]

											if do_rescale:
																	_snake_case:   List[Any]  					=		[self.rescale(image=__snake_case       ,     scale=__snake_case       ) for image in images]

											if do_normalize:
																	_snake_case:   Any  					=		[self.normalize(image=__snake_case       ,     mean=__snake_case       ,     std=__snake_case       ) for image in images]

											_snake_case:   List[Any]  					=		[to_channel_dimension_format(__snake_case       ,     __snake_case       ) for image in images]

											_snake_case:   str  					=		{'pixel_values': images}
											return BatchFeature(data=__snake_case       ,     tensor_type=__snake_case       )











'''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 			lowerCamelCase					:


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





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		parent
											_snake_case:   Tuple  					=		batch_size
											_snake_case:   str  					=		image_size
											_snake_case:   int  					=		patch_size
											_snake_case:   Union[str, Any]  					=		num_channels
											_snake_case:   Dict  					=		is_training
											_snake_case:   Optional[Any]  					=		use_labels
											_snake_case:   Optional[Any]  					=		hidden_size
											_snake_case:   Tuple  					=		num_hidden_layers
											_snake_case:   List[Any]  					=		num_attention_heads
											_snake_case:   Union[str, Any]  					=		intermediate_size
											_snake_case:   List[str]  					=		hidden_act
											_snake_case:   Tuple  					=		hidden_dropout_prob
											_snake_case:   List[Any]  					=		attention_probs_dropout_prob
											_snake_case:   str  					=		type_sequence_label_size
											_snake_case:   Any  					=		initializer_range
											_snake_case:   str  					=		scope
											_snake_case:   Union[str, Any]  					=		encoder_stride

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

											_snake_case:   Union[str, Any]  					=		self.get_config()

											return config, pixel_values, labels


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											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=__snake_case       ,     initializer_range=self.initializer_range       ,     encoder_stride=self.encoder_stride       ,     )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ,     __snake_case	:  int       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		ViTModel(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Tuple  					=		model(__snake_case       )
											self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  int       ):





											'''simple docstring'''





											_snake_case:   int  					=		ViTForMaskedImageModeling(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Dict  					=		model(__snake_case       )
											self.parent.assertEqual(
											    result.reconstruction.shape       ,     (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

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

											_snake_case:   List[str]  					=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
											_snake_case:   Union[str, Any]  					=		model(__snake_case       )
											self.parent.assertEqual(result.reconstruction.shape       ,     (self.batch_size, 1, self.image_size, self.image_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		self.type_sequence_label_size
											_snake_case:   Union[str, Any]  					=		ViTForImageClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   List[Any]  					=		model(__snake_case       ,     labels=__snake_case       )
											self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.type_sequence_label_size)       )

											# test greyscale images
											_snake_case:   Tuple  					=		1
											_snake_case:   Optional[int]  					=		ViTForImageClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()

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




					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Any  					=		self.prepare_config_and_inputs()
											(
											    (
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						
											):   int  					=		config_and_inputs
											_snake_case:   Dict  					=		{'pixel_values': pixel_values}
											return config, inputs_dict







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

					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		ViTModelTester(self       )
											_snake_case:   Union[str, Any]  					=		ConfigTester(self       ,     config_class=__snake_case       ,     has_text_modality=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					@unittest.skip(reason='ViT does not use inputs_embeds'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   Dict  					=		self.model_tester.prepare_config_and_inputs_for_common()

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_snake_case:   str  					=		['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,     __snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   int  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__snake_case       )




					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_snake_case:   Any  					=		ViTModel.from_pretrained(__snake_case       )
																	self.assertIsNotNone(__snake_case       )





def       lowercase_      (		)   ->List[Any]:
						_snake_case:   Dict  					=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image







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


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'       ) if is_vision_available() else None


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'       ).to(__snake_case       )

											_snake_case:   Dict  					=		self.default_image_processor
											_snake_case:   Optional[Any]  					=		prepare_img()
											_snake_case:   List[str]  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       ).to(__snake_case       )

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

											# verify the logits
											_snake_case:   Union[str, Any]  					=		torch.Size((1, 10_00)       )
											self.assertEqual(outputs.logits.shape       ,     __snake_case       )

											_snake_case:   Dict  					=		torch.tensor([-0.2_744, 0.8_215, -0.0_836]       ).to(__snake_case       )

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


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		ViTModel.from_pretrained('facebook/dino-vits8'       ).to(__snake_case       )

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

											# forward pass
											with torch.no_grad():
																	_snake_case:   str  					=		model(__snake_case       ,     interpolate_pos_encoding=__snake_case       )

											# verify the logits
											_snake_case:   List[str]  					=		torch.Size((1, 36_01, 3_84)       )
											self.assertEqual(outputs.last_hidden_state.shape       ,     __snake_case       )

											_snake_case:   Any  					=		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(__snake_case       )

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




					@slow
					@require_accelerate
					@require_torch_gpu
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		ViTModel.from_pretrained('facebook/dino-vits8'       ,     torch_dtype=torch.floataa       ,     device_map='auto'       )
											_snake_case:   Dict  					=		self.default_image_processor

											_snake_case:   Any  					=		prepare_img()
											_snake_case:   str  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       )
											_snake_case:   Any  					=		inputs.pixel_values.to(__snake_case       )

											# forward pass to make sure inference works in fp16
											with torch.no_grad():
																	_snake_case:   int  					=		model(__snake_case       )





