



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




       '''simple docstring'''







       def 				snake_case_ (						self   )					->		Dict:

           """simple docstring"""
           UpperCAmelCase     =    self.config_class(**self.inputs_dict   )
           self.parent.assertTrue(hasattr(_snake_case		,       '''hidden_sizes'''   )   )
           self.parent.assertTrue(hasattr(_snake_case		,       '''neck_hidden_sizes'''   )   )
           self.parent.assertTrue(hasattr(_snake_case		,       '''num_attention_heads'''   )   )

class 					lowercase						:




       '''simple docstring'''







       def __init__(						self		,       _snake_case		,       _snake_case=13		,       _snake_case=32		,       _snake_case=2		,       _snake_case=3		,       _snake_case=640		,       _snake_case=4		,       _snake_case="silu"		,       _snake_case=3		,       _snake_case=32		,       _snake_case=0.1		,       _snake_case=0.1		,       _snake_case=0.1		,       _snake_case=0.02		,       _snake_case=True		,       _snake_case=True		,       _snake_case=10		,       _snake_case=None		,       )					->		List[str]:

           """simple docstring"""
           UpperCAmelCase     =    parent
           UpperCAmelCase     =    batch_size
           UpperCAmelCase     =    image_size
           UpperCAmelCase     =    patch_size
           UpperCAmelCase     =    num_channels
           UpperCAmelCase     =    last_hidden_size
           UpperCAmelCase     =    num_attention_heads
           UpperCAmelCase     =    hidden_act
           UpperCAmelCase     =    conv_kernel_size
           UpperCAmelCase     =    output_stride
           UpperCAmelCase     =    hidden_dropout_prob
           UpperCAmelCase     =    attention_probs_dropout_prob
           UpperCAmelCase     =    classifier_dropout_prob
           UpperCAmelCase     =    use_labels
           UpperCAmelCase     =    is_training
           UpperCAmelCase     =    num_labels
           UpperCAmelCase     =    initializer_range
           UpperCAmelCase     =    scope






       def 				snake_case_ (						self   )					->		Dict:

           """simple docstring"""
           UpperCAmelCase     =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

           UpperCAmelCase     =    self.get_config()

           return config, pixel_values, labels, pixel_labels






       def 				snake_case_ (						self   )					->		Dict:

           """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 				snake_case_ (						self		,       _snake_case		,       _snake_case		,       _snake_case		,       _snake_case   )					->		str:

           """simple docstring"""
           UpperCAmelCase     =    TFMobileViTModel(config=_snake_case   )
           UpperCAmelCase     =    model(_snake_case		,       training=_snake_case   )
           UpperCAmelCase     =    UpperCAmelCase     =    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 				snake_case_ (						self		,       _snake_case		,       _snake_case		,       _snake_case		,       _snake_case   )					->		Optional[int]:

           """simple docstring"""
           UpperCAmelCase     =    self.num_labels
           UpperCAmelCase     =    TFMobileViTForImageClassification(_snake_case   )
           UpperCAmelCase     =    model(_snake_case		,       labels=_snake_case		,       training=_snake_case   )
           self.parent.assertEqual(result.logits.shape		,       (self.batch_size, self.num_labels)   )






       def 				snake_case_ (						self		,       _snake_case		,       _snake_case		,       _snake_case		,       _snake_case   )					->		str:

           """simple docstring"""
           UpperCAmelCase     =    self.num_labels
           UpperCAmelCase     =    TFMobileViTForSemanticSegmentation(_snake_case   )
           UpperCAmelCase     =    UpperCAmelCase     =    self.image_size // self.output_stride

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

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






       def 				snake_case_ (						self   )					->		Union[str, Any]:

           """simple docstring"""
           UpperCAmelCase     =    self.prepare_config_and_inputs()
           UpperCAmelCase   ,			UpperCAmelCase   ,			UpperCAmelCase   ,			UpperCAmelCase     =    config_and_inputs
           UpperCAmelCase     =    {'''pixel_values''': pixel_values}
           return config, inputs_dict

@require_tf
class 					lowercase						(	__snake_case				, __snake_case				, unittest.TestCase ):




       '''simple docstring'''







       __SCREAMING_SNAKE_CASE										=					(
           (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
           if is_tf_available()
           else ()
       )
       __SCREAMING_SNAKE_CASE										=					(
           {'feature-extraction': TFMobileViTModel, 'image-classification': TFMobileViTForImageClassification}
           if is_tf_available()
           else {}
       )

       __SCREAMING_SNAKE_CASE										=					False
       __SCREAMING_SNAKE_CASE										=					False
       __SCREAMING_SNAKE_CASE										=					False
       __SCREAMING_SNAKE_CASE										=					False
       __SCREAMING_SNAKE_CASE										=					False






       def 				snake_case_ (						self   )					->		Tuple:

           """simple docstring"""
           UpperCAmelCase     =    TFMobileViTModelTester(self   )
           UpperCAmelCase     =    TFMobileViTConfigTester(self		,       config_class=_snake_case		,       has_text_modality=_snake_case   )






       def 				snake_case_ (						self   )					->		Dict:

           """simple docstring"""
           self.config_tester.run_common_tests()






       @unittest.skip(reason='''MobileViT does not use inputs_embeds'''   )
       def 				snake_case_ (						self   )					->		int:

           """simple docstring"""
           pass






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

           """simple docstring"""
           pass






       @unittest.skip(reason='''MobileViT does not output attentions'''   )
       def 				snake_case_ (						self   )					->		int:

           """simple docstring"""
           pass






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

           """simple docstring"""
           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.call   )
               # 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   )					->		Optional[int]:

           """simple docstring"""
           UpperCAmelCase     =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_snake_case   )






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

           """simple docstring"""
           def check_hidden_states_output(_snake_case		,       _snake_case		,       _snake_case   ):
               UpperCAmelCase     =    model_class(_snake_case   )

               UpperCAmelCase     =    model(**self._prepare_for_class(_snake_case		,       _snake_case   )   )

               UpperCAmelCase     =    outputs.hidden_states

               UpperCAmelCase     =    5
               self.assertEqual(len(_snake_case   )		,       _snake_case   )

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

           UpperCAmelCase   ,			UpperCAmelCase     =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
               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   )






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

           """simple docstring"""
           UpperCAmelCase     =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_snake_case   )






       def 				snake_case_ (						self   )					->		Union[str, Any]:

           """simple docstring"""
           UpperCAmelCase     =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*_snake_case   )






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

           """simple docstring"""
           super().test_dataset_conversion()






       def 				snake_case_ (						self		,       _snake_case		,       _snake_case		,       _snake_case=2e-1		,       _snake_case=2e-1   )					->		Optional[Any]:

           """simple docstring"""
           self.assertTrue(np.allclose(_snake_case		,       _snake_case		,       atol=_snake_case		,       rtol=_snake_case   )   )






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

           """simple docstring"""
           UpperCAmelCase   ,			UpperCAmelCase     =    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":
                   UpperCAmelCase     =    model_class(_snake_case   )
                   if getattr(_snake_case		,       '''hf_compute_loss'''		,       _snake_case   ):
                       super().test_keras_fit()






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

           """simple docstring"""
           UpperCAmelCase   ,			UpperCAmelCase     =    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":
                   UpperCAmelCase     =    5

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

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

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

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

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

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

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

                   UpperCAmelCase     =    tuple(_snake_case   )

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

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






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

           """simple docstring"""
           for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase     =    TFMobileViTModel.from_pretrained(_snake_case   )
               self.assertIsNotNone(_snake_case   )




def 					_lowerCAmelCase   (     ):


    '''simple docstring'''


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


@require_tf
class 					lowercase						(	unittest.TestCase ):




       '''simple docstring'''







       @slow
       def 				snake_case_ (						self   )					->		Any:

           """simple docstring"""
           UpperCAmelCase     =    TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''   )

           UpperCAmelCase     =    MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''   )
           UpperCAmelCase     =    prepare_img()
           UpperCAmelCase     =    image_processor(images=_snake_case		,       return_tensors='''tf'''   )

           # forward pass
           UpperCAmelCase     =    model(**_snake_case		,       training=_snake_case   )

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

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

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






       @slow
       def 				snake_case_ (						self   )					->		List[Any]:

           """simple docstring"""
           # `from_pt` will be removed
           UpperCAmelCase     =    TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''   )

           UpperCAmelCase     =    MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''   )

           UpperCAmelCase     =    prepare_img()
           UpperCAmelCase     =    image_processor(images=_snake_case		,       return_tensors='''tf'''   )

           # forward pass
           UpperCAmelCase     =    model(inputs.pixel_values		,       training=_snake_case   )
           UpperCAmelCase     =    outputs.logits

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

           UpperCAmelCase     =    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]		,       _snake_case		,       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()