

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 _UpperCamelCase				(				__A ):
			'''simple docstring'''







			def 				__UpperCamelCase			(      self				:			List[str]						)				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							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 _UpperCamelCase				:
			'''simple docstring'''







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

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Dict					  =							parent
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							batch_size
				SCREAMING_SNAKE_CASE :   Any					  =							image_size
				SCREAMING_SNAKE_CASE :   Dict					  =							patch_size
				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							num_channels
				SCREAMING_SNAKE_CASE :   int					  =							last_hidden_size
				SCREAMING_SNAKE_CASE :   str					  =							num_attention_heads
				SCREAMING_SNAKE_CASE :   Tuple					  =							hidden_act
				SCREAMING_SNAKE_CASE :   Tuple					  =							conv_kernel_size
				SCREAMING_SNAKE_CASE :   List[Any]					  =							output_stride
				SCREAMING_SNAKE_CASE :   List[str]					  =							hidden_dropout_prob
				SCREAMING_SNAKE_CASE :   List[str]					  =							attention_probs_dropout_prob
				SCREAMING_SNAKE_CASE :   List[Any]					  =							classifier_dropout_prob
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							use_labels
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							is_training
				SCREAMING_SNAKE_CASE :   Any					  =							num_labels
				SCREAMING_SNAKE_CASE :   Dict					  =							initializer_range
				SCREAMING_SNAKE_CASE :   List[Any]					  =							scope
			def 				__UpperCamelCase			(      self				:			Dict						)				->							Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

				SCREAMING_SNAKE_CASE :   List[str]					  =							self.get_config()

				return config, pixel_values, labels, pixel_labels
			def 				__UpperCamelCase			(      self				:			Optional[Any]						)				->							Optional[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 				__UpperCamelCase			(      self				:			Optional[Any]   ,   a				:			Optional[Any]   ,   a				:			Optional[int]   ,   a				:			Optional[int]   ,   a				:			Tuple						)				->							Any:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							MobileViTModel(config=a						)
				model.to(a						)
				model.eval()
				SCREAMING_SNAKE_CASE :   Optional[Any]					  =							model(a						)
				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				:			Any   ,   a				:			Tuple   ,   a				:			Any   ,   a				:			List[Any]   ,   a				:			Union[str, Any]						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   str					  =							self.num_labels
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							MobileViTForImageClassification(a						)
				model.to(a						)
				model.eval()
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							model(a   ,   labels=a						)
				self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.num_labels)						)
			def 				__UpperCamelCase			(      self				:			Optional[int]   ,   a				:			List[str]   ,   a				:			Tuple   ,   a				:			Optional[int]   ,   a				:			Dict						)				->							int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							self.num_labels
				SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							MobileViTForSemanticSegmentation(a						)
				model.to(a						)
				model.eval()
				SCREAMING_SNAKE_CASE :   Tuple					  =							model(a						)
				self.parent.assertEqual(
				    result.logits.shape   ,   (
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    )   ,   )
				SCREAMING_SNAKE_CASE :   Tuple					  =							model(a   ,   labels=a						)
				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				:			Union[str, Any]						)				->							Optional[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   int					  =							self.prepare_config_and_inputs()
				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   List[str]					  =							config_and_inputs
				SCREAMING_SNAKE_CASE :   Any					  =							{"pixel_values": pixel_values}
				return config, inputs_dict






@require_torch
class _UpperCamelCase				(				__A				,						__A				,						unittest.TestCase ):
			'''simple docstring'''







			lowerCamelCase__							     =(
			    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			lowerCamelCase__							     =(
			    {
			        'feature-extraction': MobileViTModel,
			        'image-classification': MobileViTForImageClassification,
			        'image-segmentation': MobileViTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			lowerCamelCase__							     =False
			lowerCamelCase__							     =False
			lowerCamelCase__							     =False
			lowerCamelCase__							     =False
			def 				__UpperCamelCase			(      self				:			str						)				->							List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							MobileViTModelTester(self						)
				SCREAMING_SNAKE_CASE :   Tuple					  =							MobileViTConfigTester(self   ,   config_class=a   ,   has_text_modality=a						)
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							Dict:

				"""simple docstring"""

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

				"""simple docstring"""

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

				"""simple docstring"""

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

				"""simple docstring"""

				pass
			def 				__UpperCamelCase			(      self				:			Any						)				->							List[Any]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   Dict					  =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE :   Tuple					  =							model_class(a						)
					SCREAMING_SNAKE_CASE :   str					  =							inspect.signature(model.forward						)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					SCREAMING_SNAKE_CASE :   Dict					  =							[*signature.parameters.keys()]

					SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							["pixel_values"]
					self.assertListEqual(arg_names[:1]   ,   a						)
			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."						)
			def 				__UpperCamelCase			(      self				:			Optional[Any]						)				->							str:

				"""simple docstring"""

				pass
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Tuple					  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*a						)
			def 				__UpperCamelCase			(      self				:			str						)				->							Tuple:

				"""simple docstring"""

				def check_hidden_states_output(a				:			Tuple   ,   a				:			Tuple   ,   a				:			Optional[Any]						):
					SCREAMING_SNAKE_CASE :   str					  =							model_class(a						)
					model.to(a						)
					model.eval()

					with torch.no_grad():
						SCREAMING_SNAKE_CASE :   List[Any]					  =							model(**self._prepare_for_class(a   ,   a						)						)

					SCREAMING_SNAKE_CASE :   List[str]					  =							outputs.hidden_states

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

				SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   Tuple					  =							self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					SCREAMING_SNAKE_CASE :   Dict					  =							True
					check_hidden_states_output(a   ,   a   ,   a						)

					# check that output_hidden_states also work using config
					del inputs_dict["output_hidden_states"]
					SCREAMING_SNAKE_CASE :   List[Any]					  =							True

					check_hidden_states_output(a   ,   a   ,   a						)
			def 				__UpperCamelCase			(      self				:			Tuple						)				->							int:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Dict					  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*a						)
			def 				__UpperCamelCase			(      self				:			str						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Dict					  =							self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*a						)






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

				"""simple docstring"""

				for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					SCREAMING_SNAKE_CASE :   List[Any]					  =							MobileViTModel.from_pretrained(a						)
					self.assertIsNotNone(a						)

def 			lowerCamelCase__			(       ):
	SCREAMING_SNAKE_CASE :   Tuple					  =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
	return image






@require_torch
@require_vision
class _UpperCamelCase				(				unittest.TestCase ):
			'''simple docstring'''







			@cached_property
			def 				__UpperCamelCase			(      self				:			str						)				->							List[Any]:

				"""simple docstring"""

				return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"						) if is_vision_available() else None
			@slow
			def 				__UpperCamelCase			(      self				:			Dict						)				->							Tuple:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   int					  =							MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"						).to(a						)

				SCREAMING_SNAKE_CASE :   Dict					  =							self.default_image_processor
				SCREAMING_SNAKE_CASE :   List[Any]					  =							prepare_img()
				SCREAMING_SNAKE_CASE :   str					  =							image_processor(images=a   ,   return_tensors="pt"						).to(a						)

				# forward pass
				with torch.no_grad():
					SCREAMING_SNAKE_CASE :   List[str]					  =							model(**a						)

				# verify the logits
				SCREAMING_SNAKE_CASE :   Tuple					  =							torch.Size((1, 1000)						)
				self.assertEqual(outputs.logits.shape   ,   a						)

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

				self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,   a   ,   atol=1e-4						)						)
			@slow
			def 				__UpperCamelCase			(      self				:			int						)				->							Dict:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   List[Any]					  =							MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"						)
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							model.to(a						)

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

				SCREAMING_SNAKE_CASE :   Tuple					  =							prepare_img()
				SCREAMING_SNAKE_CASE :   Tuple					  =							image_processor(images=a   ,   return_tensors="pt"						).to(a						)

				# forward pass
				with torch.no_grad():
					SCREAMING_SNAKE_CASE :   Optional[int]					  =							model(**a						)
				SCREAMING_SNAKE_CASE :   Optional[int]					  =							outputs.logits

				# verify the logits
				SCREAMING_SNAKE_CASE :   List[Any]					  =							torch.Size((1, 21, 32, 32)						)
				self.assertEqual(logits.shape   ,   a						)

				SCREAMING_SNAKE_CASE :   Any					  =							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=a   ,   )

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






			@slow
			def 				__UpperCamelCase			(      self				:			Dict						)				->							List[str]:

				"""simple docstring"""

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"						)
				SCREAMING_SNAKE_CASE :   List[str]					  =							model.to(a						)

				SCREAMING_SNAKE_CASE :   Dict					  =							MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"						)

				SCREAMING_SNAKE_CASE :   Optional[int]					  =							prepare_img()
				SCREAMING_SNAKE_CASE :   List[str]					  =							image_processor(images=a   ,   return_tensors="pt"						).to(a						)

				# forward pass
				with torch.no_grad():
					SCREAMING_SNAKE_CASE :   Optional[int]					  =							model(**a						)

				SCREAMING_SNAKE_CASE :   int					  =							outputs.logits.detach().cpu()

				SCREAMING_SNAKE_CASE :   int					  =							image_processor.post_process_semantic_segmentation(outputs=a   ,   target_sizes=[(50, 60)]						)
				SCREAMING_SNAKE_CASE :   List[str]					  =							torch.Size((50, 60)						)
				self.assertEqual(segmentation[0].shape   ,   a						)

				SCREAMING_SNAKE_CASE :   int					  =							image_processor.post_process_semantic_segmentation(outputs=a						)
				SCREAMING_SNAKE_CASE :   Tuple					  =							torch.Size((32, 32)						)
				self.assertEqual(segmentation[0].shape   ,   a						)


def 			lowerCamelCase__			(       _a				,      _a):
	SCREAMING_SNAKE_CASE :   Optional[int]					  =							0
	while b > 0:
		if b & 1:
			res += a

		a += a
		b >>= 1

	return res

def 			lowerCamelCase__			(       _a				,      _a				,      _a):
	SCREAMING_SNAKE_CASE :   Optional[int]					  =							0
	while b > 0:
		if b & 1:
			SCREAMING_SNAKE_CASE :   Optional[Any]					  =							((res % c) + (a % c)) % c

		a += a
		b >>= 1

	return res