



import argparse
import collections
import json
from pathlib import Path

import requests
import torch
import yaml
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import (
    MobileViTImageProcessor,
    MobileViTVaConfig,
    MobileViTVaForImageClassification,
    MobileViTVaForSemanticSegmentation,
)
from transformers.utils import logging


logging.set_verbosity_info()
__A   			=logging.get_logger(__name__)

def        a						(      _UpperCAmelCase							:					Optional[int]						):







		'''simple docstring'''





		print('''Loading config file...'''						)

		def flatten_yaml_as_dict(_UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Optional[Any]="" ,   _UpperCAmelCase							:					Optional[int]="."						):
				__UpperCAmelCase    :     Any													=	[]
				for k, v in d.items():
						__UpperCAmelCase    :     Optional[int]													=	parent_key + sep + k if parent_key else k
						if isinstance(_UpperCAmelCase ,   collections.abc.MutableMapping						):
								items.extend(flatten_yaml_as_dict(_UpperCAmelCase ,   _UpperCAmelCase ,   sep=_UpperCAmelCase						).items()						)
						else:
								items.append((new_key, v)						)
				return dict(_UpperCAmelCase						)

		__UpperCAmelCase    :     Optional[Any]													=	argparse.Namespace()
		with open(_UpperCAmelCase ,   '''r'''						) as yaml_file:
				try:
						__UpperCAmelCase    :     Dict													=	yaml.load(_UpperCAmelCase ,   Loader=yaml.FullLoader						)

						__UpperCAmelCase    :     Any													=	flatten_yaml_as_dict(_UpperCAmelCase						)
						for k, v in flat_cfg.items():
								setattr(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase						)
				except yaml.YAMLError as exc:
						logger.error('''Error while loading config file: {}. Error message: {}'''.format(_UpperCAmelCase ,   str(_UpperCAmelCase						)						)						)
		return config

