

"""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        SCREAMING_SNAKE_CASE      (	a_ ):






					"""simple docstring"""



					def  __lowerCAmelCase				( self    :       str	):
						lowerCAmelCase__			:		Dict						       =			self.config_class(**self.inputs_dict	)
						self.parent.assertTrue(hasattr(lowercase_     ,'''hidden_sizes'''	)	)
						self.parent.assertTrue(hasattr(lowercase_     ,'''neck_hidden_sizes'''	)	)
						self.parent.assertTrue(hasattr(lowercase_     ,'''num_attention_heads'''	)	)







class        SCREAMING_SNAKE_CASE      :






					"""simple docstring"""



					def __init__( self    :       Any     ,lowercase_    :       Optional[Any]     ,lowercase_    :       int=1_3     ,lowercase_    :       str=3_2     ,lowercase_    :       Dict=2     ,lowercase_    :       Optional[Any]=3     ,lowercase_    :       Dict=6_4_0     ,lowercase_    :       Optional[int]=4     ,lowercase_    :       Union[str, Any]="silu"     ,lowercase_    :       Any=3     ,lowercase_    :       str=3_2     ,lowercase_    :       Any=0.1     ,lowercase_    :       List[Any]=0.1     ,lowercase_    :       Optional[int]=0.1     ,lowercase_    :       List[str]=0.02     ,lowercase_    :       Tuple=True     ,lowercase_    :       Any=True     ,lowercase_    :       str=1_0     ,lowercase_    :       Union[str, Any]=None     ,):
						lowerCAmelCase__			:		Union[str, Any]						       =			parent
						lowerCAmelCase__			:		Any						       =			batch_size
						lowerCAmelCase__			:		int						       =			image_size
						lowerCAmelCase__			:		List[str]						       =			patch_size
						lowerCAmelCase__			:		Any						       =			num_channels
						lowerCAmelCase__			:		Optional[Any]						       =			last_hidden_size
						lowerCAmelCase__			:		Union[str, Any]						       =			num_attention_heads
						lowerCAmelCase__			:		List[Any]						       =			hidden_act
						lowerCAmelCase__			:		int						       =			conv_kernel_size
						lowerCAmelCase__			:		Union[str, Any]						       =			output_stride
						lowerCAmelCase__			:		Dict						       =			hidden_dropout_prob
						lowerCAmelCase__			:		Any						       =			attention_probs_dropout_prob
						lowerCAmelCase__			:		str						       =			classifier_dropout_prob
						lowerCAmelCase__			:		Union[str, Any]						       =			use_labels
						lowerCAmelCase__			:		Optional[Any]						       =			is_training
						lowerCAmelCase__			:		Union[str, Any]						       =			num_labels
						lowerCAmelCase__			:		int						       =			initializer_range
						lowerCAmelCase__			:		Optional[int]						       =			scope







					def  __lowerCAmelCase				( self    :       int	):
						lowerCAmelCase__			:		Dict						       =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

						lowerCAmelCase__			:		Tuple						       =			None
						lowerCAmelCase__			:		Union[str, Any]						       =			None
						if self.use_labels:
							lowerCAmelCase__			:		Optional[Any]						       =			ids_tensor([self.batch_size]     ,self.num_labels	)
							lowerCAmelCase__			:		Any						       =			ids_tensor([self.batch_size, self.image_size, self.image_size]     ,self.num_labels	)

						lowerCAmelCase__			:		Optional[Any]						       =			self.get_config()

						return config, pixel_values, labels, pixel_labels







					def  __lowerCAmelCase				( self    :       Optional[int]	):
						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  __lowerCAmelCase				( self    :       Any     ,lowercase_    :       List[Any]     ,lowercase_    :       int     ,lowercase_    :       List[Any]     ,lowercase_    :       Union[str, Any]	):
						lowerCAmelCase__			:		Any						       =			TFMobileViTModel(config=lowercase_	)
						lowerCAmelCase__			:		Optional[int]						       =			model(lowercase_     ,training=lowercase_	)
						lowerCAmelCase__			:		Union[str, Any]						       =			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  __lowerCAmelCase				( self    :       List[str]     ,lowercase_    :       Optional[int]     ,lowercase_    :       List[Any]     ,lowercase_    :       Dict     ,lowercase_    :       List[str]	):
						lowerCAmelCase__			:		Union[str, Any]						       =			self.num_labels
						lowerCAmelCase__			:		str						       =			TFMobileViTForImageClassification(lowercase_	)
						lowerCAmelCase__			:		List[str]						       =			model(lowercase_     ,labels=lowercase_     ,training=lowercase_	)
						self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.num_labels)	)







					def  __lowerCAmelCase				( self    :       Dict     ,lowercase_    :       List[Any]     ,lowercase_    :       Optional[Any]     ,lowercase_    :       List[Any]     ,lowercase_    :       Union[str, Any]	):
						lowerCAmelCase__			:		Optional[int]						       =			self.num_labels
						lowerCAmelCase__			:		str						       =			TFMobileViTForSemanticSegmentation(lowercase_	)
						lowerCAmelCase__			:		str						       =			self.image_size // self.output_stride

						lowerCAmelCase__			:		Union[str, Any]						       =			model(lowercase_     ,training=lowercase_	)
						self.parent.assertEqual(
						    result.logits.shape     ,(self.batch_size, self.num_labels, expected_height, expected_width)	)

						lowerCAmelCase__			:		Optional[int]						       =			model(lowercase_     ,labels=lowercase_     ,training=lowercase_	)
						self.parent.assertEqual(
						    result.logits.shape     ,(self.batch_size, self.num_labels, expected_height, expected_width)	)







					def  __lowerCAmelCase				( self    :       Tuple	):
						lowerCAmelCase__			:		List[str]						       =			self.prepare_config_and_inputs()
						lowerCAmelCase__			:		List[str]						       =			config_and_inputs
						lowerCAmelCase__			:		Union[str, Any]						       =			{'''pixel_values''': pixel_values}
						return config, inputs_dict







@require_tf
class        SCREAMING_SNAKE_CASE      (	a_					,							a_					,							unittest.TestCase ):






					"""simple docstring"""



					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  __lowerCAmelCase				( self    :       List[Any]	):
						lowerCAmelCase__			:		Union[str, Any]						       =			TFMobileViTModelTester(self	)
						lowerCAmelCase__			:		List[str]						       =			TFMobileViTConfigTester(self     ,config_class=lowercase_     ,has_text_modality=lowercase_	)







					def  __lowerCAmelCase				( self    :       Any	):
						self.config_tester.run_common_tests()







					@unittest.skip(reason='''MobileViT does not use inputs_embeds'''	)
					def  __lowerCAmelCase				( self    :       Optional[int]	):
						pass







					@unittest.skip(reason='''MobileViT does not support input and output embeddings'''	)
					def  __lowerCAmelCase				( self    :       Tuple	):
						pass







					@unittest.skip(reason='''MobileViT does not output attentions'''	)
					def  __lowerCAmelCase				( self    :       str	):
						pass







					def  __lowerCAmelCase				( self    :       Tuple	):
						lowerCAmelCase__			:		Dict						       =			self.model_tester.prepare_config_and_inputs_for_common()

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

							lowerCAmelCase__			:		str						       =			['''pixel_values''']
							self.assertListEqual(arg_names[:1]     ,lowercase_	)







					def  __lowerCAmelCase				( self    :       str	):
						lowerCAmelCase__			:		Tuple						       =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowercase_	)







					def  __lowerCAmelCase				( self    :       Optional[int]	):
						def check_hidden_states_output(lowercase_    :       Any     ,lowercase_    :       List[Any]     ,lowercase_    :       int	):
							lowerCAmelCase__			:		Dict						       =			model_class(lowercase_	)

							lowerCAmelCase__			:		Optional[Any]						       =			model(**self._prepare_for_class(lowercase_     ,lowercase_	)	)

							lowerCAmelCase__			:		Tuple						       =			outputs.hidden_states

							lowerCAmelCase__			:		Dict						       =			5
							self.assertEqual(len(lowercase_	)     ,lowercase_	)

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

						for model_class in self.all_model_classes:
							lowerCAmelCase__			:		List[str]						       =			True
							check_hidden_states_output(lowercase_     ,lowercase_     ,lowercase_	)

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

							check_hidden_states_output(lowercase_     ,lowercase_     ,lowercase_	)







					def  __lowerCAmelCase				( self    :       Tuple	):
						lowerCAmelCase__			:		List[str]						       =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*lowercase_	)







					def  __lowerCAmelCase				( self    :       List[str]	):
						lowerCAmelCase__			:		Optional[int]						       =			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_	)







					@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  __lowerCAmelCase				( self    :       int	):
						super().test_dataset_conversion()







					def  __lowerCAmelCase				( self    :       Dict     ,lowercase_    :       Optional[int]     ,lowercase_    :       Any     ,lowercase_    :       Optional[int]=2E-1     ,lowercase_    :       int=2E-1	):
						self.assertTrue(np.allclose(lowercase_     ,lowercase_     ,atol=lowercase_     ,rtol=lowercase_	)	)







					@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  __lowerCAmelCase				( self    :       int	):
						lowerCAmelCase__			:		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__			:		Union[str, Any]						       =			model_class(lowercase_	)
								if getattr(lowercase_     ,'''hf_compute_loss'''     ,lowercase_	):
									super().test_keras_fit()







					def  __lowerCAmelCase				( self    :       int	):
						lowerCAmelCase__			:		Any						       =			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__			:		Any						       =			5

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

								# Test that model correctly compute the loss with kwargs
								lowerCAmelCase__			:		Union[str, Any]						       =			self._prepare_for_class(inputs_dict.copy()     ,lowercase_     ,return_labels=lowercase_	)
								lowerCAmelCase__			:		Union[str, Any]						       =			{'''input_ids''', '''pixel_values''', '''input_features'''}
								lowerCAmelCase__			:		Optional[Any]						       =			possible_input_names.intersection(set(lowercase_	)	).pop()
								lowerCAmelCase__			:		Any						       =			prepared_for_class.pop(lowercase_	)

								lowerCAmelCase__			:		Optional[Any]						       =			model(lowercase_     ,**lowercase_	)[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__			:		Optional[int]						       =			self._prepare_for_class(inputs_dict.copy()     ,lowercase_     ,return_labels=lowercase_	)
								lowerCAmelCase__			:		str						       =			{'''input_ids''', '''pixel_values''', '''input_features'''}
								lowerCAmelCase__			:		List[str]						       =			possible_input_names.intersection(set(lowercase_	)	).pop()
								lowerCAmelCase__			:		Optional[Any]						       =			prepared_for_class.pop(lowercase_	)
								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__			:		Tuple						       =			tf.convert_to_tensor(lowercase_	)
										lowerCAmelCase__			:		Optional[int]						       =			model(lowercase_     ,**lowercase_	)[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__			:		List[Any]						       =			self._prepare_for_class(inputs_dict.copy()     ,lowercase_     ,return_labels=lowercase_	)
								lowerCAmelCase__			:		Dict						       =			model(lowercase_	)[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__			:		Optional[Any]						       =			self._prepare_for_class(inputs_dict.copy()     ,lowercase_     ,return_labels=lowercase_	)

								# Get keys that were added with the _prepare_for_class function
								lowerCAmelCase__			:		int						       =			prepared_for_class.keys() - inputs_dict.keys()
								lowerCAmelCase__			:		int						       =			inspect.signature(model.call	).parameters
								lowerCAmelCase__			:		Dict						       =			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__			:		List[Any]						       =			signature_names.index(lowercase_	)
									lowerCAmelCase__			:		Any						       =			label_key
								lowerCAmelCase__			:		Any						       =			sorted(tuple_index_mapping.items()	)
								# Initialize a list with their default values, update the values and convert to a tuple
								lowerCAmelCase__			:		str						       =			[]

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

								for index, value in sorted_tuple_index_mapping:
									lowerCAmelCase__			:		List[str]						       =			prepared_for_class[value]

								lowerCAmelCase__			:		List[Any]						       =			tuple(lowercase_	)

								# Send to model
								lowerCAmelCase__			:		Optional[Any]						       =			model(tuple_input[:-1]	)[0]

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







					@slow
					def  __lowerCAmelCase				( self    :       List[str]	):
						for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							lowerCAmelCase__			:		Optional[Any]						       =			TFMobileViTModel.from_pretrained(lowercase_	)
							self.assertIsNotNone(lowercase_	)

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







@require_tf
class        SCREAMING_SNAKE_CASE      (	unittest.TestCase ):






					"""simple docstring"""



					@slow
					def  __lowerCAmelCase				( self    :       Optional[Any]	):
						lowerCAmelCase__			:		List[str]						       =			TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''	)

						lowerCAmelCase__			:		Optional[int]						       =			MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''	)
						lowerCAmelCase__			:		str						       =			prepare_img()
						lowerCAmelCase__			:		int						       =			image_processor(images=lowercase_     ,return_tensors='''tf'''	)

						# forward pass
						lowerCAmelCase__			:		Tuple						       =			model(**lowercase_     ,training=lowercase_	)

						# verify the logits
						lowerCAmelCase__			:		str						       =			tf.TensorShape((1, 1_0_0_0)	)
						self.assertEqual(outputs.logits.shape     ,lowercase_	)

						lowerCAmelCase__			:		Dict						       =			tf.constant([-1.9364, -1.2327, -0.4653]	)

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







					@slow
					def  __lowerCAmelCase				( self    :       int	):
						# `from_pt` will be removed
						lowerCAmelCase__			:		Any						       =			TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)

						lowerCAmelCase__			:		int						       =			MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''	)

						lowerCAmelCase__			:		Any						       =			prepare_img()
						lowerCAmelCase__			:		int						       =			image_processor(images=lowercase_     ,return_tensors='''tf'''	)

						# forward pass
						lowerCAmelCase__			:		Any						       =			model(inputs.pixel_values     ,training=lowercase_	)
						lowerCAmelCase__			:		List[Any]						       =			outputs.logits

						# verify the logits
						lowerCAmelCase__			:		str						       =			tf.TensorShape((1, 2_1, 3_2, 3_2)	)
						self.assertEqual(logits.shape     ,lowercase_	)

						lowerCAmelCase__			:		List[Any]						       =			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]     ,lowercase_     ,rtol=1E-4     ,atol=1E-4	)







"""simple docstring"""





def 						__SCREAMING_SNAKE_CASE						(   A_				):
	lowerCAmelCase__			:		List[Any]						       =			53_81
	for x in s:
		lowerCAmelCase__			:		Tuple						       =			((hash_value << 5) + hash_value) + ord(A_				)
	return hash_value & 0Xf_f_f_f_f_f_f_f




