




'''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     UpperCamelCase					(  UpperCamelCase_					):



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       List[str]       					=			self.config_class(**self.inputs_dict   )
      self.parent.assertTrue(hasattr(__UpperCamelCase		,    """hidden_sizes"""   )   )
      self.parent.assertTrue(hasattr(__UpperCamelCase		,    """neck_hidden_sizes"""   )   )
      self.parent.assertTrue(hasattr(__UpperCamelCase		,    """num_attention_heads"""   )   )






class     UpperCamelCase					:



  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		,    ):







      '''simple docstring'''


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



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Dict       					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

      _a							:       int       					=			None
      _a							:       Optional[Any]       					=			None
      if self.use_labels:
          _a							:       int       					=			ids_tensor([self.batch_size]		,    self.num_labels   )
          _a							:       Tuple       					=			ids_tensor([self.batch_size, self.image_size, self.image_size]		,    self.num_labels   )

      _a							:       Optional[int]       					=			self.get_config()

      return config, pixel_values, labels, pixel_labels



  def 						a_       ( self   ):







      '''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 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       str       					=			TFMobileViTModel(config=__UpperCamelCase   )
      _a							:       List[str]       					=			model(__UpperCamelCase		,    training=__UpperCamelCase   )
      _a							:       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 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       List[str]       					=			self.num_labels
      _a							:       List[Any]       					=			TFMobileViTForImageClassification(__UpperCamelCase   )
      _a							:       Optional[Any]       					=			model(__UpperCamelCase		,    labels=__UpperCamelCase		,    training=__UpperCamelCase   )
      self.parent.assertEqual(result.logits.shape		,    (self.batch_size, self.num_labels)   )



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):







      '''simple docstring'''


      _a							:       Tuple       					=			self.num_labels
      _a							:       Tuple       					=			TFMobileViTForSemanticSegmentation(__UpperCamelCase   )
      _a							:       List[Any]       					=			self.image_size // self.output_stride

      _a							:       Any       					=			model(__UpperCamelCase		,    training=__UpperCamelCase   )
      self.parent.assertEqual(
          result.logits.shape		,    (self.batch_size, self.num_labels, expected_height, expected_width)   )

      _a							:       Dict       					=			model(__UpperCamelCase		,    labels=__UpperCamelCase		,    training=__UpperCamelCase   )
      self.parent.assertEqual(
          result.logits.shape		,    (self.batch_size, self.num_labels, expected_height, expected_width)   )



  def 						a_       ( self   ):







      '''simple docstring'''


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






