


import inspect
import unittest

from transformers import SegformerConfig, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

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 transformers import (
      MODEL_MAPPING,
      SegformerForImageClassification,
      SegformerForSemanticSegmentation,
      SegformerModel,
  )
  from transformers.models.segformer.modeling_segformer import SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import SegformerImageProcessor







class  __SCREAMING_SNAKE_CASE      (	lowercase_      ):


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Any          =						self.config_class(**self.inputs_dict						)
            self.parent.assertTrue(hasattr(__UpperCamelCase							,  '''hidden_sizes'''						)						)
            self.parent.assertTrue(hasattr(__UpperCamelCase							,  '''num_attention_heads'''						)						)
            self.parent.assertTrue(hasattr(__UpperCamelCase							,  '''num_encoder_blocks'''						)						)







class  __SCREAMING_SNAKE_CASE      :


      def __init__(							self							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__=13							,  SCREAMING_SNAKE_CASE__=64							,  SCREAMING_SNAKE_CASE__=3							,  SCREAMING_SNAKE_CASE__=4							,  SCREAMING_SNAKE_CASE__=[2, 2, 2, 2]							,  SCREAMING_SNAKE_CASE__=[8, 4, 2, 1]							,  SCREAMING_SNAKE_CASE__=[16, 32, 64, 128]							,  SCREAMING_SNAKE_CASE__=[1, 4, 8, 16]							,  SCREAMING_SNAKE_CASE__=[1, 2, 4, 8]							,  SCREAMING_SNAKE_CASE__=True							,  SCREAMING_SNAKE_CASE__=True							,  SCREAMING_SNAKE_CASE__="gelu"							,  SCREAMING_SNAKE_CASE__=0.1							,  SCREAMING_SNAKE_CASE__=0.1							,  SCREAMING_SNAKE_CASE__=0.02							,  SCREAMING_SNAKE_CASE__=3							,  SCREAMING_SNAKE_CASE__=None							,  ):
            lowercase	:      int          =						parent
            lowercase	:      Dict          =						batch_size
            lowercase	:      Dict          =						image_size
            lowercase	:      Any          =						num_channels
            lowercase	:      Dict          =						num_encoder_blocks
            lowercase	:      Optional[int]          =						sr_ratios
            lowercase	:      int          =						depths
            lowercase	:      List[str]          =						hidden_sizes
            lowercase	:      int          =						downsampling_rates
            lowercase	:      str          =						num_attention_heads
            lowercase	:      Dict          =						is_training
            lowercase	:      Tuple          =						use_labels
            lowercase	:      Any          =						hidden_act
            lowercase	:      int          =						hidden_dropout_prob
            lowercase	:      Any          =						attention_probs_dropout_prob
            lowercase	:      Optional[int]          =						initializer_range
            lowercase	:      Dict          =						num_labels
            lowercase	:      Dict          =						scope


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

            lowercase	:      Dict          =						None
            if self.use_labels:
                  lowercase	:      Optional[int]          =						ids_tensor([self.batch_size, self.image_size, self.image_size]							,  self.num_labels						)

            lowercase	:      Dict          =						self.get_config()
            return config, pixel_values, labels


      def 				__lowerCamelCase	(							self						):
            return SegformerConfig(
                image_size=self.image_size							,  num_channels=self.num_channels							,  num_encoder_blocks=self.num_encoder_blocks							,  depths=self.depths							,  hidden_sizes=self.hidden_sizes							,  num_attention_heads=self.num_attention_heads							,  hidden_act=self.hidden_act							,  hidden_dropout_prob=self.hidden_dropout_prob							,  attention_probs_dropout_prob=self.attention_probs_dropout_prob							,  initializer_range=self.initializer_range							,  )


      def 				__lowerCamelCase	(							self							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
            lowercase	:      Optional[int]          =						SegformerModel(config=__UpperCamelCase						)
            model.to(__UpperCamelCase						)
            model.eval()
            lowercase	:      Optional[int]          =						model(__UpperCamelCase						)
            lowercase	:      Union[str, Any]          =						self.image_size // (self.downsampling_rates[-1] * 2)
            self.parent.assertEqual(
                result.last_hidden_state.shape							,  (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)						)


      def 				__lowerCamelCase	(							self							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
            lowercase	:      Tuple          =						self.num_labels
            lowercase	:      Union[str, Any]          =						SegformerForSemanticSegmentation(__UpperCamelCase						)
            model.to(__UpperCamelCase						)
            model.eval()
            lowercase	:      Tuple          =						model(__UpperCamelCase						)
            self.parent.assertEqual(
                result.logits.shape							,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)						)
            lowercase	:      Any          =						model(__UpperCamelCase							,  labels=__UpperCamelCase						)
            self.parent.assertEqual(
                result.logits.shape							,  (self.batch_size, self.num_labels, self.image_size // 4, self.image_size // 4)						)
            self.parent.assertGreater(result.loss							,  0.0						)


      def 				__lowerCamelCase	(							self							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
            lowercase	:      Optional[int]          =						1
            lowercase	:      int          =						SegformerForSemanticSegmentation(config=__UpperCamelCase						)
            model.to(__UpperCamelCase						)
            model.eval()
            lowercase	:      List[str]          =						torch.randint(0							,  1							,  (self.batch_size, self.image_size, self.image_size)						).to(__UpperCamelCase						)
            lowercase	:      Dict          =						model(__UpperCamelCase							,  labels=__UpperCamelCase						)
            self.parent.assertGreater(result.loss							,  0.0						)






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







@require_torch
class  __SCREAMING_SNAKE_CASE      (	lowercase_     ,  lowercase_     ,  unittest.TestCase      ):
      A :							str										=   (
          (
              SegformerModel,
              SegformerForSemanticSegmentation,
              SegformerForImageClassification,
          )
          if is_torch_available()
          else ()
      )
      A :							List[Any]										=   (
          {
              'feature-extraction': SegformerModel,
              'image-classification': SegformerForImageClassification,
              'image-segmentation': SegformerForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

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


      def 				__lowerCamelCase	(							self						):
            lowercase	:      List[Any]          =						SegformerModelTester(self						)
            lowercase	:      int          =						SegformerConfigTester(self							,  config_class=__UpperCamelCase						)


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


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Dict          =						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_binary_image_segmentation(*__UpperCamelCase						)


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Optional[int]          =						self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_segmentation(*__UpperCamelCase						)


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


      @unittest.skip('''SegFormer does not have get_input_embeddings method and get_output_embeddings methods'''						)
      def 				__lowerCamelCase	(							self						):
            pass


      def 				__lowerCamelCase	(							self						):
            lowercase	:      Optional[Any]          =						self.model_tester.prepare_config_and_inputs_for_common()

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

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


      def 				__lowerCamelCase	(							self						):
            lowercase	:      str          =						self.model_tester.prepare_config_and_inputs_for_common()
            lowercase	:      str          =						True

            for model_class in self.all_model_classes:
                  lowercase	:      Optional[Any]          =						True
                  lowercase	:      Dict          =						False
                  lowercase	:      Dict          =						True
                  lowercase	:      Tuple          =						model_class(__UpperCamelCase						)
                  model.to(__UpperCamelCase						)
                  model.eval()
                  with torch.no_grad():
                        lowercase	:      Dict          =						model(**self._prepare_for_class(__UpperCamelCase							,  __UpperCamelCase						)						)
                  lowercase	:      List[Any]          =						outputs.attentions

                  lowercase	:      int          =						sum(self.model_tester.depths						)
                  self.assertEqual(len(__UpperCamelCase						)							,  __UpperCamelCase						)

                  # check that output_attentions also work using config
                  del inputs_dict["output_attentions"]
                  lowercase	:      Any          =						True
                  lowercase	:      List[str]          =						model_class(__UpperCamelCase						)
                  model.to(__UpperCamelCase						)
                  model.eval()
                  with torch.no_grad():
                        lowercase	:      Optional[Any]          =						model(**self._prepare_for_class(__UpperCamelCase							,  __UpperCamelCase						)						)
                  lowercase	:      List[Any]          =						outputs.attentions

                  self.assertEqual(len(__UpperCamelCase						)							,  __UpperCamelCase						)

                  # verify the first attentions (first block, first layer)
                  lowercase	:      str          =						(self.model_tester.image_size // 4) ** 2
                  lowercase	:      Union[str, Any]          =						(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                  self.assertListEqual(
                      list(attentions[0].shape[-3:]						)							,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]							,  )

                  # verify the last attentions (last block, last layer)
                  lowercase	:      Tuple          =						(self.model_tester.image_size // 32) ** 2
                  lowercase	:      int          =						(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
                  self.assertListEqual(
                      list(attentions[-1].shape[-3:]						)							,  [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]							,  )
                  lowercase	:      Any          =						len(__UpperCamelCase						)

                  # Check attention is always last and order is fine
                  lowercase	:      int          =						True
                  lowercase	:      Any          =						True
                  lowercase	:      List[Any]          =						model_class(__UpperCamelCase						)
                  model.to(__UpperCamelCase						)
                  model.eval()
                  with torch.no_grad():
                        lowercase	:      Optional[Any]          =						model(**self._prepare_for_class(__UpperCamelCase							,  __UpperCamelCase						)						)

                  self.assertEqual(out_len + 1							,  len(__UpperCamelCase						)						)

                  lowercase	:      List[str]          =						outputs.attentions

                  self.assertEqual(len(__UpperCamelCase						)							,  __UpperCamelCase						)
                  # verify the first attentions (first block, first layer)
                  lowercase	:      Union[str, Any]          =						(self.model_tester.image_size // 4) ** 2
                  lowercase	:      List[Any]          =						(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
                  self.assertListEqual(
                      list(self_attentions[0].shape[-3:]						)							,  [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]							,  )


      def 				__lowerCamelCase	(							self						):


            def check_hidden_states_output(SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__							,  SCREAMING_SNAKE_CASE__						):
                  lowercase	:      Any          =						model_class(__UpperCamelCase						)
                  model.to(__UpperCamelCase						)
                  model.eval()

                  with torch.no_grad():
                        lowercase	:      List[Any]          =						model(**self._prepare_for_class(__UpperCamelCase							,  __UpperCamelCase						)						)

                  lowercase	:      Tuple          =						outputs.hidden_states

                  lowercase	:      str          =						self.model_tester.num_encoder_blocks
                  self.assertEqual(len(__UpperCamelCase						)							,  __UpperCamelCase						)

                  # verify the first hidden states (first block)
                  self.assertListEqual(
                      list(hidden_states[0].shape[-3:]						)							,  [
                          self.model_tester.hidden_sizes[0],
                          self.model_tester.image_size // 4,
                          self.model_tester.image_size // 4,
                      ]							,  )

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

            for model_class in self.all_model_classes:
                  lowercase	:      List[str]          =						True
                  check_hidden_states_output(__UpperCamelCase							,  __UpperCamelCase							,  __UpperCamelCase						)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  lowercase	:      List[str]          =						True

                  check_hidden_states_output(__UpperCamelCase							,  __UpperCamelCase							,  __UpperCamelCase						)


      def 				__lowerCamelCase	(							self						):


            if not self.model_tester.is_training:
                  return

            lowercase	:      Any          =						self.model_tester.prepare_config_and_inputs_for_common()
            lowercase	:      str          =						True

            for model_class in self.all_model_classes:
                  if model_class in get_values(__UpperCamelCase						):
                        continue

                  lowercase	:      str          =						model_class(__UpperCamelCase						)
                  model.to(__UpperCamelCase						)
                  model.train()
                  lowercase	:      Dict          =						self._prepare_for_class(__UpperCamelCase							,  __UpperCamelCase							,  return_labels=__UpperCamelCase						)
                  lowercase	:      List[Any]          =						model(**__UpperCamelCase						).loss
                  loss.backward()


      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''						)
      def 				__lowerCamelCase	(							self						):
            pass






      @slow
      def 				__lowerCamelCase	(							self						):


            for model_name in SEGFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  lowercase	:      int          =						SegformerModel.from_pretrained(__UpperCamelCase						)
                  self.assertIsNotNone(__UpperCamelCase						)





def 	__lowercase		(  )			->str:







      """simple docstring"""

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







@require_torch
class  __SCREAMING_SNAKE_CASE      (	unittest.TestCase      ):


      @slow
      def 				__lowerCamelCase	(							self						):
            lowercase	:      Union[str, Any]          =						SegformerImageProcessor(
                image_scale=(512, 512)							,  keep_ratio=__UpperCamelCase							,  align=__UpperCamelCase							,  do_random_crop=__UpperCamelCase						)
            lowercase	:      Dict          =						SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''						).to(
                __UpperCamelCase						)

            lowercase	:      Union[str, Any]          =						prepare_img()
            lowercase	:      List[Any]          =						image_processor(images=__UpperCamelCase							,  return_tensors='''pt'''						)
            lowercase	:      Optional[Any]          =						encoded_inputs.pixel_values.to(__UpperCamelCase						)

            with torch.no_grad():
                  lowercase	:      Tuple          =						model(__UpperCamelCase						)

            lowercase	:      Optional[int]          =						torch.Size((1, model.config.num_labels, 128, 128)						)
            self.assertEqual(outputs.logits.shape							,  __UpperCamelCase						)

            lowercase	:      int          =						torch.tensor(
                [
                    [[-4.6310, -5.5232, -6.2356], [-5.1921, -6.1444, -6.5996], [-5.4424, -6.2790, -6.7574]],
                    [[-12.1391, -13.3122, -13.9554], [-12.8732, -13.9352, -14.3563], [-12.9438, -13.8226, -14.2513]],
                    [[-12.5134, -13.4686, -14.4915], [-12.8669, -14.4343, -14.7758], [-13.2523, -14.5819, -15.0694]],
                ]						).to(__UpperCamelCase						)
            self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]							,  __UpperCamelCase							,  atol=1E-4						)						)


      @slow
      def 				__lowerCamelCase	(							self						):
            lowercase	:      Optional[int]          =						SegformerImageProcessor(
                image_scale=(512, 512)							,  keep_ratio=__UpperCamelCase							,  align=__UpperCamelCase							,  do_random_crop=__UpperCamelCase						)
            lowercase	:      Optional[Any]          =						SegformerForSemanticSegmentation.from_pretrained(
                '''nvidia/segformer-b1-finetuned-cityscapes-1024-1024'''						).to(__UpperCamelCase						)

            lowercase	:      List[Any]          =						prepare_img()
            lowercase	:      Tuple          =						image_processor(images=__UpperCamelCase							,  return_tensors='''pt'''						)
            lowercase	:      List[str]          =						encoded_inputs.pixel_values.to(__UpperCamelCase						)

            with torch.no_grad():
                  lowercase	:      str          =						model(__UpperCamelCase						)

            lowercase	:      str          =						torch.Size((1, model.config.num_labels, 128, 128)						)
            self.assertEqual(outputs.logits.shape							,  __UpperCamelCase						)

            lowercase	:      Optional[Any]          =						torch.tensor(
                [
                    [[-13.5748, -13.9111, -12.6500], [-14.3500, -15.3683, -14.2328], [-14.7532, -16.0424, -15.6087]],
                    [[-17.1651, -15.8725, -12.9653], [-17.2580, -17.3718, -14.8223], [-16.6058, -16.8783, -16.7452]],
                    [[-3.6456, -3.0209, -1.4203], [-3.0797, -3.1959, -2.0000], [-1.8757, -1.9217, -1.6997]],
                ]						).to(__UpperCamelCase						)
            self.assertTrue(torch.allclose(outputs.logits[0, :3, :3, :3]							,  __UpperCamelCase							,  atol=1E-1						)						)






      @slow
      def 				__lowerCamelCase	(							self						):
            lowercase	:      Dict          =						SegformerImageProcessor(
                image_scale=(512, 512)							,  keep_ratio=__UpperCamelCase							,  align=__UpperCamelCase							,  do_random_crop=__UpperCamelCase						)
            lowercase	:      List[Any]          =						SegformerForSemanticSegmentation.from_pretrained('''nvidia/segformer-b0-finetuned-ade-512-512'''						).to(
                __UpperCamelCase						)

            lowercase	:      Dict          =						prepare_img()
            lowercase	:      int          =						image_processor(images=__UpperCamelCase							,  return_tensors='''pt'''						)
            lowercase	:      List[str]          =						encoded_inputs.pixel_values.to(__UpperCamelCase						)

            with torch.no_grad():
                  lowercase	:      str          =						model(__UpperCamelCase						)

            lowercase	:      Dict          =						outputs.logits.detach().cpu()

            lowercase	:      str          =						image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase							,  target_sizes=[(500, 300)]						)
            lowercase	:      Union[str, Any]          =						torch.Size((500, 300)						)
            self.assertEqual(segmentation[0].shape							,  __UpperCamelCase						)

            lowercase	:      int          =						image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase						)
            lowercase	:      Union[str, Any]          =						torch.Size((128, 128)						)
            self.assertEqual(segmentation[0].shape							,  __UpperCamelCase						)


"""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			)

