




import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
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 ResNetBackbone, ResNetForImageClassification, ResNetModel
 from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor

class 			_lowerCamelCase    :

      """simple docstring"""

      def __init__(  self       :			List[Any]			,							snake_case       :			int			,							snake_case       :			List[Any]=3			,							snake_case       :			Dict=32			,							snake_case       :			Dict=3			,							snake_case       :			Optional[int]=10			,							snake_case       :			int=[10, 20, 30, 40]			,							snake_case       :			List[Any]=[1, 1, 2, 1]			,							snake_case       :			List[Any]=True			,							snake_case       :			str=True			,							snake_case       :			int="relu"			,							snake_case       :			List[str]=3			,							snake_case       :			List[str]=None			,							snake_case       :			List[Any]=["stage2", "stage3", "stage4"]			,							snake_case       :			Optional[Any]=[2, 3, 4]			,							):
          __UpperCamelCase			=    parent
          __UpperCamelCase			=    batch_size
          __UpperCamelCase			=    image_size
          __UpperCamelCase			=    num_channels
          __UpperCamelCase			=    embeddings_size
          __UpperCamelCase			=    hidden_sizes
          __UpperCamelCase			=    depths
          __UpperCamelCase			=    is_training
          __UpperCamelCase			=    use_labels
          __UpperCamelCase			=    hidden_act
          __UpperCamelCase			=    num_labels
          __UpperCamelCase			=    scope
          __UpperCamelCase			=    len(snake_case					)
          __UpperCamelCase			=    out_features
          __UpperCamelCase			=    out_indices







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

          __UpperCamelCase			=    None
          if self.use_labels:
              __UpperCamelCase			=    ids_tensor([self.batch_size]			,							self.num_labels					)

          __UpperCamelCase			=    self.get_config()

          return config, pixel_values, labels







      def    snake_case						(  self       :			Tuple					):
          return ResNetConfig(
              num_channels=self.num_channels			,							embeddings_size=self.embeddings_size			,							hidden_sizes=self.hidden_sizes			,							depths=self.depths			,							hidden_act=self.hidden_act			,							num_labels=self.num_labels			,							out_features=self.out_features			,							out_indices=self.out_indices			,							)







      def    snake_case						(  self       :			List[str]			,							snake_case       :			Optional[int]			,							snake_case       :			Tuple			,							snake_case       :			int					):
          __UpperCamelCase			=    ResNetModel(config=snake_case					)
          model.to(snake_case					)
          model.eval()
          __UpperCamelCase			=    model(snake_case					)
          # expected last hidden states: B, C, H // 32, W // 32
          self.parent.assertEqual(
              result.last_hidden_state.shape			,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,							)







      def    snake_case						(  self       :			Tuple			,							snake_case       :			Union[str, Any]			,							snake_case       :			List[str]			,							snake_case       :			List[str]					):
          __UpperCamelCase			=    self.num_labels
          __UpperCamelCase			=    ResNetForImageClassification(snake_case					)
          model.to(snake_case					)
          model.eval()
          __UpperCamelCase			=    model(snake_case			,							labels=snake_case					)
          self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)					)







      def    snake_case						(  self       :			int			,							snake_case       :			Dict			,							snake_case       :			List[str]			,							snake_case       :			Optional[int]					):
          __UpperCamelCase			=    ResNetBackbone(config=snake_case					)
          model.to(snake_case					)
          model.eval()
          __UpperCamelCase			=    model(snake_case					)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps					)			,							len(config.out_features					)					)
          self.parent.assertListEqual(list(result.feature_maps[0].shape					)			,							[self.batch_size, self.hidden_sizes[1], 4, 4]					)

          # verify channels
          self.parent.assertEqual(len(model.channels					)			,							len(config.out_features					)					)
          self.parent.assertListEqual(model.channels			,							config.hidden_sizes[1:]					)

          # verify backbone works with out_features=None
          __UpperCamelCase			=    None
          __UpperCamelCase			=    ResNetBackbone(config=snake_case					)
          model.to(snake_case					)
          model.eval()
          __UpperCamelCase			=    model(snake_case					)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps					)			,							1					)
          self.parent.assertListEqual(list(result.feature_maps[0].shape					)			,							[self.batch_size, self.hidden_sizes[-1], 1, 1]					)

          # verify channels
          self.parent.assertEqual(len(model.channels					)			,							1					)
          self.parent.assertListEqual(model.channels			,							[config.hidden_sizes[-1]]					)







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