def        a						(      _UpperCAmelCase							:					str ,   _UpperCAmelCase							:					Tuple						):







		'''simple docstring'''





		__UpperCAmelCase    :     Union[str, Any]													=	MobileViTVaConfig()

		__UpperCAmelCase    :     Any													=	False

		# dataset
		if task_name.startswith('''imagenet1k_'''						):
				__UpperCAmelCase    :     Optional[int]													=	10_00
				if int(task_name.strip().split('''_'''						)[-1]						) == 3_84:
						__UpperCAmelCase    :     Optional[Any]													=	3_84
				else:
						__UpperCAmelCase    :     List[Any]													=	2_56
				__UpperCAmelCase    :     Union[str, Any]													=	'''imagenet-1k-id2label.json'''
		elif task_name.startswith('''imagenet21k_to_1k_'''						):
				__UpperCAmelCase    :     Any													=	2_10_00
				if int(task_name.strip().split('''_'''						)[-1]						) == 3_84:
						__UpperCAmelCase    :     Dict													=	3_84
				else:
						__UpperCAmelCase    :     Tuple													=	2_56
				__UpperCAmelCase    :     str													=	'''imagenet-22k-id2label.json'''
		elif task_name.startswith('''ade20k_'''						):
				__UpperCAmelCase    :     str													=	1_51
				__UpperCAmelCase    :     Dict													=	5_12
				__UpperCAmelCase    :     Any													=	'''ade20k-id2label.json'''
				__UpperCAmelCase    :     str													=	True
		elif task_name.startswith('''voc_'''						):
				__UpperCAmelCase    :     Optional[int]													=	21
				__UpperCAmelCase    :     int													=	5_12
				__UpperCAmelCase    :     List[str]													=	'''pascal-voc-id2label.json'''
				__UpperCAmelCase    :     Optional[Any]													=	True

		# orig_config
		__UpperCAmelCase    :     List[Any]													=	load_orig_config_file(_UpperCAmelCase						)
		assert getattr(_UpperCAmelCase ,   '''model.classification.name''' ,   -1						) == "mobilevit_v2", "Invalid model"
		__UpperCAmelCase    :     Dict													=	getattr(_UpperCAmelCase ,   '''model.classification.mitv2.width_multiplier''' ,   1.0						)
		assert (
		    getattr(_UpperCAmelCase ,   '''model.classification.mitv2.attn_norm_layer''' ,   -1						) == "layer_norm_2d"
		), "Norm layers other than layer_norm_2d is not supported"
		__UpperCAmelCase    :     Dict													=	getattr(_UpperCAmelCase ,   '''model.classification.activation.name''' ,   '''swish'''						)
		# config.image_size == getattr(orig_config,  'sampler.bs.crop_size_width', 256)

		if is_segmentation_model:
				__UpperCAmelCase    :     Tuple													=	getattr(_UpperCAmelCase ,   '''model.segmentation.output_stride''' ,   16						)
				if "_deeplabv3" in task_name:
						__UpperCAmelCase    :     Dict													=	getattr(_UpperCAmelCase ,   '''model.segmentation.deeplabv3.aspp_rates''' ,   [12, 24, 36]						)
						__UpperCAmelCase    :     Dict													=	getattr(_UpperCAmelCase ,   '''model.segmentation.deeplabv3.aspp_out_channels''' ,   5_12						)
						__UpperCAmelCase    :     Union[str, Any]													=	getattr(_UpperCAmelCase ,   '''model.segmentation.deeplabv3.aspp_dropout''' ,   0.1						)

    # id2label
		__UpperCAmelCase    :     str													=	'''huggingface/label-files'''
		__UpperCAmelCase    :     int													=	json.load(open(hf_hub_download(_UpperCAmelCase ,   _UpperCAmelCase ,   repo_type='''dataset'''						) ,   '''r'''						)						)
		__UpperCAmelCase    :     List[str]													=	{int(_UpperCAmelCase						): v for k, v in idalabel.items()}
		__UpperCAmelCase    :     str													=	idalabel
		__UpperCAmelCase    :     Union[str, Any]													=	{v: k for k, v in idalabel.items()}

		return config

def        a						(      _UpperCAmelCase							:					Union[str, Any] ,   _UpperCAmelCase							:					List[str] ,   _UpperCAmelCase							:					Any						):







		'''simple docstring'''





		__UpperCAmelCase    :     List[str]													=	dct.pop(_UpperCAmelCase						)
		__UpperCAmelCase    :     int													=	val

