
import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
				from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
				from PIL import Image

				from transformers import MobileViTImageProcessor






class 				SCREAMING_SNAKE_CASE__			(							SCREAMING_SNAKE_CASE_			):

							"""simple docstring"""






							def 			A__						(     self	)->      Tuple:





													'''simple docstring'''






													__UpperCamelCase        =	self.config_class(**self.inputs_dict	)
													self.parent.assertTrue(hasattr(__UpperCAmelCase   ,		'''hidden_sizes'''	)	)
													self.parent.assertTrue(hasattr(__UpperCAmelCase   ,		'''neck_hidden_sizes'''	)	)
													self.parent.assertTrue(hasattr(__UpperCAmelCase   ,		'''num_attention_heads'''	)	)






class 				SCREAMING_SNAKE_CASE__			:

							"""simple docstring"""






							def __init__(     self   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_=13   ,		SCREAMING_SNAKE_CASE_=32   ,		SCREAMING_SNAKE_CASE_=2   ,		SCREAMING_SNAKE_CASE_=3   ,		SCREAMING_SNAKE_CASE_=640   ,		SCREAMING_SNAKE_CASE_=4   ,		SCREAMING_SNAKE_CASE_="silu"   ,		SCREAMING_SNAKE_CASE_=3   ,		SCREAMING_SNAKE_CASE_=32   ,		SCREAMING_SNAKE_CASE_=0.1   ,		SCREAMING_SNAKE_CASE_=0.1   ,		SCREAMING_SNAKE_CASE_=0.1   ,		SCREAMING_SNAKE_CASE_=0.0_2   ,		SCREAMING_SNAKE_CASE_=True   ,		SCREAMING_SNAKE_CASE_=True   ,		SCREAMING_SNAKE_CASE_=10   ,		SCREAMING_SNAKE_CASE_=None   ,		)->      Optional[int]:





													'''simple docstring'''






													__UpperCamelCase        =	parent
													__UpperCamelCase        =	batch_size
													__UpperCamelCase        =	image_size
													__UpperCamelCase        =	patch_size
													__UpperCamelCase        =	num_channels
													__UpperCamelCase        =	last_hidden_size
													__UpperCamelCase        =	num_attention_heads
													__UpperCamelCase        =	hidden_act
													__UpperCamelCase        =	conv_kernel_size
													__UpperCamelCase        =	output_stride
													__UpperCamelCase        =	hidden_dropout_prob
													__UpperCamelCase        =	attention_probs_dropout_prob
													__UpperCamelCase        =	classifier_dropout_prob
													__UpperCamelCase        =	use_labels
													__UpperCamelCase        =	is_training
													__UpperCamelCase        =	num_labels
													__UpperCamelCase        =	initializer_range
													__UpperCamelCase        =	scope



							def 			A__						(     self	)->      Dict:





													'''simple docstring'''






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

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

													__UpperCamelCase        =	self.get_config()

													return config, pixel_values, labels, pixel_labels



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





													'''simple docstring'''






													return MobileViTConfig(
													    image_size=self.image_size   ,		patch_size=self.patch_size   ,		num_channels=self.num_channels   ,		num_attention_heads=self.num_attention_heads   ,		hidden_act=self.hidden_act   ,		conv_kernel_size=self.conv_kernel_size   ,		output_stride=self.output_stride   ,		hidden_dropout_prob=self.hidden_dropout_prob   ,		attention_probs_dropout_prob=self.attention_probs_dropout_prob   ,		classifier_dropout_prob=self.classifier_dropout_prob   ,		initializer_range=self.initializer_range   ,		)



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	MobileViTModel(config=__UpperCAmelCase	)
													model.to(__UpperCAmelCase	)
													model.eval()
													__UpperCamelCase        =	model(__UpperCAmelCase	)
													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 			A__						(     self   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_	)->      Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase        =	self.num_labels
													__UpperCamelCase        =	MobileViTForImageClassification(__UpperCAmelCase	)
													model.to(__UpperCAmelCase	)
													model.eval()
													__UpperCamelCase        =	model(__UpperCAmelCase   ,		labels=__UpperCAmelCase	)
													self.parent.assertEqual(result.logits.shape   ,		(self.batch_size, self.num_labels)	)



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_	)->      Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase        =	self.num_labels
													__UpperCamelCase        =	MobileViTForSemanticSegmentation(__UpperCAmelCase	)
													model.to(__UpperCAmelCase	)
													model.eval()
													__UpperCamelCase        =	model(__UpperCAmelCase	)
													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        =	model(__UpperCAmelCase   ,		labels=__UpperCAmelCase	)
													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 			A__						(     self	)->      int:





													'''simple docstring'''






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






