



import argparse

import fairseq
import torch
from torch import nn

from transformers import (
    MBartaaTokenizer,
    MBartConfig,
    MBartForCausalLM,
    SpeechEncoderDecoderConfig,
    SpeechEncoderDecoderModel,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaModel,
    logging,
)


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

_lowercase     							=						{
    '''post_extract_proj''': '''feature_projection.projection''',
    '''encoder.pos_conv.0''': '''encoder.pos_conv_embed.conv''',
    '''self_attn.k_proj''': '''encoder.layers.*.attention.k_proj''',
    '''self_attn.v_proj''': '''encoder.layers.*.attention.v_proj''',
    '''self_attn.q_proj''': '''encoder.layers.*.attention.q_proj''',
    '''self_attn.out_proj''': '''encoder.layers.*.attention.out_proj''',
    '''self_attn_layer_norm''': '''encoder.layers.*.layer_norm''',
    '''fc1''': '''encoder.layers.*.feed_forward.intermediate_dense''',
    '''fc2''': '''encoder.layers.*.feed_forward.output_dense''',
    '''final_layer_norm''': '''encoder.layers.*.final_layer_norm''',
    '''encoder.layer_norm''': '''encoder.layer_norm''',
    '''w2v_model.layer_norm''': '''feature_projection.layer_norm''',
    '''quantizer.weight_proj''': '''quantizer.weight_proj''',
    '''quantizer.vars''': '''quantizer.codevectors''',
    '''project_q''': '''project_q''',
    '''final_proj''': '''project_hid''',
    '''w2v_encoder.proj''': '''lm_head''',
    '''mask_emb''': '''masked_spec_embed''',
}
_lowercase     							=						[
    '''lm_head''',
    '''quantizer.weight_proj''',
    '''quantizer.codevectors''',
    '''project_q''',
    '''project_hid''',
]






def      _A				(UpperCamelCase		:      int      ,			UpperCamelCase		:      Any      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Dict )  ->int:



			'''simple docstring'''







			for attribute in key.split(""".""" ):
						lowerCamelCase__ :      str								=		getattr(UpperCamelCase      ,			UpperCamelCase )

			if weight_type is not None:
						lowerCamelCase__ :      List[str]								=		getattr(UpperCamelCase      ,			UpperCamelCase ).shape
			else:
						lowerCamelCase__ :      Tuple								=		hf_pointer.shape

			assert hf_shape == value.shape, (
			    f"Shape of hf {key + '.' + weight_type if weight_type is not None else ''} is {hf_shape}, but should be"
			    f" {value.shape} for {full_name}"
			)

			if weight_type == "weight":
						lowerCamelCase__ :      Any								=		value
			elif weight_type == "weight_g":
						lowerCamelCase__ :      List[str]								=		value
			elif weight_type == "weight_v":
						lowerCamelCase__ :      str								=		value
			elif weight_type == "bias":
						lowerCamelCase__ :      Union[str, Any]								=		value
			else:
						lowerCamelCase__ :      Dict								=		value

			logger.info(f"{key + '.' + weight_type if weight_type is not None else ''} was initialized from {full_name}." )






