




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        __lowerCAmelCase					(			__magic_name__					):

			"""simple docstring"""







			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self.config_class(**self.inputs_dict				)
							self.parent.assertTrue(hasattr(lowerCamelCase__     ,		'width_multiplier'				)				)







class        __lowerCAmelCase					:

			"""simple docstring"""







			def __init__( self     ,		lowerCamelCase__     ,		lowerCamelCase__=13     ,		lowerCamelCase__=64     ,		lowerCamelCase__=2     ,		lowerCamelCase__=3     ,		lowerCamelCase__="swish"     ,		lowerCamelCase__=3     ,		lowerCamelCase__=32     ,		lowerCamelCase__=0.1     ,		lowerCamelCase__=0.02     ,		lowerCamelCase__=True     ,		lowerCamelCase__=True     ,		lowerCamelCase__=10     ,		lowerCamelCase__=None     ,		lowerCamelCase__=0.25     ,		lowerCamelCase__=0.0     ,		lowerCamelCase__=0.0     ,		)       -> List[Any]:



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


			def  lowercase_       ( self				)       -> int:



							'''simple docstring'''
							__lowerCamelCase									=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

							__lowerCamelCase									=       self.get_config()

							return config, pixel_values, labels, pixel_labels


			def  lowercase_       ( self				)       -> 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  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       MobileViTVaModel(config=lowerCamelCase__				)
							model.to(lowerCamelCase__				)
							model.eval()
							__lowerCamelCase									=       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  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self.num_labels
							__lowerCamelCase									=       MobileViTVaForImageClassification(lowerCamelCase__				)
							model.to(lowerCamelCase__				)
							model.eval()
							__lowerCamelCase									=       model(lowerCamelCase__     ,		labels=lowerCamelCase__				)
							self.parent.assertEqual(result.logits.shape     ,		(self.batch_size, self.num_labels)				)


			def  lowercase_       ( self     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)       -> Any:



							'''simple docstring'''
							__lowerCamelCase									=       self.num_labels
							__lowerCamelCase									=       MobileViTVaForSemanticSegmentation(lowerCamelCase__				)
							model.to(lowerCamelCase__				)
							model.eval()
							__lowerCamelCase									=       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,
							    )     ,		)
							__lowerCamelCase									=       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  lowercase_       ( self				)       -> Optional[Any]:



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







@require_torch
class        __lowerCAmelCase					(			__magic_name__     ,							__magic_name__     ,							unittest.TestCase					):

			"""simple docstring"""







			snake_case_  						=			(
			    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)

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

			snake_case_  						=			False
			snake_case_  						=			False
			snake_case_  						=			False
			snake_case_  						=			False


			def  lowercase_       ( self				)       -> Optional[int]:



							'''simple docstring'''
							__lowerCamelCase									=       MobileViTVaModelTester(self				)
							__lowerCamelCase									=       MobileViTVaConfigTester(self     ,		config_class=lowerCamelCase__     ,		has_text_modality=lowerCamelCase__				)


			def  lowercase_       ( self				)       -> Tuple:



							'''simple docstring'''
							self.config_tester.run_common_tests()


			@unittest.skip(reason='MobileViTV2 does not use inputs_embeds'				)
			def  lowercase_       ( self				)       -> Optional[Any]:



							'''simple docstring'''
							pass


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



							'''simple docstring'''
							pass


			@unittest.skip(reason='MobileViTV2 does not output attentions'				)
			def  lowercase_       ( self				)       -> Tuple:



							'''simple docstring'''
							pass


			@require_torch_multi_gpu
			@unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'				)
			def  lowercase_       ( self				)       -> Dict:



							'''simple docstring'''
							pass


			@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'				)
			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							pass


			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							__lowerCamelCase			,		__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs_for_common()

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

											__lowerCamelCase									=       ['pixel_values']
											self.assertListEqual(arg_names[:1]     ,		lowerCamelCase__				)


			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__				)


			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							def check_hidden_states_output(lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				):
											__lowerCamelCase									=       model_class(lowerCamelCase__				)
											model.to(lowerCamelCase__				)
											model.eval()

											with torch.no_grad():
															__lowerCamelCase									=       model(**self._prepare_for_class(lowerCamelCase__     ,		lowerCamelCase__				)				)

											__lowerCamelCase									=       outputs.hidden_states

											__lowerCamelCase									=       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.
											__lowerCamelCase									=       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				)

							__lowerCamelCase			,		__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
											__lowerCamelCase									=       True
											check_hidden_states_output(lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)

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

											check_hidden_states_output(lowerCamelCase__     ,		lowerCamelCase__     ,		lowerCamelCase__				)


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



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__				)


			def  lowercase_       ( self				)       -> List[Any]:



							'''simple docstring'''
							__lowerCamelCase									=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__				)






			@slow
			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase									=       MobileViTVaModel.from_pretrained(lowerCamelCase__				)
											self.assertIsNotNone(lowerCamelCase__				)







