import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
		from transformers.models.mobilevitva.modeling_mobilevitva import (
		    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
		    make_divisible,
		)


if is_vision_available():
		from PIL import Image

		from transformers import MobileViTImageProcessor




class        UpperCamelCase						(  SCREAMING_SNAKE_CASE_   ):




					def 				UpperCamelCase_    (			self			:       List[Any]    ):


							"""simple docstring"""




							__snake_case									=  self.config_class(**self.inputs_dict    )
							self.parent.assertTrue(hasattr(_lowerCAmelCase   ,"width_multiplier"    )    )




class        UpperCamelCase						:




					def __init__(			self			:       List[str]   ,_lowerCAmelCase			:       Optional[int]   ,_lowerCAmelCase			:       Optional[Any]=13   ,_lowerCAmelCase			:       Union[str, Any]=64   ,_lowerCAmelCase			:       Tuple=2   ,_lowerCAmelCase			:       Any=3   ,_lowerCAmelCase			:       List[str]="swish"   ,_lowerCAmelCase			:       List[str]=3   ,_lowerCAmelCase			:       str=32   ,_lowerCAmelCase			:       Union[str, Any]=0.1   ,_lowerCAmelCase			:       Union[str, Any]=0.0_2   ,_lowerCAmelCase			:       Dict=True   ,_lowerCAmelCase			:       Optional[int]=True   ,_lowerCAmelCase			:       Union[str, Any]=10   ,_lowerCAmelCase			:       int=None   ,_lowerCAmelCase			:       int=0.2_5   ,_lowerCAmelCase			:       Optional[Any]=0.0   ,_lowerCAmelCase			:       Dict=0.0   ,):


							"""simple docstring"""




							__snake_case									=  parent
							__snake_case									=  batch_size
							__snake_case									=  image_size
							__snake_case									=  patch_size
							__snake_case									=  num_channels
							__snake_case									=  make_divisible(512 * width_multiplier   ,divisor=8    )
							__snake_case									=  hidden_act
							__snake_case									=  conv_kernel_size
							__snake_case									=  output_stride
							__snake_case									=  classifier_dropout_prob
							__snake_case									=  use_labels
							__snake_case									=  is_training
							__snake_case									=  num_labels
							__snake_case									=  initializer_range
							__snake_case									=  scope
							__snake_case									=  width_multiplier
							__snake_case									=  ffn_dropout
							__snake_case									=  attn_dropout




					def 				UpperCamelCase_    (			self			:       str    ):


							"""simple docstring"""




							__snake_case									=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

							__snake_case									=  None
							__snake_case									=  None
							if self.use_labels:
									__snake_case									=  ids_tensor([self.batch_size]   ,self.num_labels    )
									__snake_case									=  ids_tensor([self.batch_size, self.image_size, self.image_size]   ,self.num_labels    )

							__snake_case									=  self.get_config()

							return config, pixel_values, labels, pixel_labels




					def 				UpperCamelCase_    (			self			:       List[str]    ):


							"""simple docstring"""




							return MobileViTVaConfig(
							    image_size=self.image_size   ,patch_size=self.patch_size   ,num_channels=self.num_channels   ,hidden_act=self.hidden_act   ,conv_kernel_size=self.conv_kernel_size   ,output_stride=self.output_stride   ,classifier_dropout_prob=self.classifier_dropout_prob   ,initializer_range=self.initializer_range   ,width_multiplier=self.width_multiplier   ,ffn_dropout=self.ffn_dropout_prob   ,attn_dropout=self.attn_dropout_prob   ,)




					def 				UpperCamelCase_    (			self			:       int   ,_lowerCAmelCase			:       Optional[Any]   ,_lowerCAmelCase			:       Optional[Any]   ,_lowerCAmelCase			:       List[str]   ,_lowerCAmelCase			:       Optional[int]    ):


							"""simple docstring"""




							__snake_case									=  MobileViTVaModel(config=_lowerCAmelCase    )
							model.to(_lowerCAmelCase    )
							model.eval()
							__snake_case									=  model(_lowerCAmelCase    )
							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			:       Dict   ,_lowerCAmelCase			:       Dict   ,_lowerCAmelCase			:       List[str]   ,_lowerCAmelCase			:       Dict   ,_lowerCAmelCase			:       Tuple    ):


							"""simple docstring"""




							__snake_case									=  self.num_labels
							__snake_case									=  MobileViTVaForImageClassification(_lowerCAmelCase    )
							model.to(_lowerCAmelCase    )
							model.eval()
							__snake_case									=  model(_lowerCAmelCase   ,labels=_lowerCAmelCase    )
							self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.num_labels)    )




					def 				UpperCamelCase_    (			self			:       Optional[Any]   ,_lowerCAmelCase			:       Tuple   ,_lowerCAmelCase			:       List[Any]   ,_lowerCAmelCase			:       List[Any]   ,_lowerCAmelCase			:       List[str]    ):


							"""simple docstring"""




							__snake_case									=  self.num_labels
							__snake_case									=  MobileViTVaForSemanticSegmentation(_lowerCAmelCase    )
							model.to(_lowerCAmelCase    )
							model.eval()
							__snake_case									=  model(_lowerCAmelCase    )
							self.parent.assertEqual(
							    result.logits.shape   ,(
							        self.batch_size,
							        self.num_labels,
							        self.image_size // self.output_stride,
							        self.image_size // self.output_stride,
							    )   ,)
							__snake_case									=  model(_lowerCAmelCase   ,labels=_lowerCAmelCase    )
							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			:       List[str]    ):


							"""simple docstring"""




							__snake_case									=  self.prepare_config_and_inputs()
							__snake_case									=  config_and_inputs
							__snake_case									=  {'pixel_values': pixel_values}
							return config, inputs_dict