def      _A				(UpperCamelCase		:      str      ,			UpperCamelCase		:      Any )  ->Any:



			'''simple docstring'''







			lowerCamelCase__ :      Dict								=		[]
			lowerCamelCase__ :      int								=		fairseq_model.state_dict()

			lowerCamelCase__ :      Any								=		hf_model.feature_extractor
			lowerCamelCase__ :      Dict								=		hf_model.adapter

			for name, value in fairseq_dict.items():
						lowerCamelCase__ :      Optional[int]								=		False
						if "conv_layers" in name:
									load_conv_layer(
									    UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase      ,			hf_model.config.feat_extract_norm == """group"""      ,			)
									lowerCamelCase__ :      Union[str, Any]								=		True
						elif any(x in name for x in ["""adaptor""", """w2v_encoder.proj.""", """w2v_proj_ln."""] ):
									load_adapter(UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase )
									lowerCamelCase__ :      Dict								=		True
						else:
									for key, mapped_key in MAPPING.items():
												if key in name or key.split("""w2v_model.""" )[-1] == name.split(""".""" )[0]:
															lowerCamelCase__ :      Dict								=		True
															if "*" in mapped_key:
																		lowerCamelCase__ :      Union[str, Any]								=		name.split(UpperCamelCase )[0].split(""".""" )[-2]
																		lowerCamelCase__ :      Dict								=		mapped_key.replace("""*"""      ,			UpperCamelCase )
															if "weight_g" in name:
																		lowerCamelCase__ :      Any								=		"""weight_g"""
															elif "weight_v" in name:
																		lowerCamelCase__ :      int								=		"""weight_v"""
															elif "bias" in name:
																		lowerCamelCase__ :      Any								=		"""bias"""
															elif "weight" in name:
																		lowerCamelCase__ :      int								=		"""weight"""
															else:
																		lowerCamelCase__ :      int								=		None
															set_recursively(UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase      ,			UpperCamelCase )
												continue
						if not is_used:
									unused_weights.append(UpperCamelCase )

			logger.warning(f"Unused weights: {unused_weights}" )






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      Dict      ,			UpperCamelCase		:      Union[str, Any]      ,			UpperCamelCase		:      List[Any] )  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Union[str, Any]								=		full_name.split("""conv_layers.""" )[-1]
			lowerCamelCase__ :      Union[str, Any]								=		name.split(""".""" )
			lowerCamelCase__ :      Union[str, Any]								=		int(items[0] )
			lowerCamelCase__ :      List[Any]								=		int(items[1] )

			if type_id == 0:
						if "bias" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found."
									)
									lowerCamelCase__ :      List[Any]								=		value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
						elif "weight" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found."
									)
									lowerCamelCase__ :      List[Any]								=		value
									logger.info(f"Feat extract conv layer {layer_id} was initialized from {full_name}." )
			elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm):
						if "bias" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, (
									    f"{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was"
									    " found."
									)
									lowerCamelCase__ :      str								=		value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
						elif "weight" in name:
									assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, (
									    f"{full_name} has size {value.shape}, but"
									    f" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found."
									)
									lowerCamelCase__ :      Union[str, Any]								=		value
									logger.info(f"Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}." )
			else:
						unused_weights.append(UpperCamelCase )






def      _A				(UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      Tuple )  ->List[str]:



			'''simple docstring'''







			lowerCamelCase__ :      Any								=		full_name.split("""adaptor.""" )[-1]
			lowerCamelCase__ :      Optional[Any]								=		name.split(""".""" )

			if items[1].isdigit():
						lowerCamelCase__ :      Tuple								=		int(items[1] )
			else:
						lowerCamelCase__ :      Tuple								=		None

			if "adaptor" not in full_name:
						if "proj_ln" in full_name:
									# has to be layer norm
									if "bias" in name:
												assert (
												    value.shape == adapter.proj_layer_norm.bias.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.bias.data.shape} was found."
												lowerCamelCase__ :      List[str]								=		value
												logger.info(f"Adapter proj layer norm bias was initialized from {full_name}." )
									if "weight" in name:
												assert (
												    value.shape == adapter.proj_layer_norm.weight.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj_layer_norm.weight.data.shape} was found."
												lowerCamelCase__ :      Dict								=		value
						else:
									# has to be projection layer
									if "bias" in name:
												assert (
												    value.shape == adapter.proj.bias.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj.bias.data.shape} was found."
												lowerCamelCase__ :      List[Any]								=		value
												logger.info(f"Adapter proj layer bias was initialized from {full_name}." )
									if "weight" in name:
												assert (
												    value.shape == adapter.proj.weight.data.shape
												), f"{full_name} has size {value.shape}, but {adapter.proj.weight.data.shape} was found."
												lowerCamelCase__ :      Dict								=		value
												logger.info(f"Adapter proj layer weight was initialized from {full_name}." )
			elif isinstance(UpperCamelCase      ,			UpperCamelCase ):
						if "bias" in name:
									assert (
									    value.shape == adapter.layers[layer_id].conv.bias.data.shape
									), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.bias.data.shape} was found."
									lowerCamelCase__ :      List[str]								=		value
									logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}." )
						elif "weight" in name:
									assert (
									    value.shape == adapter.layers[layer_id].conv.weight.data.shape
									), f"{full_name} has size {value.shape}, but {adapter.layers[layer_id].conv.weight.data.shape} was found."
									lowerCamelCase__ :      Tuple								=		value
									logger.info(f"Adapter layer {layer_id} bias was initialized from {full_name}." )
			else:
						unused_weights.append(UpperCamelCase )