def        a						(      _UpperCAmelCase							:					Any ,   _UpperCAmelCase							:					Optional[Any]=False						):







		'''simple docstring'''





		if base_model:
				__UpperCAmelCase    :     Dict													=	''''''
		else:
				__UpperCAmelCase    :     Optional[int]													=	'''mobilevitv2.'''

		__UpperCAmelCase    :     Optional[Any]													=	[]
		for k in state_dict.keys():
				if k[:8] == "encoder.":
						__UpperCAmelCase    :     Dict													=	k[8:]
				else:
						__UpperCAmelCase    :     Dict													=	k

				if ".block." in k:
						__UpperCAmelCase    :     List[Any]													=	k_new.replace('''.block.''' ,   '''.'''						)
				if ".conv." in k:
						__UpperCAmelCase    :     Tuple													=	k_new.replace('''.conv.''' ,   '''.convolution.'''						)
				if ".norm." in k:
						__UpperCAmelCase    :     Optional[Any]													=	k_new.replace('''.norm.''' ,   '''.normalization.'''						)

				if "conv_1." in k:
						__UpperCAmelCase    :     List[Any]													=	k_new.replace('''conv_1.''' ,   f'{model_prefix}conv_stem.'						)
				for i in [1, 2]:
						if f'layer_{i}.' in k:
								__UpperCAmelCase    :     str													=	k_new.replace(f'layer_{i}.' ,   f'{model_prefix}encoder.layer.{i-1}.layer.'						)
				if ".exp_1x1." in k:
						__UpperCAmelCase    :     Dict													=	k_new.replace('''.exp_1x1.''' ,   '''.expand_1x1.'''						)
				if ".red_1x1." in k:
						__UpperCAmelCase    :     Dict													=	k_new.replace('''.red_1x1.''' ,   '''.reduce_1x1.'''						)

				for i in [3, 4, 5]:
						if f'layer_{i}.0.' in k:
								__UpperCAmelCase    :     List[str]													=	k_new.replace(f'layer_{i}.0.' ,   f'{model_prefix}encoder.layer.{i-1}.downsampling_layer.'						)
						if f'layer_{i}.1.local_rep.0.' in k:
								__UpperCAmelCase    :     Any													=	k_new.replace(f'layer_{i}.1.local_rep.0.' ,   f'{model_prefix}encoder.layer.{i-1}.conv_kxk.'						)
						if f'layer_{i}.1.local_rep.1.' in k:
								__UpperCAmelCase    :     List[str]													=	k_new.replace(f'layer_{i}.1.local_rep.1.' ,   f'{model_prefix}encoder.layer.{i-1}.conv_1x1.'						)

				for i in [3, 4, 5]:
						if i == 3:
								__UpperCAmelCase    :     Union[str, Any]													=	[0, 1]
						elif i == 4:
								__UpperCAmelCase    :     int													=	[0, 1, 2, 3]
						elif i == 5:
								__UpperCAmelCase    :     List[Any]													=	[0, 1, 2]

						for j in j_in:
								if f'layer_{i}.1.global_rep.{j}.' in k:
										__UpperCAmelCase    :     Optional[int]													=	k_new.replace(
										    f'layer_{i}.1.global_rep.{j}.' ,   f'{model_prefix}encoder.layer.{i-1}.transformer.layer.{j}.'						)
						if f'layer_{i}.1.global_rep.{j+1}.' in k:
								__UpperCAmelCase    :     Any													=	k_new.replace(
								    f'layer_{i}.1.global_rep.{j+1}.' ,   f'{model_prefix}encoder.layer.{i-1}.layernorm.'						)

						if f'layer_{i}.1.conv_proj.' in k:
								__UpperCAmelCase    :     int													=	k_new.replace(f'layer_{i}.1.conv_proj.' ,   f'{model_prefix}encoder.layer.{i-1}.conv_projection.'						)

				if "pre_norm_attn.0." in k:
						__UpperCAmelCase    :     List[Any]													=	k_new.replace('''pre_norm_attn.0.''' ,   '''layernorm_before.'''						)
				if "pre_norm_attn.1." in k:
						__UpperCAmelCase    :     List[str]													=	k_new.replace('''pre_norm_attn.1.''' ,   '''attention.'''						)
				if "pre_norm_ffn.0." in k:
						__UpperCAmelCase    :     List[Any]													=	k_new.replace('''pre_norm_ffn.0.''' ,   '''layernorm_after.'''						)
				if "pre_norm_ffn.1." in k:
						__UpperCAmelCase    :     Union[str, Any]													=	k_new.replace('''pre_norm_ffn.1.''' ,   '''ffn.conv1.'''						)
				if "pre_norm_ffn.3." in k:
						__UpperCAmelCase    :     Any													=	k_new.replace('''pre_norm_ffn.3.''' ,   '''ffn.conv2.'''						)

				if "classifier.1." in k:
						__UpperCAmelCase    :     Dict													=	k_new.replace('''classifier.1.''' ,   '''classifier.'''						)

				if "seg_head." in k:
						__UpperCAmelCase    :     List[Any]													=	k_new.replace('''seg_head.''' ,   '''segmentation_head.'''						)
				if ".aspp_layer." in k:
						__UpperCAmelCase    :     str													=	k_new.replace('''.aspp_layer.''' ,   '''.'''						)
				if ".aspp_pool." in k:
						__UpperCAmelCase    :     Dict													=	k_new.replace('''.aspp_pool.''' ,   '''.'''						)

				rename_keys.append((k, k_new)						)
		return rename_keys