@require_torch
class        UpperCamelCase						(  SCREAMING_SNAKE_CASE_      ,   SCREAMING_SNAKE_CASE_      ,   unittest.TestCase   ):
					__UpperCamelCase							= (
					    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
					    if is_torch_available()
					    else ()
					)

					__UpperCamelCase							= (
					    {
					        """feature-extraction""": MobileViTVaModel,
					        """image-classification""": MobileViTVaForImageClassification,
					        """image-segmentation""": MobileViTVaForSemanticSegmentation,
					    }
					    if is_torch_available()
					    else {}
					)

					__UpperCamelCase							= False
					__UpperCamelCase							= False
					__UpperCamelCase							= False
					__UpperCamelCase							= False




					def 				UpperCamelCase_    (			self			:       Any    ):


							"""simple docstring"""




							__snake_case									=  MobileViTVaModelTester(self    )
							__snake_case									=  MobileViTVaConfigTester(self   ,config_class=_lowerCAmelCase   ,has_text_modality=_lowerCAmelCase    )




					def 				UpperCamelCase_    (			self			:       Tuple    ):


							"""simple docstring"""




							self.config_tester.run_common_tests()




					@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"    )
					def 				UpperCamelCase_    (			self			:       List[Any]    ):


							"""simple docstring"""




							pass




					@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"    )
					def 				UpperCamelCase_    (			self			:       int    ):


							"""simple docstring"""




							pass




					@unittest.skip(reason="MobileViTV2 does not output attentions"    )
					def 				UpperCamelCase_    (			self			:       Any    ):


							"""simple docstring"""




							pass




					@require_torch_multi_gpu
					@unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."    )
					def 				UpperCamelCase_    (			self			:       Union[str, Any]    ):


							"""simple docstring"""




							pass




					@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			:       str    ):


							"""simple docstring"""




							__snake_case									=  self.model_tester.prepare_config_and_inputs_for_common()

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

									__snake_case									=  ['pixel_values']
									self.assertListEqual(arg_names[:1]   ,_lowerCAmelCase    )




					def 				UpperCamelCase_    (			self			:       Optional[Any]    ):


							"""simple docstring"""




							__snake_case									=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowerCAmelCase    )




					def 				UpperCamelCase_    (			self			:       Optional[int]    ):


							"""simple docstring"""




							def check_hidden_states_output(_lowerCAmelCase			:       str   ,_lowerCAmelCase			:       Optional[Any]   ,_lowerCAmelCase			:       str    ):
									__snake_case									=  model_class(_lowerCAmelCase    )
									model.to(_lowerCAmelCase    )
									model.eval()

									with torch.no_grad():
											__snake_case									=  model(**self._prepare_for_class(_lowerCAmelCase   ,_lowerCAmelCase    )    )

									__snake_case									=  outputs.hidden_states

									__snake_case									=  5
									self.assertEqual(len(_lowerCAmelCase    )   ,_lowerCAmelCase    )

									# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
									# with the width and height being successively divided by 2.
									__snake_case									=  2
									for i in range(len(_lowerCAmelCase    )    ):
											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    )

							__snake_case									=  self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
									__snake_case									=  True
									check_hidden_states_output(_lowerCAmelCase   ,_lowerCAmelCase   ,_lowerCAmelCase    )

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

									check_hidden_states_output(_lowerCAmelCase   ,_lowerCAmelCase   ,_lowerCAmelCase    )




					def 				UpperCamelCase_    (			self			:       Optional[Any]    ):


							"""simple docstring"""




							__snake_case									=  self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase    )




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


							"""simple docstring"""




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







					@slow
					def 				UpperCamelCase_    (			self			:       Optional[int]    ):


							"""simple docstring"""




							for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__snake_case									=  MobileViTVaModel.from_pretrained(_lowerCAmelCase    )
									self.assertIsNotNone(_lowerCAmelCase    )




