


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


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

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


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Dict          =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

            lowercase	:      str          =						self.get_config()

            return config, pixel_values, labels


      def 				__lowerCamelCase	(							self						):
            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							,  )


      def 				__lowerCamelCase	(							self							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
            lowercase	:      Optional[int]          =						TFViTModel(config=__UpperCamelCase						)
            lowercase	:      List[Any]          =						model(__UpperCamelCase							,  training=__UpperCamelCase						)
            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.
            lowercase	:      Optional[int]          =						self.image_size // 2
            lowercase	:      Union[str, Any]          =						pixel_values[:, :, :image_size, :image_size]
            lowercase	:      Dict          =						model(__UpperCamelCase							,  interpolate_pos_encoding=__UpperCamelCase							,  training=__UpperCamelCase						)
            lowercase	:      List[str]          =						(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							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
            lowercase	:      Tuple          =						self.type_sequence_label_size
            lowercase	:      Dict          =						TFViTForImageClassification(__UpperCamelCase						)
            lowercase	:      Dict          =						model(__UpperCamelCase							,  labels=__UpperCamelCase							,  training=__UpperCamelCase						)
            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.
            lowercase	:      Optional[int]          =						self.image_size // 2
            lowercase	:      Any          =						pixel_values[:, :, :image_size, :image_size]
            lowercase	:      Optional[Any]          =						model(__UpperCamelCase							,  interpolate_pos_encoding=__UpperCamelCase							,  training=__UpperCamelCase						)
            self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.type_sequence_label_size)						)

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






      def 				__lowerCamelCase	(							self						):
            lowercase	:      Tuple          =						self.prepare_config_and_inputs()
            lowercase	:      int          =						config_and_inputs
            lowercase	:      str          =						{'pixel_values': pixel_values}
            return config, inputs_dict







@require_tf
class  __SCREAMING_SNAKE_CASE      (	lowercase_     ,  lowercase_     ,  unittest.TestCase      ):
      A :							Optional[int]										=   (TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      A :							Dict										=   (
          {'feature-extraction': TFViTModel, 'image-classification': TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

      A :							str										=   False
      A :							Union[str, Any]										=   False
      A :							List[str]										=   False


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Tuple          =						TFViTModelTester(self						)
            lowercase	:      int          =						ConfigTester(self							,  config_class=__UpperCamelCase							,  has_text_modality=__UpperCamelCase							,  hidden_size=37						)


      def 				__lowerCamelCase	(							self						):
            self.config_tester.run_common_tests()


      @unittest.skip(reason='''ViT does not use inputs_embeds'''						)
      def 				__lowerCamelCase	(							self						):
            pass


      @unittest.skip(reason='''ViT does not use inputs_embeds'''						)
      def 				__lowerCamelCase	(							self						):
            pass


      def 				__lowerCamelCase	(							self						):
            lowercase	:      List[str]          =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  lowercase	:      List[Any]          =						model_class(__UpperCamelCase						)
                  self.assertIsInstance(model.get_input_embeddings()							,  (tf.keras.layers.Layer)						)
                  lowercase	:      Optional[int]          =						model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(__UpperCamelCase							,  tf.keras.layers.Layer						)						)


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Union[str, Any]          =						self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  lowercase	:      str          =						model_class(__UpperCamelCase						)
                  lowercase	:      Dict          =						inspect.signature(model.call						)
                  # signature.parameters is an OrderedDict => so arg_names order is deterministic
                  lowercase	:      List[Any]          =						[*signature.parameters.keys()]

                  lowercase	:      Dict          =						['pixel_values']
                  self.assertListEqual(arg_names[:1]							,  __UpperCamelCase						)


      def 				__lowerCamelCase	(							self						):
            lowercase	:      List[str]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__UpperCamelCase						)


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Dict          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase						)






      @slow
      def 				__lowerCamelCase	(							self						):
            lowercase	:      List[str]          =						TFViTModel.from_pretrained('''google/vit-base-patch16-224'''						)
            self.assertIsNotNone(__UpperCamelCase						)





def 	__lowercase		(  )			->Dict:







      """simple docstring"""

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







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


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






      @slow
      def 				__lowerCamelCase	(							self						):
            lowercase	:      List[str]          =						TFViTForImageClassification.from_pretrained('''google/vit-base-patch16-224'''						)

            lowercase	:      Union[str, Any]          =						self.default_image_processor
            lowercase	:      str          =						prepare_img()
            lowercase	:      Union[str, Any]          =						image_processor(images=__UpperCamelCase							,  return_tensors='''tf'''						)

            # forward pass
            lowercase	:      str          =						model(**__UpperCamelCase						)

            # verify the logits
            lowercase	:      Optional[int]          =						tf.TensorShape((1, 1000)						)
            self.assertEqual(outputs.logits.shape							,  __UpperCamelCase						)

            lowercase	:      Any          =						tf.constant([-0.2744, 0.8215, -0.0836]						)

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


