


import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
		from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import MobileViTImageProcessor

class 						__a (							snake_case_     ):
		def       UpperCAmelCase__							(     self		)					->			List[str]:




									"""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 						__a :
		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=640     ,       _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     ,       )					->			Optional[int]:




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




									"""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       UpperCAmelCase__							(     self		)					->			List[str]:




									"""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       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     MobileViTModel(config=__snake_case		)
									model.to(__snake_case		)
									model.eval()
									_UpperCAmelCase											=     model(__snake_case		)
									self.parent.assertEqual(
									    result.last_hidden_state.shape     ,       (
									        self.batch_size,
									        self.last_hidden_size,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )     ,       )
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Optional[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.num_labels
									_UpperCAmelCase											=     MobileViTForImageClassification(__snake_case		)
									model.to(__snake_case		)
									model.eval()
									_UpperCAmelCase											=     model(__snake_case     ,       labels=__snake_case		)
									self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.num_labels)		)
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.num_labels
									_UpperCAmelCase											=     MobileViTForSemanticSegmentation(__snake_case		)
									model.to(__snake_case		)
									model.eval()
									_UpperCAmelCase											=     model(__snake_case		)
									self.parent.assertEqual(
									    result.logits.shape     ,       (
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )     ,       )
									_UpperCAmelCase											=     model(__snake_case     ,       labels=__snake_case		)
									self.parent.assertEqual(
									    result.logits.shape     ,       (
									        self.batch_size,
									        self.num_labels,
									        self.image_size // self.output_stride,
									        self.image_size // self.output_stride,
									    )     ,       )






		def       UpperCAmelCase__							(     self		)					->			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_torch
class 						__a (							snake_case_       , snake_case_       , unittest.TestCase     ):
		_a      :    str           =      (
		    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		_a      :    Any           =      (
		    {
		        '''feature-extraction''': MobileViTModel,
		        '''image-classification''': MobileViTForImageClassification,
		        '''image-segmentation''': MobileViTForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		_a      :    Union[str, Any]           =      False
		_a      :    Optional[int]           =      False
		_a      :    Optional[Any]           =      False
		_a      :    str           =      False
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     MobileViTModelTester(self		)
									_UpperCAmelCase											=     MobileViTConfigTester(self     ,       config_class=__snake_case     ,       has_text_modality=__snake_case		)
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									self.config_tester.run_common_tests()
		@unittest.skip(reason='MobileViT does not use inputs_embeds'		)
		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





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




									"""simple docstring"""





									pass
		@unittest.skip(reason='MobileViT does not output attentions'		)
		def       UpperCAmelCase__							(     self		)					->			Union[str, Any]:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Union[str, 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.forward		)
																# 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		)
		@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									pass
		def       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__snake_case		)
		def       UpperCAmelCase__							(     self		)					->			List[str]:




									"""simple docstring"""





									def check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase											=     model_class(__snake_case		)
																model.to(__snake_case		)
																model.eval()

																with torch.no_grad():
																							_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       UpperCAmelCase__							(     self		)					->			Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__snake_case		)
		def       UpperCAmelCase__							(     self		)					->			List[Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*__snake_case		)






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




									"""simple docstring"""





									for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCAmelCase											=     MobileViTModel.from_pretrained(__snake_case		)
																self.assertIsNotNone(__snake_case		)



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


							'''simple docstring'''





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







@require_torch
@require_vision
class 						__a (							unittest.TestCase     ):
		@cached_property
		def       UpperCAmelCase__							(     self		)					->			Any:




									"""simple docstring"""





									return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'		) if is_vision_available() else None
		@slow
		def       UpperCAmelCase__							(     self		)					->			Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase											=     MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'		).to(__snake_case		)

									_UpperCAmelCase											=     self.default_image_processor
									_UpperCAmelCase											=     prepare_img()
									_UpperCAmelCase											=     image_processor(images=__snake_case     ,       return_tensors='pt'		).to(__snake_case		)

									# forward pass
									with torch.no_grad():
																_UpperCAmelCase											=     model(**__snake_case		)

									# verify the logits
									_UpperCAmelCase											=     torch.Size((1, 1000)		)
									self.assertEqual(outputs.logits.shape     ,       __snake_case		)

									_UpperCAmelCase											=     torch.tensor([-1.9364, -1.2327, -0.4653]		).to(__snake_case		)

									self.assertTrue(torch.allclose(outputs.logits[0, :3]     ,       __snake_case     ,       atol=1e-4		)		)
		@slow
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
									_UpperCAmelCase											=     model.to(__snake_case		)

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

									_UpperCAmelCase											=     prepare_img()
									_UpperCAmelCase											=     image_processor(images=__snake_case     ,       return_tensors='pt'		).to(__snake_case		)

									# forward pass
									with torch.no_grad():
																_UpperCAmelCase											=     model(**__snake_case		)
									_UpperCAmelCase											=     outputs.logits

									# verify the logits
									_UpperCAmelCase											=     torch.Size((1, 21, 32, 32)		)
									self.assertEqual(logits.shape     ,       __snake_case		)

									_UpperCAmelCase											=     torch.tensor(
									    [
									        [[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]],
									    ]     ,       device=__snake_case     ,       )

									self.assertTrue(torch.allclose(logits[0, :3, :3, :3]     ,       __snake_case     ,       atol=1e-4		)		)






		@slow
		def       UpperCAmelCase__							(     self		)					->			Optional[int]:




									"""simple docstring"""





									_UpperCAmelCase											=     MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
									_UpperCAmelCase											=     model.to(__snake_case		)

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

									_UpperCAmelCase											=     prepare_img()
									_UpperCAmelCase											=     image_processor(images=__snake_case     ,       return_tensors='pt'		).to(__snake_case		)

									# forward pass
									with torch.no_grad():
																_UpperCAmelCase											=     model(**__snake_case		)

									_UpperCAmelCase											=     outputs.logits.detach().cpu()

									_UpperCAmelCase											=     image_processor.post_process_semantic_segmentation(outputs=__snake_case     ,       target_sizes=[(50, 60)]		)
									_UpperCAmelCase											=     torch.Size((50, 60)		)
									self.assertEqual(segmentation[0].shape     ,       __snake_case		)

									_UpperCAmelCase											=     image_processor.post_process_semantic_segmentation(outputs=__snake_case		)
									_UpperCAmelCase											=     torch.Size((32, 32)		)
									self.assertEqual(segmentation[0].shape     ,       __snake_case		)







'''simple docstring'''






def   UpperCamelCase__ (						lowerCAmelCase    ):





      """simple docstring"""


      if not isinstance(lowerCAmelCase				,      lowerCAmelCase    ):
            raise ValueError("""Input must be an integer"""    )
      if input_num <= 0:
            raise ValueError("""Input must be positive"""    )
      return sum(
          divisor for divisor in range(1				,      input_num // 2 + 1    ) if input_num % divisor == 0    )


if __name__ == "__main__":
      import doctest

      doctest.testmod()