def 				_lowerCamelCase(					)	-> Tuple:
		__snake_case									=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
		return image





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




					@cached_property
					def 				UpperCamelCase_    (			self			:       Optional[Any]    ):


							"""simple docstring"""




							return (
							    MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"    )
							    if is_vision_available()
							    else None
							)




					@slow
					def 				UpperCamelCase_    (			self			:       Optional[int]    ):


							"""simple docstring"""




							__snake_case									=  MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"    ).to(
							    _lowerCAmelCase    )

							__snake_case									=  self.default_image_processor
							__snake_case									=  prepare_img()
							__snake_case									=  image_processor(images=_lowerCAmelCase   ,return_tensors="pt"    ).to(_lowerCAmelCase    )

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

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

							__snake_case									=  torch.tensor([-1.6_336E00, -7.3_204E-02, -5.1_883E-01]    ).to(_lowerCAmelCase    )

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




					@slow
					def 				UpperCamelCase_    (			self			:       Dict    ):


							"""simple docstring"""




							__snake_case									=  MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )
							__snake_case									=  model.to(_lowerCAmelCase    )

							__snake_case									=  MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )

							__snake_case									=  prepare_img()
							__snake_case									=  image_processor(images=_lowerCAmelCase   ,return_tensors="pt"    ).to(_lowerCAmelCase    )

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

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

							__snake_case									=  torch.tensor(
							    [
							        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
							        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
							        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
							    ]   ,device=_lowerCAmelCase   ,)

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







					@slow
					def 				UpperCamelCase_    (			self			:       Optional[int]    ):


							"""simple docstring"""




							__snake_case									=  MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )
							__snake_case									=  model.to(_lowerCAmelCase    )

							__snake_case									=  MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"    )

							__snake_case									=  prepare_img()
							__snake_case									=  image_processor(images=_lowerCAmelCase   ,return_tensors="pt"    ).to(_lowerCAmelCase    )

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

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

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

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










"""simple docstring"""







# Lint as: python3
import dataclasses
import re
from dataclasses import dataclass
from functools import total_ordering
from typing import Optional, Union


a_							=    re.compile(r"""^(?P<major>\d+)""" r"""\.(?P<minor>\d+)""" r"""\.(?P<patch>\d+)$""")







@total_ordering
@dataclass
class 					A_:







			"""simple docstring"""



			a_       :			str
			a_       :			Optional[str]												=			None
			a_       :			Optional[Union[str, int]]												=			None
			a_       :			Optional[Union[str, int]]												=			None
			a_       :			Optional[Union[str, int]]												=			None
			def    _lowerCAmelCase		(	self							):
						_lowerCamelCase       ,							_lowerCamelCase       ,							_lowerCamelCase					:					List[str]	       =    _str_to_version_tuple(self.version_str							)
			def __repr__(	self							):
						return F"{self.tuple[0]}.{self.tuple[1]}.{self.tuple[2]}"
			@property
			def    _lowerCAmelCase		(	self							):
						return self.major, self.minor, self.patch
			def    _lowerCAmelCase		(	self				,   A							):
						if isinstance(A				,   A							):
									return Version(A							)
						elif isinstance(A				,   A							):
									return other
						raise TypeError(F"{other} (type {type(A							)}) cannot be compared to version."							)
			def __eq__(	self				,   A							):
						try:
									_lowerCamelCase					:					Dict	       =    self._validate_operand(A							)
						except (TypeError, ValueError):
									return False
						else:
									return self.tuple == other.tuple
			def __lt__(	self				,   A							):
						_lowerCamelCase					:					Any	       =    self._validate_operand(A							)
						return self.tuple < other.tuple
			def __hash__(	self							):
						return hash(_version_tuple_to_str(self.tuple							)							)
			@classmethod
			def    _lowerCAmelCase		(	cls				,   A							):
						_lowerCamelCase					:					Optional[Any]	       =    {f.name for f in dataclasses.fields(cls							)}
						return cls(**{k: v for k, v in dic.items() if k in field_names}							)

			def    _lowerCAmelCase		(	self							):
						return self.version_str






def     UpperCAmelCase_					(				__a   :			Any						):




			'''simple docstring'''



			_lowerCamelCase					:					Union[str, Any]	       =    _VERSION_REG.match(__a						)
			if not res:
						raise ValueError(f"Invalid version '{version_str}'. Format should be x.y.z with {{x,y,z}} being digits."						)
			return tuple(int(__a						) for v in [res.group('major'						), res.group('minor'						), res.group('patch'						)]						)



def     UpperCAmelCase_					(				__a   :			List[str]						):




			'''simple docstring'''



			return ".".join(str(__a						) for v in version_tuple						)