def        a						(      _UpperCAmelCase							:					List[Any]						):







		'''simple docstring'''





		__UpperCAmelCase    :     int													=	[]
		for k in state_dict.keys():
				if k.startswith('''seg_head.aux_head.'''						):
						keys_to_ignore.append(_UpperCAmelCase						)
		for k in keys_to_ignore:
				state_dict.pop(_UpperCAmelCase ,   _UpperCAmelCase						)

def        a						(      ):







		'''simple docstring'''





		__UpperCAmelCase    :     Union[str, Any]													=	'''http://images.cocodataset.org/val2017/000000039769.jpg'''
		# url = "https://cdn.britannica.com/86/141086-050-9D7C75EE/Gulfstream-G450-business-jet-passengers.jpg"
		__UpperCAmelCase    :     Union[str, Any]													=	Image.open(requests.get(_UpperCAmelCase ,   stream=_UpperCAmelCase						).raw						)
		return im

@torch.no_grad()
def        a						(      _UpperCAmelCase							:					str ,   _UpperCAmelCase							:					Optional[int] ,   _UpperCAmelCase							:					List[Any] ,   _UpperCAmelCase							:					List[str]						):







		'''simple docstring'''





		__UpperCAmelCase    :     Tuple													=	get_mobilevitva_config(_UpperCAmelCase ,   _UpperCAmelCase						)

		# load original state_dict
		__UpperCAmelCase    :     Optional[Any]													=	torch.load(_UpperCAmelCase ,   map_location='''cpu'''						)

		# load huggingface model
		if task_name.startswith('''ade20k_'''						) or task_name.startswith('''voc_'''						):
				__UpperCAmelCase    :     Dict													=	MobileViTVaForSemanticSegmentation(_UpperCAmelCase						).eval()
				__UpperCAmelCase    :     List[str]													=	False
		else:
				__UpperCAmelCase    :     Optional[Any]													=	MobileViTVaForImageClassification(_UpperCAmelCase						).eval()
				__UpperCAmelCase    :     Optional[Any]													=	False

		# remove and rename some keys of load the original model
		__UpperCAmelCase    :     List[Any]													=	checkpoint
		remove_unused_keys(_UpperCAmelCase						)
		__UpperCAmelCase    :     str													=	create_rename_keys(_UpperCAmelCase ,   base_model=_UpperCAmelCase						)
		for rename_key_src, rename_key_dest in rename_keys:
				rename_key(_UpperCAmelCase ,   _UpperCAmelCase ,   _UpperCAmelCase						)

		# load modified state_dict
		model.load_state_dict(_UpperCAmelCase						)

		# Check outputs on an image, prepared by MobileViTImageProcessor
		__UpperCAmelCase    :     Optional[int]													=	MobileViTImageProcessor(crop_size=config.image_size ,   size=config.image_size + 32						)
		__UpperCAmelCase    :     Union[str, Any]													=	image_processor(images=prepare_img() ,   return_tensors='''pt'''						)
		__UpperCAmelCase    :     List[str]													=	model(**_UpperCAmelCase						)

		# verify classification model
		if task_name.startswith('''imagenet'''						):
				__UpperCAmelCase    :     Optional[Any]													=	outputs.logits
				__UpperCAmelCase    :     int													=	logits.argmax(-1						).item()
				print('''Predicted class:''' ,   model.config.idalabel[predicted_class_idx]						)
				if task_name.startswith('''imagenet1k_256'''						) and config.width_multiplier == 1.0:
						# expected_logits for base variant
						__UpperCAmelCase    :     Tuple													=	torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01]						)
						assert torch.allclose(logits[0, :3] ,   _UpperCAmelCase ,   atol=1e-4						)

		Path(_UpperCAmelCase						).mkdir(exist_ok=_UpperCAmelCase						)
		print(f'Saving model {task_name} to {pytorch_dump_folder_path}'						)
		model.save_pretrained(_UpperCAmelCase						)
		print(f'Saving image processor to {pytorch_dump_folder_path}'						)
		image_processor.save_pretrained(_UpperCAmelCase						)


