





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

			'''simple docstring'''


			def __init__(					self,	__magic_name__,	__magic_name__=13,	__magic_name__=30,	__magic_name__=2,	__magic_name__=3,	__magic_name__=True,	__magic_name__=True,	__magic_name__=32,	__magic_name__=5,	__magic_name__=4,	__magic_name__=37,	__magic_name__="gelu",	__magic_name__=0.1,	__magic_name__=0.1,	__magic_name__=10,	__magic_name__=0.02,	__magic_name__=None,	__magic_name__=2,	)				->   List[str]:






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

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




			def    UpperCamelCase__						(					self							)				->   Any:






							"""simple docstring"""
							UpperCamelCase__							:       Tuple      =   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

							UpperCamelCase__							:       List[str]      =   self.get_config()

							return config, pixel_values, labels




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






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




			def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   List[str]:






							"""simple docstring"""
							UpperCamelCase__							:       Dict      =   ViTModel(config=__magic_name__							)
							model.to(__magic_name__							)
							model.eval()
							UpperCamelCase__							:       Dict      =   model(__magic_name__							)
							self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)							)




			def    UpperCamelCase__						(					self,	__magic_name__,	__magic_name__,	__magic_name__							)				->   Optional[int]:






							"""simple docstring"""
							UpperCamelCase__							:       str      =   ViTForMaskedImageModeling(config=__magic_name__							)
							model.to(__magic_name__							)
							model.eval()
							UpperCamelCase__							:       Optional[Any]      =   model(__magic_name__							)
							self.parent.assertEqual(
							    result.reconstruction.shape,	(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

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

							UpperCamelCase__							:       Union[str, Any]      =   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
							UpperCamelCase__							:       int      =   model(__magic_name__							)
							self.parent.assertEqual(result.reconstruction.shape,	(self.batch_size, 1, self.image_size, self.image_size)							)




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






							"""simple docstring"""
							UpperCamelCase__							:       Optional[int]      =   self.type_sequence_label_size
							UpperCamelCase__							:       Tuple      =   ViTForImageClassification(__magic_name__							)
							model.to(__magic_name__							)
							model.eval()
							UpperCamelCase__							:       Optional[int]      =   model(__magic_name__,	labels=__magic_name__							)
							self.parent.assertEqual(result.logits.shape,	(self.batch_size, self.type_sequence_label_size)							)

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

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




			def    UpperCamelCase__						(					self							)				->   str:






							"""simple docstring"""
							UpperCamelCase__							:       Union[str, Any]      =   self.prepare_config_and_inputs()
							(
							    (
							    UpperCamelCase__       
							)     ,(
							    UpperCamelCase__       
							)     ,(
							    UpperCamelCase__       
							)     ,       
							)							:       Optional[Any]      =   config_and_inputs
							UpperCamelCase__							:       Tuple      =   {'''pixel_values''': pixel_values}
							return config, inputs_dict






@require_torch
class 					lowercase__ (			UpperCamelCase__    ,       UpperCamelCase__    ,       unittest.TestCase       ):

			'''simple docstring'''


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

			a		:							Optional[Any]     	=	False
			a		:							List[Any]     	=	False
			a		:							str     	=	False




			def    UpperCamelCase__						(					self							)				->   Optional[Any]:






							"""simple docstring"""
							UpperCamelCase__							:       Dict      =   ViTModelTester(self							)
							UpperCamelCase__							:       Optional[Any]      =   ConfigTester(self,	config_class=__magic_name__,	has_text_modality=__magic_name__,	hidden_size=37							)




			def    UpperCamelCase__						(					self							)				->   Optional[int]:






							"""simple docstring"""
							self.config_tester.run_common_tests()




			@unittest.skip(reason='''ViT does not use inputs_embeds'''							)
			def    UpperCamelCase__						(					self							)				->   str:






							"""simple docstring"""
							pass




			def    UpperCamelCase__						(					self							)				->   Any:






							"""simple docstring"""
							UpperCamelCase__     ,UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs_for_common()

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




			def    UpperCamelCase__						(					self							)				->   Tuple:






							"""simple docstring"""
							UpperCamelCase__     ,UpperCamelCase__							:       Union[str, Any]      =   self.model_tester.prepare_config_and_inputs_for_common()

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

											UpperCamelCase__							:       Tuple      =   ['''pixel_values''']
											self.assertListEqual(arg_names[:1],	__magic_name__							)




			def    UpperCamelCase__						(					self							)				->   Tuple:






							"""simple docstring"""
							UpperCamelCase__							:       Union[str, Any]      =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__magic_name__							)




			def    UpperCamelCase__						(					self							)				->   Optional[Any]:






							"""simple docstring"""
							UpperCamelCase__							:       str      =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_masked_image_modeling(*__magic_name__							)




			def    UpperCamelCase__						(					self							)				->   List[Any]:






							"""simple docstring"""
							UpperCamelCase__							:       Dict      =   self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__magic_name__							)




			@slow
			def    UpperCamelCase__						(					self							)				->   str:






							"""simple docstring"""
							for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCamelCase__							:       Optional[int]      =   ViTModel.from_pretrained(__magic_name__							)
											self.assertIsNotNone(__magic_name__							)




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






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

			'''simple docstring'''


			@cached_property
			def    UpperCamelCase__						(					self							)				->   Any:






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




			@slow
			def    UpperCamelCase__						(					self							)				->   List[str]:






							"""simple docstring"""
							UpperCamelCase__							:       str      =   ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''							).to(__magic_name__							)

							UpperCamelCase__							:       Union[str, Any]      =   self.default_image_processor
							UpperCamelCase__							:       Union[str, Any]      =   prepare_img()
							UpperCamelCase__							:       Any      =   image_processor(images=__magic_name__,	return_tensors='''pt'''							).to(__magic_name__							)

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

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

							UpperCamelCase__							:       Optional[int]      =   torch.tensor([-0.2744, 0.8215, -0.0836]							).to(__magic_name__							)

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




			@slow
			def    UpperCamelCase__						(					self							)				->   Any:






							"""simple docstring"""
							# 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.
							UpperCamelCase__							:       Dict      =   ViTModel.from_pretrained('''facebook/dino-vits8'''							).to(__magic_name__							)

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

							# forward pass
							with torch.no_grad():
											UpperCamelCase__							:       Dict      =   model(__magic_name__,	interpolate_pos_encoding=__magic_name__							)

							# verify the logits
							UpperCamelCase__							:       List[Any]      =   torch.Size((1, 3601, 384)							)
							self.assertEqual(outputs.last_hidden_state.shape,	__magic_name__							)

							UpperCamelCase__							:       Dict      =   torch.tensor(
							    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]							).to(__magic_name__							)

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




			@slow
			@require_accelerate
			@require_torch_gpu
			def    UpperCamelCase__						(					self							)				->   List[str]:






							"""simple docstring"""
							UpperCamelCase__							:       Dict      =   ViTModel.from_pretrained('''facebook/dino-vits8''',	torch_dtype=torch.floataa,	device_map='''auto'''							)
							UpperCamelCase__							:       Optional[int]      =   self.default_image_processor

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

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








from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCAmelCase_  							=				{
    'configuration_informer': [
        'INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'InformerConfig',
    ],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase_  							=				[
      'INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
      'InformerForPrediction',
      'InformerModel',
      'InformerPreTrainedModel',
  ]


if TYPE_CHECKING:
  from .configuration_informer import INFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, InformerConfig

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_informer import (
        INFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
        InformerForPrediction,
        InformerModel,
        InformerPreTrainedModel,
    )

else:
  import sys

  UpperCAmelCase_  							=				_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

