'''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 					a__   (     UpperCAmelCase__				):






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[Any]					):





         """simple docstring"""



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




class 					a__   :






     def __init__(				self	:	int						,       a	:	str						,       a	:	Dict=13						,       a	:	Optional[Any]=32						,       a	:	Union[str, Any]=2						,       a	:	List[str]=3						,       a	:	Any=6_40						,       a	:	Dict=4						,       a	:	List[str]="silu"						,       a	:	str=3						,       a	:	Union[str, Any]=32						,       a	:	Any=0.1						,       a	:	List[Any]=0.1						,       a	:	int=0.1						,       a	:	Dict=0.02						,       a	:	Union[str, Any]=True						,       a	:	Optional[int]=True						,       a	:	str=10						,       a	:	List[str]=None						,       ):





         """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      SCREAMING_SNAKE_CASE__     (				self	:	Tuple					):





         """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      SCREAMING_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      SCREAMING_SNAKE_CASE__     (				self	:	int						,       a	:	Dict						,       a	:	List[str]						,       a	:	Tuple						,       a	:	str					):





         """simple docstring"""



         __lowerCamelCase						=						TFMobileViTModel(config=a					)
         __lowerCamelCase						=						model(a						,       training=a					)
         __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      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]						,       a	:	List[str]						,       a	:	Tuple						,       a	:	Dict						,       a	:	Optional[int]					):





         """simple docstring"""



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






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]						,       a	:	Tuple						,       a	:	Optional[int]						,       a	:	Tuple						,       a	:	Optional[Any]					):





         """simple docstring"""



         __lowerCamelCase						=						self.num_labels
         __lowerCamelCase						=						TFMobileViTForSemanticSegmentation(a					)
         __lowerCamelCase						=						__lowerCamelCase						=						self.image_size // self.output_stride

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

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






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[int]					):





         """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 					a__   (     UpperCAmelCase__							,     UpperCAmelCase__							,     unittest.TestCase				):
     lowerCamelCase						:  Union[str, Any]							=(
         (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
         if is_tf_available()
         else ()
     )
     lowerCamelCase						:  List[Any]							=(
         {"feature-extraction": TFMobileViTModel, "image-classification": TFMobileViTForImageClassification}
         if is_tf_available()
         else {}
     )

     lowerCamelCase						:  str							=False
     lowerCamelCase						:  List[str]							=False
     lowerCamelCase						:  Optional[int]							=False
     lowerCamelCase						:  str							=False
     lowerCamelCase						:  Dict							=False






     def      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """simple docstring"""



         __lowerCamelCase						=						TFMobileViTModelTester(self					)
         __lowerCamelCase						=						TFMobileViTConfigTester(self						,       config_class=a						,       has_text_modality=a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[int]					):





         """simple docstring"""



         self.config_tester.run_common_tests()






     @unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
     def      SCREAMING_SNAKE_CASE__     (				self	:	Tuple					):





         """simple docstring"""



         pass






     @unittest.skip(reason='''MobileViT does not support input and output embeddings'''					)
     def      SCREAMING_SNAKE_CASE__     (				self	:	Optional[Any]					):





         """simple docstring"""



         pass






     @unittest.skip(reason='''MobileViT does not output attentions'''					)
     def      SCREAMING_SNAKE_CASE__     (				self	:	Tuple					):





         """simple docstring"""



         pass






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[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(a					)
             __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]						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	str					):





         """simple docstring"""



         __lowerCamelCase						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	str					):





         """simple docstring"""



         def check_hidden_states_output(a	:	Union[str, Any]						,       a	:	Optional[int]						,       a	:	Optional[int]					):
             __lowerCamelCase						=						model_class(a					)

             __lowerCamelCase						=						model(**self._prepare_for_class(a						,       a					)					)

             __lowerCamelCase						=						outputs.hidden_states

             __lowerCamelCase						=						5
             self.assertEqual(len(a					)						,       a					)

             # 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(a					)					):
                 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(a						,       a						,       a					)

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

             check_hidden_states_output(a						,       a						,       a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Union[str, Any]					):





         """simple docstring"""



         __lowerCamelCase						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*a					)






     def      SCREAMING_SNAKE_CASE__     (				self	:	Any					):





         """simple docstring"""



         __lowerCamelCase						=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*a					)






     @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      SCREAMING_SNAKE_CASE__     (				self	:	Optional[int]					):





         """simple docstring"""



         super().test_dataset_conversion()






     def      SCREAMING_SNAKE_CASE__     (				self	:	List[str]						,       a	:	int						,       a	:	Optional[Any]						,       a	:	Optional[int]=2e-1						,       a	:	List[Any]=2e-1					):





         """simple docstring"""



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






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





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






     def      SCREAMING_SNAKE_CASE__     (				self	:	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(a					)
             if getattr(a						,       '''hf_compute_loss'''						,       a					):
                 # 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()						,       a						,       return_labels=a					)
                 __lowerCamelCase						=						prepared_for_class[
                     sorted(prepared_for_class.keys() - inputs_dict.keys()						,       reverse=a					)[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()						,       a						,       return_labels=a					)
                 __lowerCamelCase						=						{'''input_ids''', '''pixel_values''', '''input_features'''}
                 __lowerCamelCase						=						possible_input_names.intersection(set(a					)					).pop()
                 __lowerCamelCase						=						prepared_for_class.pop(a					)

                 __lowerCamelCase						=						model(a						,       **a					)[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()						,       a						,       return_labels=a					)
                 __lowerCamelCase						=						{'''input_ids''', '''pixel_values''', '''input_features'''}
                 __lowerCamelCase						=						possible_input_names.intersection(set(a					)					).pop()
                 __lowerCamelCase						=						prepared_for_class.pop(a					)
                 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(a					)
                         __lowerCamelCase						=						model(a						,       **a					)[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()						,       a						,       return_labels=a					)
                 __lowerCamelCase						=						model(a					)[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()						,       a						,       return_labels=a					)

                 # 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(a					)
                     __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(a					)

                 # 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      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """simple docstring"""



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






def __lowerCAmelCase				(							)			->					Tuple:
    __lowerCamelCase						=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''       )
    return image




@require_tf
class 					a__   (     unittest.TestCase				):






     @slow
     def      SCREAMING_SNAKE_CASE__     (				self	:	int					):





         """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=a						,       return_tensors='''tf'''					)

         # forward pass
         __lowerCamelCase						=						model(**a						,       training=a					)

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

         __lowerCamelCase						=						tf.constant([-1.93_64, -1.23_27, -0.46_53]					)

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






     @slow
     def      SCREAMING_SNAKE_CASE__     (				self	:	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=a						,       return_tensors='''tf'''					)

         # forward pass
         __lowerCamelCase						=						model(inputs.pixel_values						,       training=a					)
         __lowerCamelCase						=						outputs.logits

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

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

'''simple docstring'''




from __future__ import annotations






def __lowerCAmelCase				(							UpperCamelCase__       ,						UpperCamelCase__       )			->					list:
    __lowerCamelCase						=						[None] * (len(UpperCamelCase__       ) + len(UpperCamelCase__       ))

    __lowerCamelCase						=						0  # pointer to current index for left Half
    __lowerCamelCase						=						0  # pointer to current index for the right Half
    __lowerCamelCase						=						0  # pointer to current index for the sorted array Half

    while pointera < len(UpperCamelCase__       ) and pointera < len(UpperCamelCase__       ):
        if left_half[pointera] < right_half[pointera]:
            __lowerCamelCase						=						left_half[pointera]
            pointera += 1
            index += 1
        else:
            __lowerCamelCase						=						right_half[pointera]
            pointera += 1
            index += 1
    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						left_half[pointera]
        pointera += 1
        index += 1

    while pointera < len(UpperCamelCase__       ):
        __lowerCamelCase						=						right_half[pointera]
        pointera += 1
        index += 1

    return sorted_array






def __lowerCAmelCase				(							UpperCamelCase__       )			->					list:
    if len(UpperCamelCase__       ) <= 1:
        return array
    # the actual formula to calculate the middle element = left + (right - left) // 2
    # this avoids integer overflow in case of large N
    __lowerCamelCase						=						0 + (len(UpperCamelCase__       ) - 0) // 2

    # Split the array into halves till the array length becomes equal to One
    # merge the arrays of single length returned by mergeSort function and
    # pass them into the merge arrays function which merges the array
    __lowerCamelCase						=						array[:middle]
    __lowerCamelCase						=						array[middle:]

    return merge(merge_sort(UpperCamelCase__       )       ,						merge_sort(UpperCamelCase__       )       )


if __name__ == "__main__":
  import doctest

  doctest.testmod()
