






"""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        __lowercase(       snake_case_  ):






      def 		lowerCAmelCase   (					self)			->  Dict:




           """simple docstring"""





           lowerCamelCase__				=self.config_class(**self.inputs_dict)
           self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE    ,						'hidden_sizes'))
           self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE    ,						'neck_hidden_sizes'))
           self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE    ,						'num_attention_heads'))




class        __lowercase:






      def __init__(					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=13    ,						_SCREAMING_SNAKE_CASE=32    ,						_SCREAMING_SNAKE_CASE=2    ,						_SCREAMING_SNAKE_CASE=3    ,						_SCREAMING_SNAKE_CASE=6_40    ,						_SCREAMING_SNAKE_CASE=4    ,						_SCREAMING_SNAKE_CASE="silu"    ,						_SCREAMING_SNAKE_CASE=3    ,						_SCREAMING_SNAKE_CASE=32    ,						_SCREAMING_SNAKE_CASE=0.1    ,						_SCREAMING_SNAKE_CASE=0.1    ,						_SCREAMING_SNAKE_CASE=0.1    ,						_SCREAMING_SNAKE_CASE=0.02    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=True    ,						_SCREAMING_SNAKE_CASE=10    ,						_SCREAMING_SNAKE_CASE=None    ,						)			->  List[Any]:




           """simple docstring"""





           lowerCamelCase__				=parent
           lowerCamelCase__				=batch_size
           lowerCamelCase__				=image_size
           lowerCamelCase__				=patch_size
           lowerCamelCase__				=num_channels
           lowerCamelCase__				=last_hidden_size
           lowerCamelCase__				=num_attention_heads
           lowerCamelCase__				=hidden_act
           lowerCamelCase__				=conv_kernel_size
           lowerCamelCase__				=output_stride
           lowerCamelCase__				=hidden_dropout_prob
           lowerCamelCase__				=attention_probs_dropout_prob
           lowerCamelCase__				=classifier_dropout_prob
           lowerCamelCase__				=use_labels
           lowerCamelCase__				=is_training
           lowerCamelCase__				=num_labels
           lowerCamelCase__				=initializer_range
           lowerCamelCase__				=scope






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




           """simple docstring"""





           lowerCamelCase__				=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

           lowerCamelCase__				=self.get_config()

           return config, pixel_values, labels, pixel_labels






      def 		lowerCAmelCase   (					self)			->  Any:




           """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 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Optional[Any]:




           """simple docstring"""





           lowerCamelCase__				=TFMobileViTModel(config=_SCREAMING_SNAKE_CASE)
           lowerCamelCase__				=model(_SCREAMING_SNAKE_CASE    ,						training=_SCREAMING_SNAKE_CASE)
           lowerCamelCase__				=lowerCamelCase__				=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    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Dict:




           """simple docstring"""





           lowerCamelCase__				=self.num_labels
           lowerCamelCase__				=TFMobileViTForImageClassification(_SCREAMING_SNAKE_CASE)
           lowerCamelCase__				=model(_SCREAMING_SNAKE_CASE    ,						labels=_SCREAMING_SNAKE_CASE    ,						training=_SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels))






      def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)			->  Optional[int]:




           """simple docstring"""





           lowerCamelCase__				=self.num_labels
           lowerCamelCase__				=TFMobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE)
           lowerCamelCase__				=lowerCamelCase__				=self.image_size // self.output_stride

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

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






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




           """simple docstring"""





           lowerCamelCase__				=self.prepare_config_and_inputs()
           lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				,     lowerCamelCase__				=config_and_inputs
           lowerCamelCase__				={'pixel_values': pixel_values}
           return config, inputs_dict




