

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  __lowerCamelCase				(	__snake_case	):







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        snake_case_       						=      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  __lowerCamelCase				:







      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							,  )						->       List[str]:
        snake_case_       						=      parent
        snake_case_       						=      batch_size
        snake_case_       						=      image_size
        snake_case_       						=      patch_size
        snake_case_       						=      num_channels
        snake_case_       						=      last_hidden_size
        snake_case_       						=      num_attention_heads
        snake_case_       						=      hidden_act
        snake_case_       						=      conv_kernel_size
        snake_case_       						=      output_stride
        snake_case_       						=      hidden_dropout_prob
        snake_case_       						=      attention_probs_dropout_prob
        snake_case_       						=      classifier_dropout_prob
        snake_case_       						=      use_labels
        snake_case_       						=      is_training
        snake_case_       						=      num_labels
        snake_case_       						=      initializer_range
        snake_case_       						=      scope







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        snake_case_       						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

        snake_case_       						=      self.get_config()

        return config, pixel_values, labels, pixel_labels







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        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 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       str:
        snake_case_       						=      TFMobileViTModel(config=lowerCamelCase   )
        snake_case_       						=      model(lowerCamelCase							,  training=lowerCamelCase   )
        snake_case_       						=      snake_case_       						=      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 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       Optional[int]:
        snake_case_       						=      self.num_labels
        snake_case_       						=      TFMobileViTForImageClassification(lowerCamelCase   )
        snake_case_       						=      model(lowerCamelCase							,  labels=lowerCamelCase							,  training=lowerCamelCase   )
        self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels)   )







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )						->       str:
        snake_case_       						=      self.num_labels
        snake_case_       						=      TFMobileViTForSemanticSegmentation(lowerCamelCase   )
        snake_case_       						=      snake_case_       						=      self.image_size // self.output_stride

        snake_case_       						=      model(lowerCamelCase							,  training=lowerCamelCase   )
        self.parent.assertEqual(
            result.logits.shape							,  (self.batch_size, self.num_labels, expected_height, expected_width)   )

        snake_case_       						=      model(lowerCamelCase							,  labels=lowerCamelCase							,  training=lowerCamelCase   )
        self.parent.assertEqual(
            result.logits.shape							,  (self.batch_size, self.num_labels, expected_height, expected_width)   )







      def 	lowerCAmelCase_    (     self   )						->       Union[str, Any]:
        snake_case_       						=      self.prepare_config_and_inputs()
        snake_case_						,				snake_case_						,				snake_case_						,				snake_case_       						=      config_and_inputs
        snake_case_       						=      {"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_tf
class  __lowerCamelCase				(	__snake_case  ,							__snake_case  ,							unittest.TestCase	):
      lowerCamelCase_	:      Tuple          =					(
          (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
          if is_tf_available()
          else ()
      )
      lowerCamelCase_	:      List[str]          =					(
          {'feature-extraction': TFMobileViTModel, 'image-classification': TFMobileViTForImageClassification}
          if is_tf_available()
          else {}
      )

      lowerCamelCase_	:      Any          =					False
      lowerCamelCase_	:      Dict          =					False
      lowerCamelCase_	:      int          =					False
      lowerCamelCase_	:      Union[str, Any]          =					False
      lowerCamelCase_	:      Dict          =					False







      def 	lowerCAmelCase_    (     self   )						->       Tuple:
        snake_case_       						=      TFMobileViTModelTester(self   )
        snake_case_       						=      TFMobileViTConfigTester(self							,  config_class=lowerCamelCase							,  has_text_modality=lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Dict:
        self.config_tester.run_common_tests()







      @unittest.skip(reason="""MobileViT does not use inputs_embeds"""   )
      def 	lowerCAmelCase_    (     self   )						->       int:
        pass







      @unittest.skip(reason="""MobileViT does not support input and output embeddings"""   )
      def 	lowerCAmelCase_    (     self   )						->       Tuple:
        pass







      @unittest.skip(reason="""MobileViT does not output attentions"""   )
      def 	lowerCAmelCase_    (     self   )						->       int:
        pass







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_						,				snake_case_       						=      self.model_tester.prepare_config_and_inputs_for_common()

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

          snake_case_       						=      ["""pixel_values"""]
          self.assertListEqual(arg_names[:1]							,  lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        def check_hidden_states_output(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   ):
          snake_case_       						=      model_class(lowerCamelCase   )

          snake_case_       						=      model(**self._prepare_for_class(lowerCamelCase							,  lowerCamelCase   )   )

          snake_case_       						=      outputs.hidden_states

          snake_case_       						=      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_       						=      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_       						=      self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
          snake_case_       						=      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_       						=      True

          check_hidden_states_output(lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Optional[int]:
        snake_case_       						=      self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*lowerCamelCase   )







      def 	lowerCAmelCase_    (     self   )						->       Union[str, Any]:
        snake_case_       						=      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 	lowerCAmelCase_    (     self   )						->       Tuple:
        super().test_dataset_conversion()







      def 	lowerCAmelCase_    (     self							,  lowerCamelCase							,  lowerCamelCase							,  lowerCamelCase=2e-1							,  lowerCamelCase=2e-1   )						->       Optional[Any]:
        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 	lowerCAmelCase_    (     self   )						->       Tuple:
        snake_case_						,				snake_case_       						=      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_       						=      model_class(lowerCamelCase   )
            if getattr(lowerCamelCase							,  """hf_compute_loss"""							,  lowerCamelCase   ):
              super().test_keras_fit()







      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        snake_case_						,				snake_case_       						=      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_       						=      5

          snake_case_       						=      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_       						=      self._prepare_for_class(inputs_dict.copy()							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
            snake_case_       						=      prepared_for_class[
                sorted(prepared_for_class.keys() - inputs_dict.keys()							,  reverse=lowerCamelCase   )[0]
            ]
            snake_case_       						=      added_label.shape.as_list()[:1]

            # Test that model correctly compute the loss with kwargs
            snake_case_       						=      self._prepare_for_class(inputs_dict.copy()							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
            snake_case_       						=      {"""input_ids""", """pixel_values""", """input_features"""}
            snake_case_       						=      possible_input_names.intersection(set(lowerCamelCase   )   ).pop()
            snake_case_       						=      prepared_for_class.pop(lowerCamelCase   )

            snake_case_       						=      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_       						=      self._prepare_for_class(inputs_dict.copy()							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
            snake_case_       						=      {"""input_ids""", """pixel_values""", """input_features"""}
            snake_case_       						=      possible_input_names.intersection(set(lowerCamelCase   )   ).pop()
            snake_case_       						=      prepared_for_class.pop(lowerCamelCase   )
            if "labels" in prepared_for_class:
              snake_case_       						=      prepared_for_class["""labels"""].numpy()
              if len(labels.shape   ) > 1 and labels.shape[1] != 1:
                # labels[0] = -100
                snake_case_       						=      tf.convert_to_tensor(lowerCamelCase   )
                snake_case_       						=      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_       						=      self._prepare_for_class(inputs_dict.copy()							,  lowerCamelCase							,  return_labels=lowerCamelCase   )
            snake_case_       						=      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_       						=      self._prepare_for_class(inputs_dict.copy()							,  lowerCamelCase							,  return_labels=lowerCamelCase   )

            # Get keys that were added with the _prepare_for_class function
            snake_case_       						=      prepared_for_class.keys() - inputs_dict.keys()
            snake_case_       						=      inspect.signature(model.call   ).parameters
            snake_case_       						=      list(signature.keys()   )

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

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

            for index, value in sorted_tuple_index_mapping:
              snake_case_       						=      prepared_for_class[value]

            snake_case_       						=      tuple(lowerCamelCase   )

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

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







      @slow
      def 	lowerCAmelCase_    (     self   )						->       List[str]:
        for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          snake_case_       						=      TFMobileViTModel.from_pretrained(lowerCamelCase   )
          self.assertIsNotNone(lowerCamelCase   )



def    UpperCamelCase(					)	->				Dict:





  '''simple docstring'''





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







@require_tf
class  __lowerCamelCase				(	unittest.TestCase	):







      @slow
      def 	lowerCAmelCase_    (     self   )						->       Any:
        snake_case_       						=      TFMobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""   )

        snake_case_       						=      MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""   )
        snake_case_       						=      prepare_img()
        snake_case_       						=      image_processor(images=lowerCamelCase							,  return_tensors="""tf"""   )

        # forward pass
        snake_case_       						=      model(**lowerCamelCase							,  training=lowerCamelCase   )

        # verify the logits
        snake_case_       						=      tf.TensorShape((1, 1000)   )
        self.assertEqual(outputs.logits.shape							,  lowerCamelCase   )

        snake_case_       						=      tf.constant([-1.9364, -1.2327, -0.4653]   )

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







      @slow
      def 	lowerCAmelCase_    (     self   )						->       List[Any]:
        # `from_pt` will be removed
        snake_case_       						=      TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

        snake_case_       						=      MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""   )

        snake_case_       						=      prepare_img()
        snake_case_       						=      image_processor(images=lowerCamelCase							,  return_tensors="""tf"""   )

        # forward pass
        snake_case_       						=      model(inputs.pixel_values							,  training=lowerCamelCase   )
        snake_case_       						=      outputs.logits

        # verify the logits
        snake_case_       						=      tf.TensorShape((1, 21, 32, 32)   )
        self.assertEqual(logits.shape							,  lowerCamelCase   )

        snake_case_       						=      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]							,  lowerCamelCase							,  rtol=1e-4							,  atol=1e-4   )


from __future__ import annotations

from collections.abc import Generator



def    UpperCamelCase(					lowercase_							)	->				Generator[int, None, None]:





  '''simple docstring'''





  if not isinstance(lowercase_			,					lowercase_							) or n < 1:
    raise Exception("""Sequence only defined for positive integers"""							)

  yield n
  while n != 1:
    if n % 2 == 0:
      n //= 2
    else:
      snake_case_       						=      3 * n + 1
    yield n



def    UpperCamelCase(					)	->				Optional[int]:





  '''simple docstring'''





  snake_case_       						=      43
  snake_case_       						=      tuple(collatz_sequence(lowercase_							)							)
  print(lowercase_							)
  print(f'''Collatz sequence from {n} took {len(lowercase_							)} steps.'''							)


if __name__ == "__main__":
    main()