


'''simple docstring'''



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




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Any        =     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 		_snake_case					:




					def __init__(      self							,							_lowerCamelCase							,							_lowerCamelCase=13							,							_lowerCamelCase=32							,							_lowerCamelCase=2							,							_lowerCamelCase=3							,							_lowerCamelCase=640							,							_lowerCamelCase=4							,							_lowerCamelCase="silu"							,							_lowerCamelCase=3							,							_lowerCamelCase=32							,							_lowerCamelCase=0.1							,							_lowerCamelCase=0.1							,							_lowerCamelCase=0.1							,							_lowerCamelCase=0.02							,							_lowerCamelCase=True							,							_lowerCamelCase=True							,							_lowerCamelCase=10							,							_lowerCamelCase=None							,							):
								UpperCAmelCase__  :					str        =     parent
								UpperCAmelCase__  :					Any        =     batch_size
								UpperCAmelCase__  :					str        =     image_size
								UpperCAmelCase__  :					Tuple        =     patch_size
								UpperCAmelCase__  :					Union[str, Any]        =     num_channels
								UpperCAmelCase__  :					int        =     last_hidden_size
								UpperCAmelCase__  :					Any        =     num_attention_heads
								UpperCAmelCase__  :					Tuple        =     hidden_act
								UpperCAmelCase__  :					List[str]        =     conv_kernel_size
								UpperCAmelCase__  :					int        =     output_stride
								UpperCAmelCase__  :					Optional[Any]        =     hidden_dropout_prob
								UpperCAmelCase__  :					Optional[Any]        =     attention_probs_dropout_prob
								UpperCAmelCase__  :					Optional[Any]        =     classifier_dropout_prob
								UpperCAmelCase__  :					Dict        =     use_labels
								UpperCAmelCase__  :					Union[str, Any]        =     is_training
								UpperCAmelCase__  :					Any        =     num_labels
								UpperCAmelCase__  :					str        =     initializer_range
								UpperCAmelCase__  :					Tuple        =     scope




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[str]        =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

								UpperCAmelCase__  :					str        =     None
								UpperCAmelCase__  :					List[str]        =     None
								if self.use_labels:
											UpperCAmelCase__  :					Optional[int]        =     ids_tensor([self.batch_size]							,							self.num_labels)
											UpperCAmelCase__  :					Any        =     ids_tensor([self.batch_size, self.image_size, self.image_size]							,							self.num_labels)

								UpperCAmelCase__  :					Dict        =     self.get_config()

								return config, pixel_values, labels, pixel_labels




					def 				snake_case__						(      self):
								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							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
								UpperCAmelCase__  :					Optional[int]        =     MobileViTModel(config=__UpperCamelCase)
								model.to(__UpperCamelCase)
								model.eval()
								UpperCAmelCase__  :					Optional[int]        =     model(__UpperCamelCase)
								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 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
								UpperCAmelCase__  :					Optional[Any]        =     self.num_labels
								UpperCAmelCase__  :					Optional[Any]        =     MobileViTForImageClassification(__UpperCamelCase)
								model.to(__UpperCamelCase)
								model.eval()
								UpperCAmelCase__  :					Tuple        =     model(__UpperCamelCase							,							labels=__UpperCamelCase)
								self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.num_labels))




					def 				snake_case__						(      self							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
								UpperCAmelCase__  :					Optional[int]        =     self.num_labels
								UpperCAmelCase__  :					Union[str, Any]        =     MobileViTForSemanticSegmentation(__UpperCamelCase)
								model.to(__UpperCamelCase)
								model.eval()
								UpperCAmelCase__  :					Tuple        =     model(__UpperCamelCase)
								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__  :					str        =     model(__UpperCamelCase							,							labels=__UpperCamelCase)
								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 				snake_case__						(      self):
								UpperCAmelCase__  :					List[Any]        =     self.prepare_config_and_inputs()
								UpperCAmelCase__   ,       UpperCAmelCase__   ,       UpperCAmelCase__   ,       UpperCAmelCase__  :					Optional[int]        =     config_and_inputs
								UpperCAmelCase__  :					List[Any]        =     {"""pixel_values""": pixel_values}
								return config, inputs_dict


@require_torch
class 		_snake_case					(     __snake_case       ,   __snake_case       ,   unittest.TestCase	):
					lowerCAmelCase      :Optional[int]   =					(
					    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)
					lowerCAmelCase      :Optional[Any]   =					(
					    {
					        '''feature-extraction''': MobileViTModel,
					        '''image-classification''': MobileViTForImageClassification,
					        '''image-segmentation''': MobileViTForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					lowerCAmelCase      :List[Any]   =					False
					lowerCAmelCase      :List[Any]   =					False
					lowerCAmelCase      :List[Any]   =					False
					lowerCAmelCase      :List[str]   =					False




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Optional[Any]        =     MobileViTModelTester(self)
								UpperCAmelCase__  :					Optional[int]        =     MobileViTConfigTester(self							,							config_class=__UpperCamelCase							,							has_text_modality=__UpperCamelCase)




					def 				snake_case__						(      self):
								self.config_tester.run_common_tests()




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




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




					@unittest.skip(reason="""MobileViT does not output attentions""")
					def 				snake_case__						(      self):
								pass




					def 				snake_case__						(      self):
								UpperCAmelCase__   ,       UpperCAmelCase__  :					List[str]        =     self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											UpperCAmelCase__  :					Any        =     model_class(__UpperCamelCase)
											UpperCAmelCase__  :					Optional[Any]        =     inspect.signature(model.forward)
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											UpperCAmelCase__  :					Optional[Any]        =     [*signature.parameters.keys()]

											UpperCAmelCase__  :					Optional[Any]        =     ["""pixel_values"""]
											self.assertListEqual(arg_names[:1]							,							__UpperCamelCase)




					@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests.""")
					def 				snake_case__						(      self):
								pass




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Any        =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__UpperCamelCase)




					def 				snake_case__						(      self):


								def check_hidden_states_output(_lowerCamelCase							,							_lowerCamelCase							,							_lowerCamelCase):
											UpperCAmelCase__  :					int        =     model_class(__UpperCamelCase)
											model.to(__UpperCamelCase)
											model.eval()

											with torch.no_grad():
														UpperCAmelCase__  :					Tuple        =     model(**self._prepare_for_class(__UpperCamelCase							,							__UpperCamelCase))

											UpperCAmelCase__  :					Dict        =     outputs.hidden_states

											UpperCAmelCase__  :					str        =     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.
											UpperCAmelCase__  :					Union[str, Any]        =     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)

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

								for model_class in self.all_model_classes:
											UpperCAmelCase__  :					str        =     True
											check_hidden_states_output(__UpperCamelCase							,							__UpperCamelCase							,							__UpperCamelCase)

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											UpperCAmelCase__  :					Tuple        =     True

											check_hidden_states_output(__UpperCamelCase							,							__UpperCamelCase							,							__UpperCamelCase)




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					Any        =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase)




					def 				snake_case__						(      self):
								UpperCAmelCase__  :					str        =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase)




					@slow
					def 				snake_case__						(      self):


								for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											UpperCAmelCase__  :					Tuple        =     MobileViTModel.from_pretrained(__UpperCamelCase)
											self.assertIsNotNone(__UpperCamelCase)







def     _UpperCamelCase      (		):
			UpperCAmelCase__  :					Optional[int]        =     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
			return image


@require_torch
@require_vision
class 		_snake_case					(     unittest.TestCase	):




					@cached_property
					def 				snake_case__						(      self):
								return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small""") if is_vision_available() else None




					@slow
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[str]        =     MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small""").to(__UpperCamelCase)

								UpperCAmelCase__  :					Any        =     self.default_image_processor
								UpperCAmelCase__  :					Tuple        =     prepare_img()
								UpperCAmelCase__  :					Optional[Any]        =     image_processor(images=__UpperCamelCase							,							return_tensors="""pt""").to(__UpperCamelCase)

								# forward pass
								with torch.no_grad():
											UpperCAmelCase__  :					int        =     model(**__UpperCamelCase)

								# verify the logits
								UpperCAmelCase__  :					List[str]        =     torch.Size((1, 1000))
								self.assertEqual(outputs.logits.shape							,							__UpperCamelCase)

								UpperCAmelCase__  :					Union[str, Any]        =     torch.tensor([-1.9364, -1.2327, -0.4653]).to(__UpperCamelCase)

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




					@slow
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[Any]        =     MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""")
								UpperCAmelCase__  :					List[Any]        =     model.to(__UpperCamelCase)

								UpperCAmelCase__  :					Tuple        =     MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""")

								UpperCAmelCase__  :					List[str]        =     prepare_img()
								UpperCAmelCase__  :					Any        =     image_processor(images=__UpperCamelCase							,							return_tensors="""pt""").to(__UpperCamelCase)

								# forward pass
								with torch.no_grad():
											UpperCAmelCase__  :					Dict        =     model(**__UpperCamelCase)
								UpperCAmelCase__  :					Dict        =     outputs.logits

								# verify the logits
								UpperCAmelCase__  :					Tuple        =     torch.Size((1, 21, 32, 32))
								self.assertEqual(logits.shape							,							__UpperCamelCase)

								UpperCAmelCase__  :					List[str]        =     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=__UpperCamelCase							,							)

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




					@slow
					def 				snake_case__						(      self):
								UpperCAmelCase__  :					List[Any]        =     MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""")
								UpperCAmelCase__  :					List[str]        =     model.to(__UpperCamelCase)

								UpperCAmelCase__  :					Optional[Any]        =     MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small""")

								UpperCAmelCase__  :					Optional[Any]        =     prepare_img()
								UpperCAmelCase__  :					Optional[Any]        =     image_processor(images=__UpperCamelCase							,							return_tensors="""pt""").to(__UpperCamelCase)

								# forward pass
								with torch.no_grad():
											UpperCAmelCase__  :					Tuple        =     model(**__UpperCamelCase)

								UpperCAmelCase__  :					str        =     outputs.logits.detach().cpu()

								UpperCAmelCase__  :					Any        =     image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase							,							target_sizes=[(50, 60)])
								UpperCAmelCase__  :					Any        =     torch.Size((50, 60))
								self.assertEqual(segmentation[0].shape							,							__UpperCamelCase)

								UpperCAmelCase__  :					Dict        =     image_processor.post_process_semantic_segmentation(outputs=__UpperCamelCase)
								UpperCAmelCase__  :					List[Any]        =     torch.Size((32, 32))
								self.assertEqual(segmentation[0].shape							,							__UpperCamelCase)



'''simple docstring'''



import warnings
from functools import wraps
from typing import Callable







def     _UpperCamelCase      (		UpperCamelCase__					):

			@wraps(UpperCamelCase__					)
			def _inner_fn(*UpperCamelCase__ ,      **UpperCamelCase__					):
						warnings.warn(
						    (f'''\'{fn.__name__}\' is experimental and might be subject to breaking changes in the future.''') ,      UpperCamelCase__ ,      )
						return fn(*UpperCamelCase__ ,      **UpperCamelCase__					)

			return _inner_fn