@require_tf
class        __lowercase(       snake_case_						,							snake_case_						,							unittest.TestCase  ):
      lowerCAmelCase_		:							Dict=       (
          (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
          if is_tf_available()
          else ()
      )
      lowerCAmelCase_		:							List[str]=       (
          {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
          if is_tf_available()
          else {}
      )

      lowerCAmelCase_		:							List[str]=       False
      lowerCAmelCase_		:							Optional[int]=       False
      lowerCAmelCase_		:							Optional[int]=       False
      lowerCAmelCase_		:							Tuple=       False
      lowerCAmelCase_		:							int=       False






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




           """simple docstring"""





           lowerCamelCase__				=TFMobileViTModelTester(self)
           lowerCamelCase__				=TFMobileViTConfigTester(self    ,						config_class=_SCREAMING_SNAKE_CASE    ,						has_text_modality=_SCREAMING_SNAKE_CASE)






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




           """simple docstring"""





           self.config_tester.run_common_tests()






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




           """simple docstring"""





           pass






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




           """simple docstring"""





           pass






      @unittest.skip(reason='MobileViT does not output attentions')
      def 		lowerCAmelCase   (					self)			->  List[Any]:




           """simple docstring"""





           pass






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




           """simple docstring"""





           lowerCamelCase__				,     lowerCamelCase__				=self.model_tester.prepare_config_and_inputs_for_common()

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

                lowerCamelCase__				=['pixel_values']
                self.assertListEqual(arg_names[:1]    ,						_SCREAMING_SNAKE_CASE)






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




           """simple docstring"""





           lowerCamelCase__				=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE)






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




           """simple docstring"""





           def check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE):
                lowerCamelCase__				=model_class(_SCREAMING_SNAKE_CASE)

                lowerCamelCase__				=model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE))

                lowerCamelCase__				=outputs.hidden_states

                lowerCamelCase__				=5
                self.assertEqual(len(_SCREAMING_SNAKE_CASE)    ,						_SCREAMING_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.
                lowerCamelCase__				=2
                for i in range(len(_SCREAMING_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)

           lowerCamelCase__				,     lowerCamelCase__				=self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                lowerCamelCase__				=True
                check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)

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

                check_hidden_states_output(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE)






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




           """simple docstring"""





           lowerCamelCase__				=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE)






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




           """simple docstring"""





           lowerCamelCase__				=self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_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 		lowerCAmelCase   (					self)			->  Any:




           """simple docstring"""





           super().test_dataset_conversion()






      def 		lowerCAmelCase   (					self    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE=2E-1    ,						_SCREAMING_SNAKE_CASE=2E-1)			->  List[str]:




           """simple docstring"""





           self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE    ,						_SCREAMING_SNAKE_CASE    ,						atol=_SCREAMING_SNAKE_CASE    ,						rtol=_SCREAMING_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 		lowerCAmelCase   (					self)			->  Dict:




           """simple docstring"""





           lowerCamelCase__				,     lowerCamelCase__				=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":
                     lowerCamelCase__				=model_class(_SCREAMING_SNAKE_CASE)
                     if getattr(_SCREAMING_SNAKE_CASE    ,						'hf_compute_loss'    ,						_SCREAMING_SNAKE_CASE):
                          super().test_keras_fit()






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




           """simple docstring"""





           lowerCamelCase__				,     lowerCamelCase__				=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":
                     lowerCamelCase__				=5

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

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

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

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

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

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

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

                     lowerCamelCase__				=tuple(_SCREAMING_SNAKE_CASE)

                     # Send to model
                     lowerCamelCase__				=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]:




           """simple docstring"""





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




def 						lowerCamelCase_				(  ):
     lowerCamelCase__				=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     return image




@require_tf
class        __lowercase(       unittest.TestCase  ):






      @slow
      def 		lowerCAmelCase   (					self)			->  Optional[Any]:




           """simple docstring"""





           lowerCamelCase__				=TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small')

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

           # forward pass
           lowerCamelCase__				=model(**_SCREAMING_SNAKE_CASE    ,						training=_SCREAMING_SNAKE_CASE)

           # verify the logits
           lowerCamelCase__				=tf.TensorShape((1, 10_00))
           self.assertEqual(outputs.logits.shape    ,						_SCREAMING_SNAKE_CASE)

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

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






      @slow
      def 		lowerCAmelCase   (					self)			->  Union[str, Any]:




           """simple docstring"""





           lowerCamelCase__				=TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small')

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

           lowerCamelCase__				=prepare_img()
           lowerCamelCase__				=image_processor(images=_SCREAMING_SNAKE_CASE    ,						return_tensors='tf')

           # forward pass
           lowerCamelCase__				=model(inputs.pixel_values    ,						training=_SCREAMING_SNAKE_CASE)
           lowerCamelCase__				=outputs.logits

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

           lowerCamelCase__				=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]    ,						_SCREAMING_SNAKE_CASE    ,						rtol=1E-4    ,						atol=1E-4)







"""simple docstring"""



from doctest import testmod
from math import sqrt




def 						lowerCamelCase_				(  __A  :		int			):
					lowerCamelCase__				=[]
					if num < 1:
										return facs
					facs.append(1			)
					if num == 1:
										return facs
					facs.append(__A			)
					for i in range(2			,	int(sqrt(__A			)			) + 1			):
										if num % i == 0:  # If i is a factor of num
															facs.append(__A			)
															lowerCamelCase__				=num // i  # num//i is the other factor of num
															if d != i:  # If d and i are distinct
																				facs.append(__A			)  # we have found another factor
					facs.sort()
					return facs


if __name__ == "__main__":
						testmod(name="factors_of_a_number", verbose=True)