
"""simple docstring"""

from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import numpy as np
					import tensorflow as tf

					from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
					from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import MobileViTImageProcessor






class 			_lowercase  (							__UpperCAmelCase						):




	def      _UpperCamelCase       (					self   )						->				Tuple:
			lowerCamelCase	:     Dict            =       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 			_lowercase  :




	def __init__(					self						,					UpperCAmelCase_						,					UpperCAmelCase_=13						,					UpperCAmelCase_=32						,					UpperCAmelCase_=2						,					UpperCAmelCase_=3						,					UpperCAmelCase_=640						,					UpperCAmelCase_=4						,					UpperCAmelCase_="silu"						,					UpperCAmelCase_=3						,					UpperCAmelCase_=32						,					UpperCAmelCase_=0.1						,					UpperCAmelCase_=0.1						,					UpperCAmelCase_=0.1						,					UpperCAmelCase_=0.02						,					UpperCAmelCase_=True						,					UpperCAmelCase_=True						,					UpperCAmelCase_=10						,					UpperCAmelCase_=None						,					)						->				Dict:
			lowerCamelCase	:     List[Any]            =       parent
			lowerCamelCase	:     Union[str, Any]            =       batch_size
			lowerCamelCase	:     List[Any]            =       image_size
			lowerCamelCase	:     Tuple            =       patch_size
			lowerCamelCase	:     Optional[Any]            =       num_channels
			lowerCamelCase	:     Tuple            =       last_hidden_size
			lowerCamelCase	:     Optional[int]            =       num_attention_heads
			lowerCamelCase	:     Tuple            =       hidden_act
			lowerCamelCase	:     int            =       conv_kernel_size
			lowerCamelCase	:     Optional[Any]            =       output_stride
			lowerCamelCase	:     Any            =       hidden_dropout_prob
			lowerCamelCase	:     int            =       attention_probs_dropout_prob
			lowerCamelCase	:     Union[str, Any]            =       classifier_dropout_prob
			lowerCamelCase	:     Optional[Any]            =       use_labels
			lowerCamelCase	:     Tuple            =       is_training
			lowerCamelCase	:     int            =       num_labels
			lowerCamelCase	:     Tuple            =       initializer_range
			lowerCamelCase	:     Union[str, Any]            =       scope




	def      _UpperCamelCase       (					self   )						->				Dict:
			lowerCamelCase	:     Union[str, Any]            =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

			lowerCamelCase	:     List[Any]            =       None
			lowerCamelCase	:     Optional[Any]            =       None
			if self.use_labels:
					lowerCamelCase	:     Optional[Any]            =       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	:     Optional[int]            =       self.get_config()

			return config, pixel_values, labels, pixel_labels




	def      _UpperCamelCase       (					self   )						->				Union[str, Any]:
			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      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				Any:
			lowerCamelCase	:     Optional[int]            =       TFMobileViTModel(config=UpperCAmelCase__   )
			lowerCamelCase	:     Union[str, Any]            =       model(UpperCAmelCase__						,					training=UpperCAmelCase__   )
			lowerCamelCase	:     Dict            =       self.image_size // self.output_stride
			self.parent.assertEqual(
			    result.last_hidden_state.shape						,					(self.batch_size, self.last_hidden_size, expected_height, expected_width)   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				List[Any]:
			lowerCamelCase	:     Tuple            =       self.num_labels
			lowerCamelCase	:     Any            =       TFMobileViTForImageClassification(UpperCAmelCase__   )
			lowerCamelCase	:     Any            =       model(UpperCAmelCase__						,					labels=UpperCAmelCase__						,					training=UpperCAmelCase__   )
			self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				int:
			lowerCamelCase	:     Optional[int]            =       self.num_labels
			lowerCamelCase	:     Dict            =       TFMobileViTForSemanticSegmentation(UpperCAmelCase__   )
			lowerCamelCase	:     Dict            =       self.image_size // self.output_stride

			lowerCamelCase	:     int            =       model(UpperCAmelCase__						,					training=UpperCAmelCase__   )
			self.parent.assertEqual(
			    result.logits.shape						,					(self.batch_size, self.num_labels, expected_height, expected_width)   )

			lowerCamelCase	:     List[str]            =       model(UpperCAmelCase__						,					labels=UpperCAmelCase__						,					training=UpperCAmelCase__   )
			self.parent.assertEqual(
			    result.logits.shape						,					(self.batch_size, self.num_labels, expected_height, expected_width)   )




	def      _UpperCamelCase       (					self   )						->				Optional[Any]:
			lowerCamelCase	:     List[str]            =       self.prepare_config_and_inputs()
			lowerCamelCase	:     Optional[Any]            =       config_and_inputs
			lowerCamelCase	:     List[str]            =       {"""pixel_values""": pixel_values}
			return config, inputs_dict






@require_tf
class 			_lowercase  (							__UpperCAmelCase							,			__UpperCAmelCase							,			unittest.TestCase						):
	lowercase_								=      (
	    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
	    if is_tf_available()
	    else ()
	)
	lowercase_								=      (
	    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowercase_								=      False
	lowercase_								=      False
	lowercase_								=      False
	lowercase_								=      False
	lowercase_								=      False




	def      _UpperCamelCase       (					self   )						->				Union[str, Any]:
			lowerCamelCase	:     str            =       TFMobileViTModelTester(self   )
			lowerCamelCase	:     List[str]            =       TFMobileViTConfigTester(self						,					config_class=UpperCAmelCase__						,					has_text_modality=UpperCAmelCase__   )




	def      _UpperCamelCase       (					self   )						->				Optional[Any]:
			self.config_tester.run_common_tests()




	@unittest.skip(reason='MobileViT does not use inputs_embeds'   )
	def      _UpperCamelCase       (					self   )						->				List[Any]:
			pass




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




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




	def      _UpperCamelCase       (					self   )						->				Dict:
			lowerCamelCase	:     Union[str, Any]            =       self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					lowerCamelCase	:     str            =       model_class(UpperCAmelCase__   )
					lowerCamelCase	:     Optional[int]            =       inspect.signature(model.call   )
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					lowerCamelCase	:     Any            =       [*signature.parameters.keys()]

					lowerCamelCase	:     Any            =       ["""pixel_values"""]
					self.assertListEqual(arg_names[:1]						,					UpperCAmelCase__   )




	def      _UpperCamelCase       (					self   )						->				Tuple:
			lowerCamelCase	:     Tuple            =       self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*UpperCAmelCase__   )




	def      _UpperCamelCase       (					self   )						->				Tuple:







			def check_hidden_states_output(UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   ):
					lowerCamelCase	:     str            =       model_class(UpperCAmelCase__   )

					lowerCamelCase	:     Any            =       model(**self._prepare_for_class(UpperCAmelCase__						,					UpperCAmelCase__   )   )

					lowerCamelCase	:     List[str]            =       outputs.hidden_states

					lowerCamelCase	:     List[Any]            =       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.
					lowerCamelCase	:     str            =       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   )

			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(UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__   )

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

					check_hidden_states_output(UpperCAmelCase__						,					UpperCAmelCase__						,					UpperCAmelCase__   )




	def      _UpperCamelCase       (					self   )						->				Tuple:
			lowerCamelCase	:     Union[str, Any]            =       self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__   )




	def      _UpperCamelCase       (					self   )						->				Dict:
			lowerCamelCase	:     int            =       self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase__   )




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0						,					reason='TF does not support backprop for grouped convolutions on CPU.'						,					)
	def      _UpperCamelCase       (					self   )						->				str:
			super().test_dataset_conversion()




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_=2E-1						,					UpperCAmelCase_=2E-1   )						->				Optional[int]:
			self.assertTrue(np.allclose(UpperCAmelCase__						,					UpperCAmelCase__						,					atol=UpperCAmelCase__						,					rtol=UpperCAmelCase__   )   )




	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices('GPU'   )   ) == 0						,					reason='TF does not support backprop for grouped convolutions on CPU.'						,					)
	@slow
	def      _UpperCamelCase       (					self   )						->				Any:
			lowerCamelCase	:     List[str]            =       self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					# Since `TFMobileViTModel` cannot operate with the default `fit()` method.
					if model_class.__name__ != "TFMobileViTModel":
							lowerCamelCase	:     Dict            =       model_class(UpperCAmelCase__   )
							if getattr(UpperCAmelCase__						,					'hf_compute_loss'						,					UpperCAmelCase__   ):
									super().test_keras_fit()




	def      _UpperCamelCase       (					self   )						->				int:
			lowerCamelCase	:     List[str]            =       self.model_tester.prepare_config_and_inputs_for_common()
			for model_class in self.all_model_classes:
					# set an ignore index to correctly test the masked loss used in
					# `TFMobileViTForSemanticSegmentation`.
					if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
							lowerCamelCase	:     str            =       5

					lowerCamelCase	:     int            =       model_class(UpperCAmelCase__   )
					if getattr(UpperCAmelCase__						,					'hf_compute_loss'						,					UpperCAmelCase__   ):
							# The number of elements in the loss should be the same as the number of elements in the label
							lowerCamelCase	:     Dict            =       self._prepare_for_class(inputs_dict.copy()						,					UpperCAmelCase__						,					return_labels=UpperCAmelCase__   )
							lowerCamelCase	:     Optional[int]            =       prepared_for_class[
							    sorted(prepared_for_class.keys() - inputs_dict.keys()						,					reverse=UpperCAmelCase__   )[0]
							]
							lowerCamelCase	:     int            =       added_label.shape.as_list()[:1]

							# Test that model correctly compute the loss with kwargs
							lowerCamelCase	:     List[str]            =       self._prepare_for_class(inputs_dict.copy()						,					UpperCAmelCase__						,					return_labels=UpperCAmelCase__   )
							lowerCamelCase	:     Dict            =       {"""input_ids""", """pixel_values""", """input_features"""}
							lowerCamelCase	:     int            =       possible_input_names.intersection(set(UpperCAmelCase__   )   ).pop()
							lowerCamelCase	:     str            =       prepared_for_class.pop(UpperCAmelCase__   )

							lowerCamelCase	:     Optional[int]            =       model(UpperCAmelCase__						,					**UpperCAmelCase__   )[0]
							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

							# Test that model correctly compute the loss when we mask some positions
							lowerCamelCase	:     str            =       self._prepare_for_class(inputs_dict.copy()						,					UpperCAmelCase__						,					return_labels=UpperCAmelCase__   )
							lowerCamelCase	:     str            =       {"""input_ids""", """pixel_values""", """input_features"""}
							lowerCamelCase	:     int            =       possible_input_names.intersection(set(UpperCAmelCase__   )   ).pop()
							lowerCamelCase	:     Union[str, Any]            =       prepared_for_class.pop(UpperCAmelCase__   )
							if "labels" in prepared_for_class:
									lowerCamelCase	:     List[str]            =       prepared_for_class["""labels"""].numpy()
									if len(labels.shape   ) > 1 and labels.shape[1] != 1:
											# labels[0] = -100
											lowerCamelCase	:     List[Any]            =       tf.convert_to_tensor(UpperCAmelCase__   )
											lowerCamelCase	:     Union[str, Any]            =       model(UpperCAmelCase__						,					**UpperCAmelCase__   )[0]
											self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )
											self.assertTrue(not np.any(np.isnan(loss.numpy()   )   )   )

                # Test that model correctly compute the loss with a dict
							lowerCamelCase	:     Optional[Any]            =       self._prepare_for_class(inputs_dict.copy()						,					UpperCAmelCase__						,					return_labels=UpperCAmelCase__   )
							lowerCamelCase	:     Union[str, Any]            =       model(UpperCAmelCase__   )[0]
							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

							# Test that model correctly compute the loss with a tuple
							lowerCamelCase	:     Dict            =       self._prepare_for_class(inputs_dict.copy()						,					UpperCAmelCase__						,					return_labels=UpperCAmelCase__   )

							# Get keys that were added with the _prepare_for_class function
							lowerCamelCase	:     Union[str, Any]            =       prepared_for_class.keys() - inputs_dict.keys()
							lowerCamelCase	:     Optional[Any]            =       inspect.signature(model.call   ).parameters
							lowerCamelCase	:     Optional[Any]            =       list(signature.keys()   )

							# Create a dictionary holding the location of the tensors in the tuple
							lowerCamelCase	:     List[str]            =       {0: input_name}
							for label_key in label_keys:
									lowerCamelCase	:     Any            =       signature_names.index(UpperCAmelCase__   )
									lowerCamelCase	:     int            =       label_key
							lowerCamelCase	:     Optional[Any]            =       sorted(tuple_index_mapping.items()   )
							# Initialize a list with their default values, update the values and convert to a tuple
							lowerCamelCase	:     Optional[int]            =       []

							for name in signature_names:
									if name != "kwargs":
											list_input.append(signature[name].default   )

							for index, value in sorted_tuple_index_mapping:
									lowerCamelCase	:     List[Any]            =       prepared_for_class[value]

							lowerCamelCase	:     Optional[Any]            =       tuple(UpperCAmelCase__   )

							# Send to model
							lowerCamelCase	:     List[Any]            =       model(tuple_input[:-1]   )[0]

							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )




	@slow
	def      _UpperCamelCase       (					self   )						->				Optional[int]:







			for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					lowerCamelCase	:     Tuple            =       TFMobileViTModel.from_pretrained(UpperCAmelCase__   )
					self.assertIsNotNone(UpperCAmelCase__   )