"""simple docstring"""







import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
       import jax

       from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel







class        UpperCamelCase		(			unittest.TestCase  ):
   def __init__(			self     ,__UpperCamelCase     ,__UpperCamelCase=13     ,__UpperCamelCase=30     ,__UpperCamelCase=2     ,__UpperCamelCase=3     ,__UpperCamelCase=True     ,__UpperCamelCase=True     ,__UpperCamelCase=32     ,__UpperCamelCase=5     ,__UpperCamelCase=4     ,__UpperCamelCase=37     ,__UpperCamelCase="gelu"     ,__UpperCamelCase=0.1     ,__UpperCamelCase=0.1     ,__UpperCamelCase=10     ,__UpperCamelCase=0.02     ,)	->      Tuple:


        '''simple docstring'''


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

        # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        lowercase_	:				str													=	(image_size // patch_size) ** 2
        lowercase_	:				Optional[int]													=	num_patches + 1
   def 			_UpperCAmelCase   (			self			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Tuple													=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        lowercase_	:				List[Any]													=	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     ,)

        return config, pixel_values
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Dict:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	FlaxViTModel(config=__UpperCamelCase			)
        lowercase_	:				Dict													=	model(__UpperCamelCase			)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
        lowercase_	:				Union[str, Any]													=	(self.image_size, self.image_size)
        lowercase_	:				List[Any]													=	(self.patch_size, self.patch_size)
        lowercase_	:				List[str]													=	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
        self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, num_patches + 1, self.hidden_size)			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	self.type_sequence_label_size
        lowercase_	:				str													=	FlaxViTForImageClassification(config=__UpperCamelCase			)
        lowercase_	:				Optional[Any]													=	model(__UpperCamelCase			)
        self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size)			)

        # test greyscale images
        lowercase_	:				Union[str, Any]													=	1
        lowercase_	:				Optional[int]													=	FlaxViTForImageClassification(__UpperCamelCase			)

        lowercase_	:				List[Any]													=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]			)
        lowercase_	:				str													=	model(__UpperCamelCase			)







   def 			_UpperCAmelCase   (			self			)	->      Any:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	self.prepare_config_and_inputs()
        (
            (
            lowercase_
        )							,  (
            lowercase_
        )							,  
        )	:				List[Any]													=	config_and_inputs
        lowercase_	:				Tuple													=	{'pixel_values': pixel_values}
        return config, inputs_dict







@require_flax
class        UpperCamelCase		(			lowercase_						,      unittest.TestCase  ):
   lowercase							=  (FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()
   def 			_UpperCAmelCase   (			self			)	->      None:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	FlaxViTModelTester(self			)
        lowercase_	:				Union[str, Any]													=	ConfigTester(self     ,config_class=__UpperCamelCase     ,has_text_modality=__UpperCamelCase     ,hidden_size=37			)
   def 			_UpperCAmelCase   (			self			)	->      List[str]:


        '''simple docstring'''


        self.config_tester.run_common_tests()
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				Optional[Any]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      List[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Any													=	self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_	:				str													=	['pixel_values']
             self.assertListEqual(arg_names[:1]     ,__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				str													=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             with self.subTest(model_class.__name__			):
                  lowercase_	:				Optional[Any]													=	self._prepare_for_class(__UpperCamelCase     ,__UpperCamelCase			)
                  lowercase_	:				Dict													=	model_class(__UpperCamelCase			)

                  @jax.jit
                  def model_jitted(__UpperCamelCase     ,**__UpperCamelCase			):
                       return model(pixel_values=__UpperCamelCase     ,**__UpperCamelCase			)

                  with self.subTest('JIT Enabled'			):
                       lowercase_	:				Optional[int]													=	model_jitted(**__UpperCamelCase			).to_tuple()

                  with self.subTest('JIT Disabled'			):
                       with jax.disable_jit():
                            lowercase_	:				List[str]													=	model_jitted(**__UpperCamelCase			).to_tuple()

                  self.assertEqual(len(__UpperCamelCase			)     ,len(__UpperCamelCase			)			)
                  for jitted_output, output in zip(__UpperCamelCase     ,__UpperCamelCase			):
                       self.assertEqual(jitted_output.shape     ,output.shape			)







   @slow
   def 			_UpperCAmelCase   (			self			)	->      Optional[int]:


        '''simple docstring'''


        for model_class_name in self.all_model_classes:
             lowercase_	:				Optional[int]													=	model_class_name.from_pretrained('google/vit-base-patch16-224'			)
             lowercase_	:				int													=	model(np.ones((1, 3, 224, 224)			)			)
             self.assertIsNotNone(__UpperCamelCase			)

