





from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
	import tensorflow as tf

	from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
	from PIL import Image

	from transformers import ViTImageProcessor



class 					__lowerCAmelCase       :






			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__=2					,							__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__=3					,							__magic_name__=None					,							)     ->   Any:


							'''simple docstring'''



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

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






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


							'''simple docstring'''



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

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

							snake_case_						:    Optional[Any]				=  self.get_config()

							return config, pixel_values, labels






			def 			lowerCamelCase  (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=__magic_name__					,							initializer_range=self.initializer_range					,							)






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   Dict:


							'''simple docstring'''



							snake_case_						:    Any				=  TFViTModel(config=__magic_name__    )
							snake_case_						:    List[Any]				=  model(__magic_name__					,							training=__magic_name__    )
							self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, self.seq_length, self.hidden_size)    )

							# Test with an image with different size than the one specified in config.
							snake_case_						:    List[Any]				=  self.image_size // 2
							snake_case_						:    Union[str, Any]				=  pixel_values[:, :, :image_size, :image_size]
							snake_case_						:    Tuple				=  model(__magic_name__					,							interpolate_pos_encoding=__magic_name__					,							training=__magic_name__    )
							snake_case_						:    Optional[int]				=  (image_size // self.patch_size) ** 2 + 1
							self.parent.assertEqual(result.last_hidden_state.shape					,							(self.batch_size, seq_length, self.hidden_size)    )






			def 			lowerCamelCase  (self					,							__magic_name__					,							__magic_name__					,							__magic_name__    )     ->   str:


							'''simple docstring'''



							snake_case_						:    List[Any]				=  self.type_sequence_label_size
							snake_case_						:    int				=  TFViTForImageClassification(__magic_name__    )
							snake_case_						:    Any				=  model(__magic_name__					,							labels=__magic_name__					,							training=__magic_name__    )
							self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)    )

							# Test with an image with different size than the one specified in config.
							snake_case_						:    List[str]				=  self.image_size // 2
							snake_case_						:    str				=  pixel_values[:, :, :image_size, :image_size]
							snake_case_						:    Optional[Any]				=  model(__magic_name__					,							interpolate_pos_encoding=__magic_name__					,							training=__magic_name__    )
							self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)    )

							# test greyscale images
							snake_case_						:    int				=  1
							snake_case_						:    Union[str, Any]				=  TFViTForImageClassification(__magic_name__    )
							snake_case_						:    Tuple				=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
							snake_case_						:    Dict				=  model(__magic_name__    )
							self.parent.assertEqual(result.logits.shape					,							(self.batch_size, self.type_sequence_label_size)    )






			def 			lowerCamelCase  (self    )     ->   Dict:


							'''simple docstring'''



							snake_case_						:    List[str]				=  self.prepare_config_and_inputs()
							snake_case_			,							snake_case_			,							snake_case_						:    str				=  config_and_inputs
							snake_case_						:    int				=  {'''pixel_values''': pixel_values}
							return config, inputs_dict




@require_tf
class 					__lowerCAmelCase       (			lowercase_,     lowercase_,     unittest.TestCase     ):
			lowerCamelCase_     :     Optional[Any]       			=      (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
			lowerCamelCase_     :     Tuple       			=      (
			    {"""feature-extraction""": TFViTModel, """image-classification""": TFViTForImageClassification}
			    if is_tf_available()
			    else {}
			)

			lowerCamelCase_     :     Optional[int]       			=      False
			lowerCamelCase_     :     Any       			=      False
			lowerCamelCase_     :     List[str]       			=      False






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


							'''simple docstring'''



							snake_case_						:    List[Any]				=  TFViTModelTester(self    )
							snake_case_						:    List[Any]				=  ConfigTester(self					,							config_class=__magic_name__					,							has_text_modality=__magic_name__					,							hidden_size=37    )






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


							'''simple docstring'''



							self.config_tester.run_common_tests()






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


							'''simple docstring'''



							pass






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


							'''simple docstring'''



							pass






			def 			lowerCamelCase  (self    )     ->   Dict:


							'''simple docstring'''



							snake_case_			,							snake_case_						:    int				=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											snake_case_						:    str				=  model_class(__magic_name__    )
											self.assertIsInstance(model.get_input_embeddings()					,							(tf.keras.layers.Layer)    )
											snake_case_						:    int				=  model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(__magic_name__					,							tf.keras.layers.Layer    )    )






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


							'''simple docstring'''



							snake_case_			,							snake_case_						:    Tuple				=  self.model_tester.prepare_config_and_inputs_for_common()

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

											snake_case_						:    List[str]				=  ['''pixel_values''']
											self.assertListEqual(arg_names[:1]					,							__magic_name__    )






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


							'''simple docstring'''



							snake_case_						:    str				=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__magic_name__    )






			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    int				=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__magic_name__    )






			@slow
			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    int				=  TFViTModel.from_pretrained('''google/vit-base-patch16-224'''    )
							self.assertIsNotNone(__magic_name__    )






def      lowerCamelCase_						(				)		->						List[Any]:






				"""simple docstring"""


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





@require_tf
@require_vision
class 					__lowerCAmelCase       (			unittest.TestCase     ):






			@cached_property
			def 			lowerCamelCase  (self    )     ->   Optional[int]:


							'''simple docstring'''



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






			@slow
			def 			lowerCamelCase  (self    )     ->   Any:


							'''simple docstring'''



							snake_case_						:    str				=  TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''    )

							snake_case_						:    int				=  self.default_image_processor
							snake_case_						:    str				=  prepare_img()
							snake_case_						:    str				=  image_processor(images=__magic_name__					,							return_tensors='''tf'''    )

							# forward pass
							snake_case_						:    Tuple				=  model(**__magic_name__    )

							# verify the logits
							snake_case_						:    Optional[Any]				=  tf.TensorShape((1, 1000)    )
							self.assertEqual(outputs.logits.shape					,							__magic_name__    )

							snake_case_						:    List[Any]				=  tf.constant([-0.2_744, 0.8_215, -0.0_836]    )

							tf.debugging.assert_near(outputs.logits[0, :3]					,							__magic_name__					,							atol=1e-4    )




'''simple docstring'''

from ....utils import logging


lowerCamelCase							:   Optional[Any]  						=	logging.get_logger(__name__)
class   __lowerCAmelCase						(lowercase_     ):





      '''simple docstring'''






      def __init__(self    :    Optional[int]   ,						UpperCamelCase    :    Union[str, Any]   ,						UpperCamelCase    :    Optional[Any]=None   ,						UpperCamelCase    :    int=2048 ):

             '''simple docstring'''







             lowercase__      			= config.__dict__
             lowercase__      			= modal_hidden_size
             if num_labels:
                    lowercase__      			= num_labels