def 						UpperCAmelCase   (						):





		'''simple docstring'''


		lowerCamelCase	:     List[Any]            =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
		return image






@require_tf
class 			_lowercase  (							unittest.TestCase						):




	@slow
	def      _UpperCamelCase       (					self   )						->				Any:
			lowerCamelCase	:     List[str]            =       TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'   )

			lowerCamelCase	:     str            =       MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'   )
			lowerCamelCase	:     Tuple            =       prepare_img()
			lowerCamelCase	:     str            =       image_processor(images=UpperCAmelCase__						,					return_tensors='tf'   )

			# forward pass
			lowerCamelCase	:     Tuple            =       model(**UpperCAmelCase__						,					training=UpperCAmelCase__   )

			# verify the logits
			lowerCamelCase	:     List[Any]            =       tf.TensorShape((1, 1000)   )
			self.assertEqual(outputs.logits.shape						,					UpperCAmelCase__   )

			lowerCamelCase	:     Optional[int]            =       tf.constant([-1.9364, -1.2327, -0.4653]   )

			tf.debugging.assert_near(outputs.logits[0, :3]						,					UpperCAmelCase__						,					atol=1E-4						,					rtol=1E-0_4   )




	@slow
	def      _UpperCamelCase       (					self   )						->				Tuple:
			lowerCamelCase	:     Union[str, Any]            =       TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

			lowerCamelCase	:     Tuple            =       MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

			lowerCamelCase	:     Union[str, Any]            =       prepare_img()
			lowerCamelCase	:     Dict            =       image_processor(images=UpperCAmelCase__						,					return_tensors='tf'   )

			# forward pass
			lowerCamelCase	:     List[str]            =       model(inputs.pixel_values						,					training=UpperCAmelCase__   )
			lowerCamelCase	:     Any            =       outputs.logits

			# verify the logits
			lowerCamelCase	:     Tuple            =       tf.TensorShape((1, 21, 32, 32)   )
			self.assertEqual(logits.shape						,					UpperCAmelCase__   )

			lowerCamelCase	:     List[str]            =       tf.constant(
			    [
			        [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
			        [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
			        [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
			    ]   )

			tf.debugging.assert_near(logits[0, :3, :3, :3]						,					UpperCAmelCase__						,					rtol=1E-4						,					atol=1E-4   )









import safs







class 							a__							( safs.SaFileSystem							):







  """simple docstring"""