def      _A				(UpperCamelCase		:      Union[str, Any] )  ->Optional[Any]:



			'''simple docstring'''







			lowerCamelCase__							,lowerCamelCase__ :      Any								=		emb.weight.shape
			lowerCamelCase__ :      Any								=		nn.Linear(UpperCamelCase      ,			UpperCamelCase      ,			bias=UpperCamelCase )
			lowerCamelCase__ :      Any								=		emb.weight.data
			return lin_layer






@torch.no_grad()
def      _A				(UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Dict      ,			UpperCamelCase		:      int      ,			UpperCamelCase		:      Optional[int]      ,			UpperCamelCase		:      List[Any]      ,			UpperCamelCase		:      Optional[Any]      ,			UpperCamelCase		:      Tuple      ,			UpperCamelCase		:      int      ,			)  ->str:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		WavaVecaConfig.from_pretrained(
			    UpperCamelCase      ,			add_adapter=UpperCamelCase      ,			adapter_stride=UpperCamelCase      ,			adapter_kernel_size=UpperCamelCase      ,			use_auth_token=UpperCamelCase      ,			output_hidden_size=UpperCamelCase      ,			)
			lowerCamelCase__ :      int								=		MBartConfig.from_pretrained(UpperCamelCase )

			# load model
			lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      Optional[int]								=		fairseq.checkpoint_utils.load_model_ensemble_and_task(
			    [checkpoint_path]      ,			arg_overrides={
			        """config_yaml""": config_yaml_path,
			        """data""": """/""".join(dict_path.split("""/""" )[:-1] ),
			        """w2v_path""": checkpoint_path,
			        """load_pretrained_decoder_from""": None,
			    }      ,			)
			lowerCamelCase__ :      Optional[Any]								=		model[0].eval()

			# load feature extractor
			lowerCamelCase__ :      int								=		WavaVecaFeatureExtractor.from_pretrained(UpperCamelCase      ,			use_auth_token=UpperCamelCase )

			# set weights for wav2vec2 encoder
			lowerCamelCase__ :      str								=		WavaVecaModel(UpperCamelCase )

			recursively_load_weights_wavaveca(model.encoder      ,			UpperCamelCase )

			# load decoder weights
			lowerCamelCase__ :      List[str]								=		MBartForCausalLM(UpperCamelCase )
			lowerCamelCase__							,lowerCamelCase__ :      Dict								=		hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict()      ,			strict=UpperCamelCase )
			logger.warning(f"The following keys are missing when loading the decoder weights: {missing_keys}" )
			logger.warning(f"The following keys are unexpected when loading the decoder weights: {unexpected_keys}" )

			lowerCamelCase__ :      Optional[Any]								=		SpeechEncoderDecoderModel(encoder=UpperCamelCase      ,			decoder=UpperCamelCase )
			lowerCamelCase__ :      Optional[Any]								=		False

			lowerCamelCase__ :      Optional[int]								=		MBartaaTokenizer(UpperCamelCase )
			tokenizer.save_pretrained(UpperCamelCase )

			lowerCamelCase__ :      Optional[int]								=		hf_wavavec.config.to_dict()
			lowerCamelCase__ :      Dict								=		tokenizer.pad_token_id
			lowerCamelCase__ :      Union[str, Any]								=		tokenizer.bos_token_id
			lowerCamelCase__ :      Any								=		tokenizer.eos_token_id
			lowerCamelCase__ :      List[str]								=		"""mbart50"""
			lowerCamelCase__ :      Optional[Any]								=		"""wav2vec2"""

			lowerCamelCase__ :      Optional[int]								=		tokenizer.eos_token_id
			lowerCamelCase__ :      int								=		250004
			lowerCamelCase__ :      List[str]								=		tokenizer.eos_token_id

			lowerCamelCase__ :      Dict								=		SpeechEncoderDecoderConfig.from_dict(UpperCamelCase )

			hf_wavavec.save_pretrained(UpperCamelCase )
			feature_extractor.save_pretrained(UpperCamelCase )