if __name__ == "__main__":
				__A   			=argparse.ArgumentParser()
				# Required parameters
				parser.add_argument(
				    "--task",
				    default="imagenet1k_256",
				    type=str,
				    help=(
				        "Name of the task for which the MobileViTV2 model you'd like to convert is trained on . "
				        "\n                Classification (ImageNet-1k)\n                    - MobileViTV2 (256x256) : imagenet1k_256\n                    - MobileViTV2 (Trained on 256x256 and Finetuned on 384x384) : imagenet1k_384\n                    - MobileViTV2 (Trained on ImageNet-21k and Finetuned on ImageNet-1k 256x256) :\n                      imagenet21k_to_1k_256\n                    - MobileViTV2 (Trained on ImageNet-21k, Finetuned on ImageNet-1k 256x256, and Finetuned on\n                      ImageNet-1k 384x384) : imagenet21k_to_1k_384\n                Segmentation\n                    - ADE20K Dataset : ade20k_deeplabv3\n                    - Pascal VOC 2012 Dataset: voc_deeplabv3\n            "
				    ),
				    choices=[
				        "imagenet1k_256",
				        "imagenet1k_384",
				        "imagenet21k_to_1k_256",
				        "imagenet21k_to_1k_384",
				        "ade20k_deeplabv3",
				        "voc_deeplabv3",
				    ],
				)

				parser.add_argument(
				    "--orig_checkpoint_path", required=True, type=str, help="Path to the original state dict (.pt file)."
				)
				parser.add_argument("--orig_config_path", required=True, type=str, help="Path to the original config file.")
				parser.add_argument(
				    "--pytorch_dump_folder_path", required=True, type=str, help="Path to the output PyTorch model directory."
				)

				__A   			=parser.parse_args()
				convert_mobilevitva_checkpoint(
				    args.task, args.orig_checkpoint_path, args.orig_config_path, args.pytorch_dump_folder_path
				)










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__			(			__UpperCamelCase   ):




			'''simple docstring'''






			def  snake_case__     (   self							: str ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[int]													=	self.config_class(**self.inputs_dict )
					self.parent.assertTrue(hasattr(a_       ,       '''width_multiplier''' ) )

class 		UpperCAmelCase__			:




			'''simple docstring'''






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





					__UpperCAmelCase    :     Optional[Any]													=	parent
					__UpperCAmelCase    :     str													=	batch_size
					__UpperCAmelCase    :     Dict													=	image_size
					__UpperCAmelCase    :     List[Any]													=	patch_size
					__UpperCAmelCase    :     Union[str, Any]													=	num_channels
					__UpperCAmelCase    :     Any													=	make_divisible(5_12 * width_multiplier       ,       divisor=8 )
					__UpperCAmelCase    :     Tuple													=	hidden_act
					__UpperCAmelCase    :     Dict													=	conv_kernel_size
					__UpperCAmelCase    :     Optional[Any]													=	output_stride
					__UpperCAmelCase    :     Dict													=	classifier_dropout_prob
					__UpperCAmelCase    :     Optional[Any]													=	use_labels
					__UpperCAmelCase    :     List[Any]													=	is_training
					__UpperCAmelCase    :     Tuple													=	num_labels
					__UpperCAmelCase    :     List[str]													=	initializer_range
					__UpperCAmelCase    :     Optional[Any]													=	scope
					__UpperCAmelCase    :     Optional[Any]													=	width_multiplier
					__UpperCAmelCase    :     List[str]													=	ffn_dropout
					__UpperCAmelCase    :     Dict													=	attn_dropout




			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     int													=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

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

					return config, pixel_values, labels, pixel_labels




			def  snake_case__     (   self							: Union[str, Any] ):
					'''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  snake_case__     (   self							: Optional[Any]       ,       a_							: Dict       ,       a_							: List[Any]       ,       a_							: Dict       ,       a_							: Tuple ):
					'''simple docstring'''





					__UpperCAmelCase    :     List[str]													=	MobileViTVaModel(config=a_ )
					model.to(a_ )
					model.eval()
					__UpperCAmelCase    :     Tuple													=	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  snake_case__     (   self							: Union[str, Any]       ,       a_							: Dict       ,       a_							: Union[str, Any]       ,       a_							: str       ,       a_							: List[str] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Dict													=	self.num_labels
					__UpperCAmelCase    :     List[str]													=	MobileViTVaForImageClassification(a_ )
					model.to(a_ )
					model.eval()
					__UpperCAmelCase    :     List[Any]													=	model(a_       ,       labels=a_ )
					self.parent.assertEqual(result.logits.shape       ,       (self.batch_size, self.num_labels) )




			def  snake_case__     (   self							: str       ,       a_							: List[str]       ,       a_							: Optional[Any]       ,       a_							: List[str]       ,       a_							: int ):
					'''simple docstring'''





					__UpperCAmelCase    :     Any													=	self.num_labels
					__UpperCAmelCase    :     List[Any]													=	MobileViTVaForSemanticSegmentation(a_ )
					model.to(a_ )
					model.eval()
					__UpperCAmelCase    :     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,
					    )       ,       )
					__UpperCAmelCase    :     List[str]													=	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  snake_case__     (   self							: List[str] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[int]													=	self.prepare_config_and_inputs()
					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase    :     str													=	config_and_inputs
					__UpperCAmelCase    :     Optional[Any]													=	{'''pixel_values''': pixel_values}
					return config, inputs_dict

@require_torch
class 		UpperCAmelCase__			(			__UpperCamelCase						,__UpperCamelCase						,unittest.TestCase   ):




			'''simple docstring'''






			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  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Dict													=	MobileViTVaModelTester(self )
					__UpperCAmelCase    :     Union[str, Any]													=	MobileViTVaConfigTester(self       ,       config_class=a_       ,       has_text_modality=a_ )




			def  snake_case__     (   self							: str ):
					'''simple docstring'''





					self.config_tester.run_common_tests()




			@unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''' )
			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					pass




			@unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''' )
			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					pass




			@unittest.skip(reason='''MobileViTV2 does not output attentions''' )
			def  snake_case__     (   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  snake_case__     (   self							: Dict ):
					'''simple docstring'''





					pass




			@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
			def  snake_case__     (   self							: Optional[Any] ):
					'''simple docstring'''





					pass




			def  snake_case__     (   self							: Any ):
					'''simple docstring'''





					__UpperCAmelCase							,					__UpperCAmelCase    :     str													=	self.model_tester.prepare_config_and_inputs_for_common()

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

							__UpperCAmelCase    :     List[str]													=	['''pixel_values''']
							self.assertListEqual(arg_names[:1]       ,       a_ )




			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[Any]													=	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*a_ )




			def  snake_case__     (   self							: int ):
					'''simple docstring'''





					def check_hidden_states_output(a_							: List[Any]       ,       a_							: List[Any]       ,       a_							: Union[str, Any] ):
							__UpperCAmelCase    :     Optional[int]													=	model_class(a_ )
							model.to(a_ )
							model.eval()

							with torch.no_grad():
									__UpperCAmelCase    :     Dict													=	model(**self._prepare_for_class(a_       ,       a_ ) )

							__UpperCAmelCase    :     List[Any]													=	outputs.hidden_states

							__UpperCAmelCase    :     str													=	5
							self.assertEqual(len(a_ )       ,       a_ )

							# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
							# with the width and height being successively divided by 2.
							__UpperCAmelCase    :     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 )

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

					for model_class in self.all_model_classes:
							__UpperCAmelCase    :     Dict													=	True
							check_hidden_states_output(a_       ,       a_       ,       a_ )

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

							check_hidden_states_output(a_       ,       a_       ,       a_ )




			def  snake_case__     (   self							: Dict ):
					'''simple docstring'''





					__UpperCAmelCase    :     List[Any]													=	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*a_ )




			def  snake_case__     (   self							: Any ):
					'''simple docstring'''





					__UpperCAmelCase    :     Union[str, Any]													=	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*a_ )




			@slow
			def  snake_case__     (   self							: Optional[int] ):
					'''simple docstring'''





					for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__UpperCAmelCase    :     Optional[int]													=	MobileViTVaModel.from_pretrained(a_ )
							self.assertIsNotNone(a_ )

def        a						(      ):







		'''simple docstring'''





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

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




			'''simple docstring'''






			@cached_property
			def  snake_case__     (   self							: Optional[int] ):
					'''simple docstring'''





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




			@slow
			def  snake_case__     (   self							: Optional[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Optional[Any]													=	MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''' ).to(
					    a_ )

					__UpperCAmelCase    :     Optional[int]													=	self.default_image_processor
					__UpperCAmelCase    :     int													=	prepare_img()
					__UpperCAmelCase    :     Union[str, Any]													=	image_processor(images=a_       ,       return_tensors='''pt''' ).to(a_ )

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase    :     Union[str, Any]													=	model(**a_ )

					# verify the logits
					__UpperCAmelCase    :     str													=	torch.Size((1, 10_00) )
					self.assertEqual(outputs.logits.shape       ,       a_ )

					__UpperCAmelCase    :     Any													=	torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01] ).to(a_ )

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




			@slow
			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     int													=	MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' )
					__UpperCAmelCase    :     int													=	model.to(a_ )

					__UpperCAmelCase    :     str													=	MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' )

					__UpperCAmelCase    :     List[str]													=	prepare_img()
					__UpperCAmelCase    :     Tuple													=	image_processor(images=a_       ,       return_tensors='''pt''' ).to(a_ )

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase    :     Dict													=	model(**a_ )
					__UpperCAmelCase    :     int													=	outputs.logits

					# verify the logits
					__UpperCAmelCase    :     Union[str, Any]													=	torch.Size((1, 21, 32, 32) )
					self.assertEqual(logits.shape       ,       a_ )

					__UpperCAmelCase    :     List[Any]													=	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=a_       ,       )

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




			@slow
			def  snake_case__     (   self							: Dict ):
					'''simple docstring'''





					__UpperCAmelCase    :     Tuple													=	MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' )
					__UpperCAmelCase    :     Optional[int]													=	model.to(a_ )

					__UpperCAmelCase    :     List[Any]													=	MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''' )

					__UpperCAmelCase    :     Optional[int]													=	prepare_img()
					__UpperCAmelCase    :     Dict													=	image_processor(images=a_       ,       return_tensors='''pt''' ).to(a_ )

					# forward pass
					with torch.no_grad():
							__UpperCAmelCase    :     Union[str, Any]													=	model(**a_ )

					__UpperCAmelCase    :     Optional[Any]													=	outputs.logits.detach().cpu()

					__UpperCAmelCase    :     List[Any]													=	image_processor.post_process_semantic_segmentation(outputs=a_       ,       target_sizes=[(50, 60)] )
					__UpperCAmelCase    :     Tuple													=	torch.Size((50, 60) )
					self.assertEqual(segmentation[0].shape       ,       a_ )

					__UpperCAmelCase    :     List[Any]													=	image_processor.post_process_semantic_segmentation(outputs=a_ )
					__UpperCAmelCase    :     Optional[int]													=	torch.Size((32, 32) )
					self.assertEqual(segmentation[0].shape       ,       a_ )





