


"""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_  ( UpperCamelCase_						):







      def 				_lowerCAmelCase       (      self :							Any    ):
        lowerCAmelCase__    :    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  lowercase_  :







      def __init__(      self :							Union[str, Any]		,  _lowercase :							List[str]		,  _lowercase :							Optional[Any]=1_3		,  _lowercase :							List[str]=3_2		,  _lowercase :							Optional[Any]=2		,  _lowercase :							Union[str, Any]=3		,  _lowercase :							Dict=6_4_0		,  _lowercase :							Optional[Any]=4		,  _lowercase :							List[Any]="silu"		,  _lowercase :							Any=3		,  _lowercase :							str=3_2		,  _lowercase :							Dict=0.1		,  _lowercase :							int=0.1		,  _lowercase :							Tuple=0.1		,  _lowercase :							Tuple=0.02		,  _lowercase :							Optional[int]=True		,  _lowercase :							List[Any]=True		,  _lowercase :							Tuple=1_0		,  _lowercase :							Optional[Any]=None		,  ):
        lowerCAmelCase__    :    Tuple								=					parent
        lowerCAmelCase__    :    Dict								=					batch_size
        lowerCAmelCase__    :    Any								=					image_size
        lowerCAmelCase__    :    str								=					patch_size
        lowerCAmelCase__    :    Union[str, Any]								=					num_channels
        lowerCAmelCase__    :    Optional[int]								=					last_hidden_size
        lowerCAmelCase__    :    Optional[Any]								=					num_attention_heads
        lowerCAmelCase__    :    Any								=					hidden_act
        lowerCAmelCase__    :    List[str]								=					conv_kernel_size
        lowerCAmelCase__    :    str								=					output_stride
        lowerCAmelCase__    :    List[Any]								=					hidden_dropout_prob
        lowerCAmelCase__    :    Any								=					attention_probs_dropout_prob
        lowerCAmelCase__    :    List[Any]								=					classifier_dropout_prob
        lowerCAmelCase__    :    int								=					use_labels
        lowerCAmelCase__    :    Optional[Any]								=					is_training
        lowerCAmelCase__    :    Union[str, Any]								=					num_labels
        lowerCAmelCase__    :    Tuple								=					initializer_range
        lowerCAmelCase__    :    Optional[Any]								=					scope







      def 				_lowerCAmelCase       (      self :							Tuple    ):
        lowerCAmelCase__    :    Dict								=					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

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

        return config, pixel_values, labels, pixel_labels







      def 				_lowerCAmelCase       (      self :							Tuple    ):
        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 :							int		,  _lowercase :							Optional[int]		,  _lowercase :							str		,  _lowercase :							Union[str, Any]		,  _lowercase :							Tuple    ):
        lowerCAmelCase__    :    str								=					TFMobileViTModel(config=__UpperCamelCase    )
        lowerCAmelCase__    :    List[str]								=					model(__UpperCamelCase		,  training=__UpperCamelCase    )
        lowerCAmelCase__    :    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 				_lowerCAmelCase       (      self :							Any		,  _lowercase :							Optional[int]		,  _lowercase :							str		,  _lowercase :							Union[str, Any]		,  _lowercase :							List[Any]    ):
        lowerCAmelCase__    :    List[str]								=					self.num_labels
        lowerCAmelCase__    :    List[Any]								=					TFMobileViTForImageClassification(__UpperCamelCase    )
        lowerCAmelCase__    :    Optional[Any]								=					model(__UpperCamelCase		,  labels=__UpperCamelCase		,  training=__UpperCamelCase    )
        self.parent.assertEqual(result.logits.shape		,  (self.batch_size, self.num_labels)    )







      def 				_lowerCAmelCase       (      self :							List[str]		,  _lowercase :							Union[str, Any]		,  _lowercase :							Union[str, Any]		,  _lowercase :							Dict		,  _lowercase :							int    ):
        lowerCAmelCase__    :    Tuple								=					self.num_labels
        lowerCAmelCase__    :    Tuple								=					TFMobileViTForSemanticSegmentation(__UpperCamelCase    )
        lowerCAmelCase__    :    List[Any]								=					self.image_size // self.output_stride

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

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







      def 				_lowerCAmelCase       (      self :							Optional[int]    ):
        lowerCAmelCase__    :    str								=					self.prepare_config_and_inputs()
        lowerCAmelCase__    :    Dict								=					config_and_inputs
        lowerCAmelCase__    :    List[str]								=					{'''pixel_values''': pixel_values}
        return config, inputs_dict

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

      __magic_name__     :							Optional[int]          =				False
      __magic_name__     :							Dict          =				False
      __magic_name__     :							List[Any]          =				False
      __magic_name__     :							Union[str, Any]          =				False
      __magic_name__     :							Optional[int]          =				False







      def 				_lowerCAmelCase       (      self :							Dict    ):
        lowerCAmelCase__    :    Optional[int]								=					TFMobileViTModelTester(self    )
        lowerCAmelCase__    :    Union[str, Any]								=					TFMobileViTConfigTester(self		,  config_class=__UpperCamelCase		,  has_text_modality=__UpperCamelCase    )







      def 				_lowerCAmelCase       (      self :							int    ):
        self.config_tester.run_common_tests()







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







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







      @unittest.skip(reason="MobileViT does not output attentions"    )
      def 				_lowerCAmelCase       (      self :							Optional[Any]    ):
        pass







      def 				_lowerCAmelCase       (      self :							Tuple    ):
        lowerCAmelCase__    :    Tuple								=					self.model_tester.prepare_config_and_inputs_for_common()

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

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







      def 				_lowerCAmelCase       (      self :							Optional[Any]    ):
        lowerCAmelCase__    :    str								=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCamelCase    )







      def 				_lowerCAmelCase       (      self :							str    ):


        def check_hidden_states_output(_lowercase :							Any		,  _lowercase :							List[str]		,  _lowercase :							List[str]    ):
          lowerCAmelCase__    :    Optional[Any]								=					model_class(__UpperCamelCase    )

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

          lowerCAmelCase__    :    Tuple								=					outputs.hidden_states

          lowerCAmelCase__    :    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.
          lowerCAmelCase__    :    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    )

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

        for model_class in self.all_model_classes:
          lowerCAmelCase__    :    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"]
          lowerCAmelCase__    :    List[str]								=					True

          check_hidden_states_output(__UpperCamelCase		,  __UpperCamelCase		,  __UpperCamelCase    )







      def 				_lowerCAmelCase       (      self :							Tuple    ):
        lowerCAmelCase__    :    Any								=					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase    )







      def 				_lowerCAmelCase       (      self :							int    ):
        lowerCAmelCase__    :    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 				_lowerCAmelCase       (      self :							Tuple    ):
        super().test_dataset_conversion()







      def 				_lowerCAmelCase       (      self :							Optional[Any]		,  _lowercase :							List[Any]		,  _lowercase :							Tuple		,  _lowercase :							Optional[int]=2e-1		,  _lowercase :							Tuple=2e-1    ):
        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 				_lowerCAmelCase       (      self :							Optional[Any]    ):
        lowerCAmelCase__    :    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":
            lowerCAmelCase__    :    Optional[Any]								=					model_class(__UpperCamelCase    )
            if getattr(__UpperCamelCase		,  "hf_compute_loss"		,  __UpperCamelCase    ):
              super().test_keras_fit()







      def 				_lowerCAmelCase       (      self :							Optional[int]    ):
        lowerCAmelCase__    :    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":
            lowerCAmelCase__    :    List[str]								=					5

          lowerCAmelCase__    :    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
            lowerCAmelCase__    :    Any								=					self._prepare_for_class(inputs_dict.copy()		,  __UpperCamelCase		,  return_labels=__UpperCamelCase    )
            lowerCAmelCase__    :    Optional[Any]								=					prepared_for_class[
                sorted(prepared_for_class.keys() - inputs_dict.keys()		,  reverse=__UpperCamelCase    )[0]
            ]
            lowerCAmelCase__    :    Union[str, Any]								=					added_label.shape.as_list()[:1]

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

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

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

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

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

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

            lowerCAmelCase__    :    List[str]								=					tuple(__UpperCamelCase    )

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

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







      @slow
      def 				_lowerCAmelCase       (      self :							Union[str, Any]    ):


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





def     lowercase__	(  )					->     Optional[int]:
  lowerCAmelCase__    :    Dict								=					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"				)
  return image







@require_tf
class  lowercase_  ( unittest.TestCase						):







      @slow
      def 				_lowerCAmelCase       (      self :							Tuple    ):
        lowerCAmelCase__    :    Union[str, Any]								=					TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"    )

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

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

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

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

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







      @slow
      def 				_lowerCAmelCase       (      self :							List[str]    ):
        lowerCAmelCase__    :    Tuple								=					TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"    )

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

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

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

        # verify the logits
        lowerCAmelCase__    :    List[Any]								=					tf.TensorShape((1, 2_1, 3_2, 3_2)    )
        self.assertEqual(logits.shape		,  __UpperCamelCase    )

        lowerCAmelCase__    :    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 math import factorial





def     lowercase__	(  lowerCamelCase     :  Dict				,	lowerCamelCase     :  int				)					->     Tuple:
  return factorial(lowerCamelCase				) / (factorial(lowerCamelCase				) * factorial(n - r				))





def     lowercase__	(  )					->     Optional[Any]:
  lowerCAmelCase__    :    List[Any]								=					0

  for i in range(1				,	1_0_1				):
    for j in range(1				,	i + 1				):
      if combinations(lowerCamelCase				,	lowerCamelCase				) > 1e6:
        total += 1
  return total


if __name__ == "__main__":
   print(solution())