def      lowerCamelCase_						(			)	->			str:





				"""simple docstring"""


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







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

			"""simple docstring"""







			@cached_property
			def  lowercase_       ( self				)       -> Optional[int]:



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


			@slow
			def  lowercase_       ( self				)       -> Union[str, Any]:



							'''simple docstring'''
							__lowerCamelCase									=       MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'				).to(
							    lowerCamelCase__				)

							__lowerCamelCase									=       self.default_image_processor
							__lowerCamelCase									=       prepare_img()
							__lowerCamelCase									=       image_processor(images=lowerCamelCase__     ,		return_tensors='pt'				).to(lowerCamelCase__				)

							# forward pass
							with torch.no_grad():
											__lowerCamelCase									=       model(**lowerCamelCase__				)

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

							__lowerCamelCase									=       torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01]				).to(lowerCamelCase__				)

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


			@slow
			def  lowercase_       ( self				)       -> Dict:



							'''simple docstring'''
							__lowerCamelCase									=       MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'				)
							__lowerCamelCase									=       model.to(lowerCamelCase__				)

							__lowerCamelCase									=       MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'				)

							__lowerCamelCase									=       prepare_img()
							__lowerCamelCase									=       image_processor(images=lowerCamelCase__     ,		return_tensors='pt'				).to(lowerCamelCase__				)

							# forward pass
							with torch.no_grad():
											__lowerCamelCase									=       model(**lowerCamelCase__				)
							__lowerCamelCase									=       outputs.logits

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

							__lowerCamelCase									=       torch.tensor(
							    [
							        [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
							        [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
							        [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
							    ]     ,		device=lowerCamelCase__     ,		)

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






			@slow
			def  lowercase_       ( self				)       -> str:



							'''simple docstring'''
							__lowerCamelCase									=       MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'				)
							__lowerCamelCase									=       model.to(lowerCamelCase__				)

							__lowerCamelCase									=       MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'				)

							__lowerCamelCase									=       prepare_img()
							__lowerCamelCase									=       image_processor(images=lowerCamelCase__     ,		return_tensors='pt'				).to(lowerCamelCase__				)

							# forward pass
							with torch.no_grad():
											__lowerCamelCase									=       model(**lowerCamelCase__				)

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

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

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








import importlib.metadata
import operator
import re
import sys
from typing import Optional

from packaging import version


__A								=       {
    "<": operator.lt,
    "<=": operator.le,
    "==": operator.eq,
    "!=": operator.ne,
    ">=": operator.ge,
    ">": operator.gt,
}







def      lowerCamelCase_						(			UpperCamelCase__							: List[str]					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: Any					,	UpperCamelCase__							: Dict					,	UpperCamelCase__							: int )	->			List[Any]:





				"""simple docstring"""


				if got_ver is None or want_ver is None:
								raise ValueError(
								    F"""Unable to compare versions for {requirement}: need={want_ver} found={got_ver}. This is unusual. Consider"""
								    F""" reinstalling {pkg}.""" )
				if not ops[op](version.parse(UpperCamelCase__ )					,	version.parse(UpperCamelCase__ ) ):
								raise ImportError(
								    F"""{requirement} is required for a normal functioning of this module, but found {pkg}=={got_ver}.{hint}""" )







def      lowerCamelCase_						(			UpperCamelCase__							: str					,	UpperCamelCase__							: Optional[str] = None )	->			None:





				"""simple docstring"""


				__lowerCamelCase									=       F"""\n{hint}""" if hint is not None else ''

				# non-versioned check
				if re.match(R'^[\w_\-\d]+$'					,	UpperCamelCase__ ):
								__lowerCamelCase			,		__lowerCamelCase			,		__lowerCamelCase									=       requirement, None, None
				else:
								__lowerCamelCase									=       re.findall(R'^([^!=<>\s]+)([\s!=<>]{1,2}.+)'					,	UpperCamelCase__ )
								if not match:
												raise ValueError(
												    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23, but'
												    F""" got {requirement}""" )
								__lowerCamelCase			,		__lowerCamelCase									=       match[0]
								__lowerCamelCase									=       want_full.split(',' )  # there could be multiple requirements
								__lowerCamelCase									=       {}
								for w in want_range:
												__lowerCamelCase									=       re.findall(R'^([\s!=<>]{1,2})(.+)'					,	UpperCamelCase__ )
												if not match:
																raise ValueError(
																    'requirement needs to be in the pip package format, .e.g., package_a==1.23, or package_b>=1.23,'
																    F""" but got {requirement}""" )
												__lowerCamelCase			,		__lowerCamelCase									=       match[0]
												__lowerCamelCase									=       want_ver
												if op not in ops:
																raise ValueError(F"""{requirement}: need one of {list(ops.keys() )}, but got {op}""" )

    # special case
				if pkg == "python":
								__lowerCamelCase									=       '.'.join([str(UpperCamelCase__ ) for x in sys.version_info[:3]] )
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )
								return

				# check if any version is installed
				try:
								__lowerCamelCase									=       importlib.metadata.version(UpperCamelCase__ )
				except importlib.metadata.PackageNotFoundError:
								raise importlib.metadata.PackageNotFoundError(
								    F"""The '{requirement}' distribution was not found and is required by this application. {hint}""" )

				# check that the right version is installed if version number or a range was provided
				if want_ver is not None:
								for op, want_ver in wanted.items():
												_compare_versions(UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__					,	UpperCamelCase__ )







def      lowerCamelCase_						(			UpperCamelCase__							: Optional[int] )	->			Optional[int]:





				"""simple docstring"""


				__lowerCamelCase									=       'Try: pip install transformers -U or pip install -e \'.[dev]\' if you\'re working with git main'
				return require_version(UpperCamelCase__					,	UpperCamelCase__ )