@require_torch
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE				,      _SCREAMING_SNAKE_CASE				,      unittest.TestCase ):

      """simple docstring"""

      lowerCAmelCase__      :			List[str]     =       (
          (
              ResNetModel,
              ResNetForImageClassification,
              ResNetBackbone,
          )
          if is_torch_available()
          else ()
      )
      lowerCAmelCase__      :			Optional[int]     =       (
          {"feature-extraction": ResNetModel, "image-classification": ResNetForImageClassification}
          if is_torch_available()
          else {}
      )

      lowerCAmelCase__      :			Optional[Any]     =       True
      lowerCAmelCase__      :			Union[str, Any]     =       False
      lowerCAmelCase__      :			Optional[int]     =       False
      lowerCAmelCase__      :			Tuple     =       False
      lowerCAmelCase__      :			Any     =       False







      def    snake_case						(  self       :			Tuple					):
          __UpperCamelCase			=    ResNetModelTester(self					)
          __UpperCamelCase			=    ConfigTester(self			,							config_class=snake_case			,							has_text_modality=snake_case					)







      def    snake_case						(  self       :			Optional[Any]					):
          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()







      def    snake_case						(  self       :			int					):
          return







      @unittest.skip(reason='''ResNet does not use inputs_embeds'''					)
      def    snake_case						(  self       :			Union[str, Any]					):
          pass







      @unittest.skip(reason='''ResNet does not support input and output embeddings'''					)
      def    snake_case						(  self       :			Optional[int]					):
          pass







      def    snake_case						(  self       :			Optional[int]					):
          __UpperCamelCase		,   __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __UpperCamelCase			=    model_class(snake_case					)
              __UpperCamelCase			=    inspect.signature(model.forward					)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __UpperCamelCase			=    [*signature.parameters.keys()]

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







      def    snake_case						(  self       :			Union[str, Any]					):
          __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case					)







      def    snake_case						(  self       :			List[Any]					):
          __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*snake_case					)







      def    snake_case						(  self       :			str					):
          __UpperCamelCase		,   __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __UpperCamelCase			=    model_class(config=snake_case					)
              for name, module in model.named_modules():
                  if isinstance(snake_case			,							(nn.BatchNormad, nn.GroupNorm)					):
                      self.assertTrue(
                          torch.all(module.weight == 1					)			,							msg=F"Parameter {name} of model {model_class} seems not properly initialized"			,							)
                      self.assertTrue(
                          torch.all(module.bias == 0					)			,							msg=F"Parameter {name} of model {model_class} seems not properly initialized"			,							)







      def    snake_case						(  self       :			Optional[int]					):
          def check_hidden_states_output(snake_case       :			str			,							snake_case       :			Union[str, Any]			,							snake_case       :			str					):
              __UpperCamelCase			=    model_class(snake_case					)
              model.to(snake_case					)
              model.eval()

              with torch.no_grad():
                  __UpperCamelCase			=    model(**self._prepare_for_class(snake_case			,							snake_case					)					)

              __UpperCamelCase			=    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __UpperCamelCase			=    self.model_tester.num_stages
              self.assertEqual(len(snake_case					)			,							expected_num_stages + 1					)

              # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]					)			,							[self.model_tester.image_size // 4, self.model_tester.image_size // 4]			,							)

          __UpperCamelCase		,   __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs_for_common()
          __UpperCamelCase			=    ['''basic''', '''bottleneck''']
          for model_class in self.all_model_classes:
              for layer_type in layers_type:
                  __UpperCamelCase			=    layer_type
                  __UpperCamelCase			=    True
                  check_hidden_states_output(snake_case			,							snake_case			,							snake_case					)

                  # check that output_hidden_states also work using config
                  del inputs_dict["output_hidden_states"]
                  __UpperCamelCase			=    True

                  check_hidden_states_output(snake_case			,							snake_case			,							snake_case					)







      @unittest.skip(reason='''ResNet does not use feedforward chunking'''					)
      def    snake_case						(  self       :			Any					):
          pass







      def    snake_case						(  self       :			List[str]					):
          __UpperCamelCase			=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case					)







      @slow
      def    snake_case						(  self       :			Union[str, Any]					):
          for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __UpperCamelCase			=    ResNetModel.from_pretrained(snake_case					)
              self.assertIsNotNone(snake_case					)