if __name__ == "__main__":
				_lowercase     							=						argparse.ArgumentParser()
				parser.add_argument('''--pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''')
				parser.add_argument('''--checkpoint_path''', default=None, type=str, help='''Path to fairseq checkpoint''')
				parser.add_argument('''--dict_path''', default=None, type=str, help='''Path to dict of fine-tuned model''')
				parser.add_argument('''--config_yaml_path''', default=None, type=str, help='''Path to yaml file of fine-tuned model''')
				parser.add_argument(
				    '''--encoder_config_path''',
				    default='''facebook/wav2vec2-xls-r-1b''',
				    type=str,
				    help='''Path to hf encoder wav2vec2 checkpoint config''',
				)
				parser.add_argument(
				    '''--decoder_config_path''',
				    default='''facebook/mbart-large-50-one-to-many-mmt''',
				    type=str,
				    help='''Path to hf decoder checkpoint config''',
				)
				parser.add_argument('''--add_adapter''', default=True, type=bool, help='''whethere to add model adapter layers''')
				parser.add_argument('''--adapter_stride''', default=2, type=int, help='''stride of adapter layers''')
				parser.add_argument('''--adapter_kernel_size''', default=3, type=int, help='''kernel size of adapter layers''')
				parser.add_argument('''--encoder_output_dim''', default=10_24, type=int, help='''encoder output dim''')
				parser.add_argument('''--start_token_id''', default=25_00_04, type=int, help='''`decoder_start_token_id` of model config''')

				_lowercase     							=						parser.parse_args()
				convert_wavaveca_checkpoint(
				    args.checkpoint_path,
				    args.pytorch_dump_folder_path,
				    args.dict_path,
				    args.config_yaml_path,
				    encoder_config_path=args.encoder_config_path,
				    decoder_config_path=args.decoder_config_path,
				    add_adapter=args.add_adapter,
				    adapter_kernel_size=args.adapter_kernel_size,
				    adapter_stride=args.adapter_stride,
				    decoder_start_token_id=args.start_token_id,
				    encoder_output_dim=args.encoder_output_dim,
				)








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 				__A					( A_      ):





			def        _snake_case    (self				):
						lowerCamelCase__ :      Dict								=		self.config_class(**self.inputs_dict				)
						self.parent.assertTrue(hasattr(__magic_name__							,    """width_multiplier"""				)				)