@require_torch
class 				SCREAMING_SNAKE_CASE__			(							SCREAMING_SNAKE_CASE_      ,						SCREAMING_SNAKE_CASE_      ,						unittest.TestCase			):

							"""simple docstring"""






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

							_snake_case   						=     False
							_snake_case   						=     False
							_snake_case   						=     False
							_snake_case   						=     False



							def 			A__						(     self	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	MobileViTModelTester(self	)
													__UpperCamelCase        =	MobileViTConfigTester(self   ,		config_class=__UpperCAmelCase   ,		has_text_modality=__UpperCAmelCase	)



							def 			A__						(     self	)->      List[str]:





													'''simple docstring'''






													self.config_tester.run_common_tests()



							@unittest.skip(reason='''MobileViT does not use inputs_embeds'''	)
							def 			A__						(     self	)->      str:





													'''simple docstring'''






													pass



							@unittest.skip(reason='''MobileViT does not support input and output embeddings'''	)
							def 			A__						(     self	)->      str:





													'''simple docstring'''






													pass



							@unittest.skip(reason='''MobileViT does not output attentions'''	)
							def 			A__						(     self	)->      Optional[Any]:





													'''simple docstring'''






													pass



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





													'''simple docstring'''






													__UpperCamelCase        =	self.model_tester.prepare_config_and_inputs_for_common()

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

																			__UpperCamelCase        =	['pixel_values']
																			self.assertListEqual(arg_names[:1]   ,		__UpperCAmelCase	)



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





													'''simple docstring'''






													pass



							def 			A__						(     self	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__UpperCAmelCase	)



							def 			A__						(     self	)->      Optional[Any]:





													'''simple docstring'''






													def check_hidden_states_output(SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_	):
																			__UpperCamelCase        =	model_class(__UpperCAmelCase	)
																			model.to(__UpperCAmelCase	)
																			model.eval()

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

																			__UpperCamelCase        =	outputs.hidden_states

																			__UpperCamelCase        =	5
																			self.assertEqual(len(__UpperCAmelCase	)   ,		__UpperCAmelCase	)

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

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

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

																			check_hidden_states_output(__UpperCAmelCase   ,		__UpperCAmelCase   ,		__UpperCAmelCase	)



							def 			A__						(     self	)->      Tuple:





													'''simple docstring'''






													__UpperCamelCase        =	self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase	)



							def 			A__						(     self	)->      Tuple:





													'''simple docstring'''






													__UpperCamelCase        =	self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase	)



							@slow
							def 			A__						(     self	)->      Dict:





													'''simple docstring'''






													for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			__UpperCamelCase        =	MobileViTModel.from_pretrained(__UpperCAmelCase	)
																			self.assertIsNotNone(__UpperCAmelCase	)





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



						'''simple docstring'''

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






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

							"""simple docstring"""






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





													'''simple docstring'''






													return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''	) if is_vision_available() else None



							@slow
							def 			A__						(     self	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''	).to(__UpperCAmelCase	)

													__UpperCamelCase        =	self.default_image_processor
													__UpperCamelCase        =	prepare_img()
													__UpperCamelCase        =	image_processor(images=__UpperCAmelCase   ,		return_tensors='''pt'''	).to(__UpperCAmelCase	)

													# forward pass
													with torch.no_grad():
																			__UpperCamelCase        =	model(**__UpperCAmelCase	)

													# verify the logits
													__UpperCamelCase        =	torch.Size((1, 1000)	)
													self.assertEqual(outputs.logits.shape   ,		__UpperCAmelCase	)

													__UpperCamelCase        =	torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]	).to(__UpperCAmelCase	)

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



							@slow
							def 			A__						(     self	)->      int:





													'''simple docstring'''






													__UpperCamelCase        =	MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)
													__UpperCamelCase        =	model.to(__UpperCAmelCase	)

													__UpperCamelCase        =	MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)

													__UpperCamelCase        =	prepare_img()
													__UpperCamelCase        =	image_processor(images=__UpperCAmelCase   ,		return_tensors='''pt'''	).to(__UpperCAmelCase	)

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

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

													__UpperCamelCase        =	torch.tensor(
													    [
													        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
													        [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
													        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
													    ]   ,		device=__UpperCAmelCase   ,		)

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



							@slow
							def 			A__						(     self	)->      Any:





													'''simple docstring'''






													__UpperCamelCase        =	MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)
													__UpperCamelCase        =	model.to(__UpperCAmelCase	)

													__UpperCamelCase        =	MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)

													__UpperCamelCase        =	prepare_img()
													__UpperCamelCase        =	image_processor(images=__UpperCAmelCase   ,		return_tensors='''pt'''	).to(__UpperCAmelCase	)

													# forward pass
													with torch.no_grad():
																			__UpperCamelCase        =	model(**__UpperCAmelCase	)

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

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

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











"""simple docstring"""





import argparse

import torch

from transformers import BertConfig, BertForPreTraining, load_tf_weights_in_bert
from transformers.utils import logging


logging.set_verbosity_info()
def  __A   (_SCREAMING_SNAKE_CASE     ,   _SCREAMING_SNAKE_CASE     ,   _SCREAMING_SNAKE_CASE			)					->Dict:





  """simple docstring"""


  lowerCAmelCase__			:str											=							BertConfig.from_json_file(_SCREAMING_SNAKE_CASE			)
  print(F"Building PyTorch model from configuration: {config}"			)
  lowerCAmelCase__			:int											=							BertForPreTraining(_SCREAMING_SNAKE_CASE			)

  # Load weights from tf checkpoint
  load_tf_weights_in_bert(_SCREAMING_SNAKE_CASE     ,   _SCREAMING_SNAKE_CASE     ,   _SCREAMING_SNAKE_CASE			)

  # Save pytorch-model
  print(F"Save PyTorch model to {pytorch_dump_path}"			)
  torch.save(model.state_dict()     ,   _SCREAMING_SNAKE_CASE			)


if __name__ == "__main__":
  __A											=		argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      """--tf_checkpoint_path""", default=None, type=str, required=True, help="""Path to the TensorFlow checkpoint path."""
  )
  parser.add_argument(
      """--bert_config_file""",
      default=None,
      type=str,
      required=True,
      help=(
          """The config json file corresponding to the pre-trained BERT model. \n"""
          """This specifies the model architecture."""
      ),
  )
  parser.add_argument(
      """--pytorch_dump_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
  )
  __A											=		parser.parse_args()
  convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)