def        __SCREAMING_SNAKE_CASE (	)							->						int:

    """simple docstring"""


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

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

      """simple docstring"""

      @cached_property
      def    snake_case						(  self       :			str					):
          return (
              AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					)
              if is_vision_available()
              else None
          )







      @slow
      def    snake_case						(  self       :			Dict					):
          __UpperCamelCase			=    ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]					).to(snake_case					)

          __UpperCamelCase			=    self.default_image_processor
          __UpperCamelCase			=    prepare_img()
          __UpperCamelCase			=    image_processor(images=snake_case			,							return_tensors='''pt'''					).to(snake_case					)

          # forward pass
          with torch.no_grad():
              __UpperCamelCase			=    model(**snake_case					)

          # verify the logits
          __UpperCamelCase			=    torch.Size((1, 1000)					)
          self.assertEqual(outputs.logits.shape			,							snake_case					)

          __UpperCamelCase			=    torch.tensor([-11.10_69, -9.78_77, -8.37_77]					).to(snake_case					)

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







@require_torch
class 			_lowerCamelCase    (      _SCREAMING_SNAKE_CASE				,      unittest.TestCase ):

      """simple docstring"""

      lowerCAmelCase__      :			Tuple     =       (ResNetBackbone,) if is_torch_available() else ()
      lowerCAmelCase__      :			List[str]     =       False
      lowerCAmelCase__      :			int     =       ResNetConfig







      def    snake_case						(  self       :			Optional[Any]					):
          __UpperCamelCase			=    ResNetModelTester(self					)










"""simple docstring"""






from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

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 numpy as np
					import tensorflow as tf

					from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
					from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import MobileViTImageProcessor


class 			SCREAMING_SNAKE_CASE_  (   _lowercase):




							'''simple docstring'''





							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.config_class(**self.inputs_dict)
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"neck_hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"num_attention_heads"))


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__=13	,					lowerCamelCase__=32	,					lowerCamelCase__=2	,					lowerCamelCase__=3	,					lowerCamelCase__=640	,					lowerCamelCase__=4	,					lowerCamelCase__="silu"	,					lowerCamelCase__=3	,					lowerCamelCase__=32	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.02	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=10	,					lowerCamelCase__=None	,					)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      parent
								snake_case__  :						List[Any]		=      batch_size
								snake_case__  :						Any		=      image_size
								snake_case__  :						Tuple		=      patch_size
								snake_case__  :						int		=      num_channels
								snake_case__  :						Optional[Any]		=      last_hidden_size
								snake_case__  :						Union[str, Any]		=      num_attention_heads
								snake_case__  :						Tuple		=      hidden_act
								snake_case__  :						Optional[int]		=      conv_kernel_size
								snake_case__  :						int		=      output_stride
								snake_case__  :						Optional[Any]		=      hidden_dropout_prob
								snake_case__  :						str		=      attention_probs_dropout_prob
								snake_case__  :						Any		=      classifier_dropout_prob
								snake_case__  :						Tuple		=      use_labels
								snake_case__  :						Optional[Any]		=      is_training
								snake_case__  :						Dict		=      num_labels
								snake_case__  :						Dict		=      initializer_range
								snake_case__  :						List[str]		=      scope




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







								'''simple docstring'''




								snake_case__  :						List[Any]		=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

								snake_case__  :						Optional[Any]		=      None
								snake_case__  :						int		=      None
								if self.use_labels:
									snake_case__  :						List[str]		=      ids_tensor([self.batch_size]	,					self.num_labels)
									snake_case__  :						Any		=      ids_tensor([self.batch_size, self.image_size, self.image_size]	,					self.num_labels)

								snake_case__  :						Dict		=      self.get_config()

								return config, pixel_values, labels, pixel_labels




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								return MobileViTConfig(
								    image_size=self.image_size	,					patch_size=self.patch_size	,					num_channels=self.num_channels	,					num_attention_heads=self.num_attention_heads	,					hidden_act=self.hidden_act	,					conv_kernel_size=self.conv_kernel_size	,					output_stride=self.output_stride	,					hidden_dropout_prob=self.hidden_dropout_prob	,					attention_probs_dropout_prob=self.attention_probs_dropout_prob	,					classifier_dropout_prob=self.classifier_dropout_prob	,					initializer_range=self.initializer_range	,					)




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Tuple		=      TFMobileViTModel(config=lowerCamelCase__)
								snake_case__  :						int		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								snake_case__  :						Tuple		=      self.image_size // self.output_stride
								self.parent.assertEqual(
								    result.last_hidden_state.shape	,					(self.batch_size, self.last_hidden_size, expected_height, expected_width))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Any		=      self.num_labels
								snake_case__  :						Dict		=      TFMobileViTForImageClassification(lowerCamelCase__)
								snake_case__  :						List[Any]		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      self.num_labels
								snake_case__  :						Any		=      TFMobileViTForSemanticSegmentation(lowerCamelCase__)
								snake_case__  :						List[Any]		=      self.image_size // self.output_stride

								snake_case__  :						Tuple		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))

								snake_case__  :						str		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))







							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




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