class 				__A					:





			def __init__(self							,    __magic_name__							,    __magic_name__=13							,    __magic_name__=64							,    __magic_name__=2							,    __magic_name__=3							,    __magic_name__="swish"							,    __magic_name__=3							,    __magic_name__=32							,    __magic_name__=0.1							,    __magic_name__=0.02							,    __magic_name__=True							,    __magic_name__=True							,    __magic_name__=10							,    __magic_name__=None							,    __magic_name__=0.25							,    __magic_name__=0.0							,    __magic_name__=0.0							,    ):
						lowerCamelCase__ :      Optional[Any]								=		parent
						lowerCamelCase__ :      List[Any]								=		batch_size
						lowerCamelCase__ :      Optional[Any]								=		image_size
						lowerCamelCase__ :      Union[str, Any]								=		patch_size
						lowerCamelCase__ :      Dict								=		num_channels
						lowerCamelCase__ :      Optional[Any]								=		make_divisible(512 * width_multiplier							,    divisor=8				)
						lowerCamelCase__ :      str								=		hidden_act
						lowerCamelCase__ :      Union[str, Any]								=		conv_kernel_size
						lowerCamelCase__ :      int								=		output_stride
						lowerCamelCase__ :      Tuple								=		classifier_dropout_prob
						lowerCamelCase__ :      Optional[Any]								=		use_labels
						lowerCamelCase__ :      Tuple								=		is_training
						lowerCamelCase__ :      List[Any]								=		num_labels
						lowerCamelCase__ :      str								=		initializer_range
						lowerCamelCase__ :      Optional[Any]								=		scope
						lowerCamelCase__ :      Tuple								=		width_multiplier
						lowerCamelCase__ :      List[Any]								=		ffn_dropout
						lowerCamelCase__ :      Union[str, Any]								=		attn_dropout





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

						lowerCamelCase__ :      str								=		None
						lowerCamelCase__ :      List[Any]								=		None
						if self.use_labels:
									lowerCamelCase__ :      Tuple								=		ids_tensor([self.batch_size]							,    self.num_labels				)
									lowerCamelCase__ :      List[Any]								=		ids_tensor([self.batch_size, self.image_size, self.image_size]							,    self.num_labels				)

						lowerCamelCase__ :      int								=		self.get_config()

						return config, pixel_values, labels, pixel_labels





			def        _snake_case    (self				):
						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							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Any								=		MobileViTVaModel(config=__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Optional[Any]								=		model(__magic_name__				)
						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							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      List[str]								=		self.num_labels
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaForImageClassification(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Dict								=		model(__magic_name__							,    labels=__magic_name__				)
						self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)				)





			def        _snake_case    (self							,    __magic_name__							,    __magic_name__							,    __magic_name__							,    __magic_name__				):
						lowerCamelCase__ :      Dict								=		self.num_labels
						lowerCamelCase__ :      Any								=		MobileViTVaForSemanticSegmentation(__magic_name__				)
						model.to(__magic_name__				)
						model.eval()
						lowerCamelCase__ :      Optional[int]								=		model(__magic_name__				)
						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__ :      Dict								=		model(__magic_name__							,    labels=__magic_name__				)
						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				):
						lowerCamelCase__ :      Any								=		self.prepare_config_and_inputs()
						lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__							,lowerCamelCase__ :      List[str]								=		config_and_inputs
						lowerCamelCase__ :      str								=		{"""pixel_values""": pixel_values}
						return config, inputs_dict