@require_tf
class     UpperCamelCase					(  UpperCamelCase_			,		UpperCamelCase_			,		unittest.TestCase					):
  a    :int      					=				(
      (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
      if is_tf_available()
      else ()
  )
  a    :List[Any]      					=				(
      {'feature-extraction': TFMobileViTModel, 'image-classification': TFMobileViTForImageClassification}
      if is_tf_available()
      else {}
  )

  a    :Union[str, Any]      					=				False
  a    :Optional[Any]      					=				False
  a    :Tuple      					=				False
  a    :Any      					=				False
  a    :Any      					=				False



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Optional[int]       					=			TFMobileViTModelTester(self   )
      _a							:       Union[str, Any]       					=			TFMobileViTConfigTester(self		,    config_class=__UpperCamelCase		,    has_text_modality=__UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      self.config_tester.run_common_tests()



  @unittest.skip(reason="""MobileViT does not use inputs_embeds"""   )
  def 						a_       ( self   ):







      '''simple docstring'''


      pass



  @unittest.skip(reason="""MobileViT does not support input and output embeddings"""   )
  def 						a_       ( self   ):







      '''simple docstring'''


      pass



  @unittest.skip(reason="""MobileViT does not output attentions"""   )
  def 						a_       ( self   ):







      '''simple docstring'''


      pass



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Tuple       					=			self.model_tester.prepare_config_and_inputs_for_common()

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

          _a							:       Union[str, Any]       					=			['''pixel_values''']
          self.assertListEqual(arg_names[:1]		,    __UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       str       					=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      def check_hidden_states_output(__lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase   ):
          _a							:       Optional[Any]       					=			model_class(__UpperCamelCase   )

          _a							:       Union[str, Any]       					=			model(**self._prepare_for_class(__UpperCamelCase		,    __UpperCamelCase   )   )

          _a							:       Tuple       					=			outputs.hidden_states

          _a							:       Optional[Any]       					=			5
          self.assertEqual(len(__UpperCamelCase   )		,    __UpperCamelCase   )

          # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
          # with the width and height being successively divided by 2.
          _a							:       Tuple       					=			2
          for i in range(len(__UpperCamelCase   )   ):
              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   )

      _a							:       List[Any]       					=			self.model_tester.prepare_config_and_inputs_for_common()

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

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

          check_hidden_states_output(__UpperCamelCase		,    __UpperCamelCase		,    __UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Any       					=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase   )



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       List[Any]       					=			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase   )



  @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 						a_       ( self   ):







      '''simple docstring'''


      super().test_dataset_conversion()



  def 						a_       ( self		,    __lowerCAmelCase		,    __lowerCAmelCase		,    __lowerCAmelCase=2e-1		,    __lowerCAmelCase=2e-1   ):







      '''simple docstring'''


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



  @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 						a_       ( self   ):







      '''simple docstring'''


      _a							:       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":
              _a							:       Optional[Any]       					=			model_class(__UpperCamelCase   )
              if getattr(__UpperCamelCase		,    """hf_compute_loss"""		,    __UpperCamelCase   ):
                  super().test_keras_fit()



  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       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":
              _a							:       List[str]       					=			5

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

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

              _a							:       Any       					=			model(__UpperCamelCase		,    **__UpperCamelCase   )[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
              _a							:       Tuple       					=			self._prepare_for_class(inputs_dict.copy()		,    __UpperCamelCase		,    return_labels=__UpperCamelCase   )
              _a							:       int       					=			{'''input_ids''', '''pixel_values''', '''input_features'''}
              _a							:       Tuple       					=			possible_input_names.intersection(set(__UpperCamelCase   )   ).pop()
              _a							:       Optional[int]       					=			prepared_for_class.pop(__UpperCamelCase   )
              if "labels" in prepared_for_class:
                  _a							:       Dict       					=			prepared_for_class['''labels'''].numpy()
                  if len(labels.shape   ) > 1 and labels.shape[1] != 1:
                      # labels[0] = -100
                      _a							:       Any       					=			tf.convert_to_tensor(__UpperCamelCase   )
                      _a							:       Optional[Any]       					=			model(__UpperCamelCase		,    **__UpperCamelCase   )[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
              _a							:       List[Any]       					=			self._prepare_for_class(inputs_dict.copy()		,    __UpperCamelCase		,    return_labels=__UpperCamelCase   )
              _a							:       List[str]       					=			model(__UpperCamelCase   )[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
              _a							:       str       					=			self._prepare_for_class(inputs_dict.copy()		,    __UpperCamelCase		,    return_labels=__UpperCamelCase   )

              # Get keys that were added with the _prepare_for_class function
              _a							:       Optional[Any]       					=			prepared_for_class.keys() - inputs_dict.keys()
              _a							:       Union[str, Any]       					=			inspect.signature(model.call   ).parameters
              _a							:       Dict       					=			list(signature.keys()   )

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

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

              for index, value in sorted_tuple_index_mapping:
                  _a							:       Tuple       					=			prepared_for_class[value]

              _a							:       List[str]       					=			tuple(__UpperCamelCase   )

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

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



  @slow
  def 						a_       ( self   ):







      '''simple docstring'''


      for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          _a							:       List[str]       					=			TFMobileViTModel.from_pretrained(__UpperCamelCase   )
          self.assertIsNotNone(__UpperCamelCase   )






def UpperCAmelCase						(					):
    _a							:       Dict       					=			Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
    return image





@require_tf
class     UpperCamelCase					(  unittest.TestCase					):



  @slow
  def 						a_       ( self   ):







      '''simple docstring'''


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

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

      # forward pass
      _a							:       Any       					=			model(**__UpperCamelCase		,    training=__UpperCamelCase   )

      # verify the logits
      _a							:       Dict       					=			tf.TensorShape((1, 1000)   )
      self.assertEqual(outputs.logits.shape		,    __UpperCamelCase   )

      _a							:       List[str]       					=			tf.constant([-1.9364, -1.2327, -0.4653]   )

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



  @slow
  def 						a_       ( self   ):







      '''simple docstring'''


      _a							:       Tuple       					=			TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

      _a							:       Union[str, Any]       					=			MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

      _a							:       List[str]       					=			prepare_img()
      _a							:       str       					=			image_processor(images=__UpperCamelCase		,    return_tensors="""tf"""   )

      # forward pass
      _a							:       Any       					=			model(inputs.pixel_values		,    training=__UpperCamelCase   )
      _a							:       Optional[int]       					=			outputs.logits

      # verify the logits
      _a							:       List[Any]       					=			tf.TensorShape((1, 21, 32, 32)   )
      self.assertEqual(logits.shape		,    __UpperCamelCase   )

      _a							:       Tuple       					=			tf.constant(
          [
              [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
              [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
              [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
          ]   )

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








'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
    is_vision_available,
)


a		:  Dict   			=			{
    '''configuration_mobilevitv2''': [
        '''MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''MobileViTV2Config''',
        '''MobileViTV2OnnxConfig''',
    ],
}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  a		:  List[str]   			=			[
      '''MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST''',
      '''MobileViTV2ForImageClassification''',
      '''MobileViTV2ForSemanticSegmentation''',
      '''MobileViTV2Model''',
      '''MobileViTV2PreTrainedModel''',
  ]

if TYPE_CHECKING:
  from .configuration_mobilevitva import (
      MOBILEVITV2_PRETRAINED_CONFIG_ARCHIVE_MAP,
      MobileViTVaConfig,
      MobileViTVaOnnxConfig,
  )

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_mobilevitva import (
        MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
        MobileViTVaForImageClassification,
        MobileViTVaForSemanticSegmentation,
        MobileViTVaModel,
        MobileViTVaPreTrainedModel,
    )

else:
  import sys

  a		:  Dict   			=			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)