@require_tf
class 			SCREAMING_SNAKE_CASE_  (   _lowercase	,      _lowercase	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     Optional[int]				  =  (
							    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
							    if is_tf_available()
							    else ()
							)
							__magic_name__					:     str				  =  (
							    {'''feature-extraction''': TFMobileViTModel, '''image-classification''': TFMobileViTForImageClassification}
							    if is_tf_available()
							    else {}
							)

							__magic_name__					:     List[str]				  =  False
							__magic_name__					:     int				  =  False
							__magic_name__					:     Any				  =  False
							__magic_name__					:     Optional[int]				  =  False
							__magic_name__					:     Union[str, Any]				  =  False




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







								'''simple docstring'''




								snake_case__  :						Any		=      TFMobileViTModelTester(self)
								snake_case__  :						Dict		=      TFMobileViTConfigTester(self	,					config_class=lowerCamelCase__	,					has_text_modality=lowerCamelCase__)




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







								'''simple docstring'''




								self.config_tester.run_common_tests()




							@unittest.skip(reason="MobileViT does not use inputs_embeds")
							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not support input and output embeddings")
							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not output attentions")
							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								pass




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







								'''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(lowerCamelCase__)
									snake_case__  :						Optional[int]		=      inspect.signature(model.call)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									snake_case__  :						List[Any]		=      [*signature.parameters.keys()]

									snake_case__  :						Dict		=      ["pixel_values"]
									self.assertListEqual(arg_names[:1]	,					lowerCamelCase__)




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







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase__)




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







								'''simple docstring'''




								def check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						List[Any]		=      model_class(lowerCamelCase__)

									snake_case__  :						Optional[int]		=      model(**self._prepare_for_class(lowerCamelCase__	,					lowerCamelCase__))

									snake_case__  :						List[Any]		=      outputs.hidden_states

									snake_case__  :						Union[str, Any]		=      5
									self.assertEqual(len(lowerCamelCase__)	,					lowerCamelCase__)

									# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
									# with the width and height being successively divided by 2.
									snake_case__  :						str		=      2
									for i in range(len(lowerCamelCase__)):
										self.assertListEqual(
										    list(hidden_states[i].shape[-2:])	,					[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]	,					)
										divisor *= 2

									self.assertEqual(self.model_tester.output_stride	,					divisor // 2)

								snake_case__,					snake_case__  :						Union[str, Any]		=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									snake_case__  :						List[Any]		=      True
									check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)

									# check that output_hidden_states also work using config
									del inputs_dict["output_hidden_states"]
									snake_case__  :						Any		=      True

									check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)




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







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__)




							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0	,					reason="TF does not support backprop for grouped convolutions on CPU."	,					)
							def        UpperCAmelCase (						self)   ->	Any:







								'''simple docstring'''




								super().test_dataset_conversion()




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__=2E-1	,					lowerCamelCase__=2E-1)   ->	Optional[Any]:







								'''simple docstring'''




								self.assertTrue(np.allclose(lowerCamelCase__	,					lowerCamelCase__	,					atol=lowerCamelCase__	,					rtol=lowerCamelCase__))




							@unittest.skipIf(
							    not is_tf_available() or len(tf.config.list_physical_devices("GPU")) == 0	,					reason="TF does not support backprop for grouped convolutions on CPU."	,					)
							@slow
							def        UpperCAmelCase (						self)   ->	int:







								'''simple docstring'''




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

								for model_class in self.all_model_classes:
									# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
									if model_class.__name__ != "TFMobileViTModel":
										snake_case__  :						Dict		=      model_class(lowerCamelCase__)
										if getattr(lowerCamelCase__	,					"hf_compute_loss"	,					lowerCamelCase__):
											super().test_keras_fit()




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__,					snake_case__  :						List[str]		=      self.model_tester.prepare_config_and_inputs_for_common()
								for model_class in self.all_model_classes:
									# set an ignore index to correctly test the masked loss used in
									# `TFMobileViTForSemanticSegmentation`.
									if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
										snake_case__  :						Any		=      5

									snake_case__  :						Any		=      model_class(lowerCamelCase__)
									if getattr(lowerCamelCase__	,					"hf_compute_loss"	,					lowerCamelCase__):
										# The number of elements in the loss should be the same as the number of elements in the label
										snake_case__  :						Tuple		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Optional[Any]		=      prepared_for_class[
										    sorted(prepared_for_class.keys() - inputs_dict.keys()	,					reverse=lowerCamelCase__)[0]
										]
										snake_case__  :						Optional[int]		=      added_label.shape.as_list()[:1]

										# Test that model correctly compute the loss with kwargs
										snake_case__  :						Dict		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Dict		=      {"input_ids", "pixel_values", "input_features"}
										snake_case__  :						Any		=      possible_input_names.intersection(set(lowerCamelCase__)).pop()
										snake_case__  :						List[str]		=      prepared_for_class.pop(lowerCamelCase__)

										snake_case__  :						Optional[Any]		=      model(lowerCamelCase__	,					**lowerCamelCase__)[0]
										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

										# Test that model correctly compute the loss when we mask some positions
										snake_case__  :						Dict		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Dict		=      {"input_ids", "pixel_values", "input_features"}
										snake_case__  :						List[Any]		=      possible_input_names.intersection(set(lowerCamelCase__)).pop()
										snake_case__  :						List[Any]		=      prepared_for_class.pop(lowerCamelCase__)
										if "labels" in prepared_for_class:
											snake_case__  :						int		=      prepared_for_class["labels"].numpy()
											if len(labels.shape) > 1 and labels.shape[1] != 1:
												# labels[0] = -100
												snake_case__  :						Union[str, Any]		=      tf.convert_to_tensor(lowerCamelCase__)
												snake_case__  :						Tuple		=      model(lowerCamelCase__	,					**lowerCamelCase__)[0]
												self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])
												self.assertTrue(not np.any(np.isnan(loss.numpy())))

                # Test that model correctly compute the loss with a dict
										snake_case__  :						int		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Union[str, Any]		=      model(lowerCamelCase__)[0]
										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])

										# Test that model correctly compute the loss with a tuple
										snake_case__  :						str		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)

										# Get keys that were added with the _prepare_for_class function
										snake_case__  :						List[Any]		=      prepared_for_class.keys() - inputs_dict.keys()
										snake_case__  :						str		=      inspect.signature(model.call).parameters
										snake_case__  :						Tuple		=      list(signature.keys())

										# Create a dictionary holding the location of the tensors in the tuple
										snake_case__  :						int		=      {0: input_name}
										for label_key in label_keys:
											snake_case__  :						Tuple		=      signature_names.index(lowerCamelCase__)
											snake_case__  :						Union[str, Any]		=      label_key
										snake_case__  :						Union[str, Any]		=      sorted(tuple_index_mapping.items())
										# Initialize a list with their default values, update the values and convert to a tuple
										snake_case__  :						List[Any]		=      []

										for name in signature_names:
											if name != "kwargs":
												list_input.append(signature[name].default)

										for index, value in sorted_tuple_index_mapping:
											snake_case__  :						Any		=      prepared_for_class[value]

										snake_case__  :						List[str]		=      tuple(lowerCamelCase__)

										# Send to model
										snake_case__  :						int		=      model(tuple_input[:-1])[0]

										self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1])







							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__  :						Optional[Any]		=      TFMobileViTModel.from_pretrained(lowerCamelCase__)
									self.assertIsNotNone(lowerCamelCase__)



def 			A__		(					)							->	Optional[Any]:

	'''simple docstring'''


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



@require_tf
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small")

								snake_case__  :						List[str]		=      MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small")
								snake_case__  :						Dict		=      prepare_img()
								snake_case__  :						List[str]		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						Union[str, Any]		=      model(**lowerCamelCase__	,					training=lowerCamelCase__)

								# verify the logits
								snake_case__  :						str		=      tf.TensorShape((1, 1_000))
								self.assertEqual(outputs.logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant([-1.93_64, -1.23_27, -0.46_53])

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







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







								'''simple docstring'''




								snake_case__  :						Dict		=      TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						Any		=      MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						List[str]		=      prepare_img()
								snake_case__  :						Dict		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						str		=      model(inputs.pixel_values	,					training=lowerCamelCase__)
								snake_case__  :						Dict		=      outputs.logits

								# verify the logits
								snake_case__  :						Union[str, Any]		=      tf.TensorShape((1, 21, 32, 32))
								self.assertEqual(logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant(
								    [
								        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
								        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
								        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
								    ])

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