@require_torch
class 				__A					( A_					, A_					, unittest.TestCase      ):
			UpperCamelCase					:Optional[Any]     =			(
			    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)

			UpperCamelCase					:List[Any]     =			(
			    {
			        '''feature-extraction''': MobileViTVaModel,
			        '''image-classification''': MobileViTVaForImageClassification,
			        '''image-segmentation''': MobileViTVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase					:List[Any]     =			False
			UpperCamelCase					:int     =			False
			UpperCamelCase					:Optional[int]     =			False
			UpperCamelCase					:int     =			False





			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaModelTester(self				)
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaConfigTester(self							,    config_class=__magic_name__							,    has_text_modality=__magic_name__				)





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





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





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





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





			@require_torch_multi_gpu
			@unittest.skip(reason="""Got `CUDA error: misaligned address` for tests after this one being run."""				)
			def        _snake_case    (self				):
						pass





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





			def        _snake_case    (self				):
						lowerCamelCase__							,lowerCamelCase__ :      Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
									lowerCamelCase__ :      List[Any]								=		model_class(__magic_name__				)
									lowerCamelCase__ :      Optional[Any]								=		inspect.signature(model.forward				)
									# signature.parameters is an OrderedDict => so arg_names order is deterministic
									lowerCamelCase__ :      Union[str, Any]								=		[*signature.parameters.keys()]

									lowerCamelCase__ :      Union[str, Any]								=		["""pixel_values"""]
									self.assertListEqual(arg_names[:1]							,    __magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      int								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__magic_name__				)





			def        _snake_case    (self				):
						def check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				):
									lowerCamelCase__ :      Dict								=		model_class(__magic_name__				)
									model.to(__magic_name__				)
									model.eval()

									with torch.no_grad():
												lowerCamelCase__ :      Optional[int]								=		model(**self._prepare_for_class(__magic_name__							,    __magic_name__				)				)

									lowerCamelCase__ :      str								=		outputs.hidden_states

									lowerCamelCase__ :      Dict								=		5
									self.assertEqual(len(__magic_name__				)							,    __magic_name__				)

									# MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
									# with the width and height being successively divided by 2.
									lowerCamelCase__ :      Dict								=		2
									for i in range(len(__magic_name__				)				):
												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__ :      Optional[Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

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

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

									check_hidden_states_output(__magic_name__							,    __magic_name__							,    __magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      Tuple								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*__magic_name__				)





			def        _snake_case    (self				):
						lowerCamelCase__ :      List[Any]								=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__				)





			@slow
			def        _snake_case    (self				):
						for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase__ :      int								=		MobileViTVaModel.from_pretrained(__magic_name__				)
									self.assertIsNotNone(__magic_name__				)







def      _A				()  ->List[Any]:



			'''simple docstring'''







			lowerCamelCase__ :      Tuple								=		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
			return image
@require_torch
@require_vision
class 				__A					( unittest.TestCase      ):





			@cached_property
			def        _snake_case    (self				):
						return (
						    MobileViTImageProcessor.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""				)
						    if is_vision_available()
						    else None
						)





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      str								=		MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""				).to(
						    __magic_name__				)

						lowerCamelCase__ :      Union[str, Any]								=		self.default_image_processor
						lowerCamelCase__ :      Any								=		prepare_img()
						lowerCamelCase__ :      Optional[Any]								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

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

						# verify the logits
						lowerCamelCase__ :      List[Any]								=		torch.Size((1, 1000)				)
						self.assertEqual(outputs.logits.shape							,    __magic_name__				)

						lowerCamelCase__ :      Optional[Any]								=		torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]				).to(__magic_name__				)

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





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Optional[int]								=		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)
						lowerCamelCase__ :      Dict								=		model.to(__magic_name__				)

						lowerCamelCase__ :      str								=		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)

						lowerCamelCase__ :      str								=		prepare_img()
						lowerCamelCase__ :      str								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

						# forward pass
						with torch.no_grad():
									lowerCamelCase__ :      Dict								=		model(**__magic_name__				)
						lowerCamelCase__ :      List[str]								=		outputs.logits

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

						lowerCamelCase__ :      Any								=		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=__magic_name__							,    )

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





			@slow
			def        _snake_case    (self				):
						lowerCamelCase__ :      Union[str, Any]								=		MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)
						lowerCamelCase__ :      List[Any]								=		model.to(__magic_name__				)

						lowerCamelCase__ :      Optional[int]								=		MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""				)

						lowerCamelCase__ :      Union[str, Any]								=		prepare_img()
						lowerCamelCase__ :      Dict								=		image_processor(images=__magic_name__							,    return_tensors="""pt"""				).to(__magic_name__				)

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

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

						lowerCamelCase__ :      Optional[int]								=		image_processor.post_process_semantic_segmentation(outputs=__magic_name__							,    target_sizes=[(50, 60)]				)
						lowerCamelCase__ :      List[Any]								=		torch.Size((50, 60)				)
						self.assertEqual(segmentation[0].shape							,    __magic_name__				)

						lowerCamelCase__ :      List[str]								=		image_processor.post_process_semantic_segmentation(outputs=__magic_name__				)
						lowerCamelCase__ :      int								=		torch.Size((32, 32)				)
						self.assertEqual(segmentation[0].shape							,    __magic_name__				)



