


"""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_  (   _lowercase):




							'''simple docstring'''





							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.config_class(**self.inputs_dict)
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"neck_hidden_sizes"))
								self.parent.assertTrue(hasattr(lowerCamelCase__	,					"num_attention_heads"))


class 			SCREAMING_SNAKE_CASE_  :




							'''simple docstring'''





							def __init__(						self	,					lowerCamelCase__	,					lowerCamelCase__=13	,					lowerCamelCase__=32	,					lowerCamelCase__=2	,					lowerCamelCase__=3	,					lowerCamelCase__=640	,					lowerCamelCase__=4	,					lowerCamelCase__="silu"	,					lowerCamelCase__=3	,					lowerCamelCase__=32	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.1	,					lowerCamelCase__=0.02	,					lowerCamelCase__=True	,					lowerCamelCase__=True	,					lowerCamelCase__=10	,					lowerCamelCase__=None	,					)   ->	Dict:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      parent
								snake_case__  :						List[Any]		=      batch_size
								snake_case__  :						Any		=      image_size
								snake_case__  :						Tuple		=      patch_size
								snake_case__  :						int		=      num_channels
								snake_case__  :						Optional[Any]		=      last_hidden_size
								snake_case__  :						Union[str, Any]		=      num_attention_heads
								snake_case__  :						Tuple		=      hidden_act
								snake_case__  :						Optional[int]		=      conv_kernel_size
								snake_case__  :						int		=      output_stride
								snake_case__  :						Optional[Any]		=      hidden_dropout_prob
								snake_case__  :						str		=      attention_probs_dropout_prob
								snake_case__  :						Any		=      classifier_dropout_prob
								snake_case__  :						Tuple		=      use_labels
								snake_case__  :						Optional[Any]		=      is_training
								snake_case__  :						Dict		=      num_labels
								snake_case__  :						Dict		=      initializer_range
								snake_case__  :						List[str]		=      scope




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







								'''simple docstring'''




								snake_case__  :						List[Any]		=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

								snake_case__  :						Dict		=      self.get_config()

								return config, pixel_values, labels, pixel_labels




							def        UpperCAmelCase (						self)   ->	str:







								'''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        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Tuple		=      TFMobileViTModel(config=lowerCamelCase__)
								snake_case__  :						int		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								snake_case__  :						Tuple		=      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	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Any		=      self.num_labels
								snake_case__  :						Dict		=      TFMobileViTForImageClassification(lowerCamelCase__)
								snake_case__  :						List[Any]		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(result.logits.shape	,					(self.batch_size, self.num_labels))




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[Any]		=      self.num_labels
								snake_case__  :						Any		=      TFMobileViTForSemanticSegmentation(lowerCamelCase__)
								snake_case__  :						List[Any]		=      self.image_size // self.output_stride

								snake_case__  :						Tuple		=      model(lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))

								snake_case__  :						str		=      model(lowerCamelCase__	,					labels=lowerCamelCase__	,					training=lowerCamelCase__)
								self.parent.assertEqual(
								    result.logits.shape	,					(self.batch_size, self.num_labels, expected_height, expected_width))







							def        UpperCAmelCase (						self)   ->	Tuple:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.prepare_config_and_inputs()
								snake_case__,					snake_case__,					snake_case__,					snake_case__  :						List[Any]		=      config_and_inputs
								snake_case__  :						Tuple		=      {"pixel_values": pixel_values}
								return config, inputs_dict


@require_tf
class 			SCREAMING_SNAKE_CASE_  (   _lowercase	,      _lowercase	,      unittest.TestCase):




							'''simple docstring'''





							__magic_name__					:     Optional[int]				  =  (
							    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
							    if is_tf_available()
							    else ()
							)
							__magic_name__					:     str				  =  (
							    {'''feature-extraction''': TFMobileViTModel, '''image-classification''': TFMobileViTForImageClassification}
							    if is_tf_available()
							    else {}
							)

							__magic_name__					:     List[str]				  =  False
							__magic_name__					:     int				  =  False
							__magic_name__					:     Any				  =  False
							__magic_name__					:     Optional[int]				  =  False
							__magic_name__					:     Union[str, Any]				  =  False




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								snake_case__  :						Any		=      TFMobileViTModelTester(self)
								snake_case__  :						Dict		=      TFMobileViTConfigTester(self	,					config_class=lowerCamelCase__	,					has_text_modality=lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	Optional[int]:







								'''simple docstring'''




								self.config_tester.run_common_tests()




							@unittest.skip(reason="MobileViT does not use inputs_embeds")
							def        UpperCAmelCase (						self)   ->	Optional[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not support input and output embeddings")
							def        UpperCAmelCase (						self)   ->	List[Any]:







								'''simple docstring'''




								pass




							@unittest.skip(reason="MobileViT does not output attentions")
							def        UpperCAmelCase (						self)   ->	Dict:







								'''simple docstring'''




								pass




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







								'''simple docstring'''




								snake_case__,					snake_case__  :						int		=      self.model_tester.prepare_config_and_inputs_for_common()

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

									snake_case__  :						Dict		=      ["pixel_values"]
									self.assertListEqual(arg_names[:1]	,					lowerCamelCase__)




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







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*lowerCamelCase__)




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







								'''simple docstring'''




								def check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__):
									snake_case__  :						List[Any]		=      model_class(lowerCamelCase__)

									snake_case__  :						Optional[int]		=      model(**self._prepare_for_class(lowerCamelCase__	,					lowerCamelCase__))

									snake_case__  :						List[Any]		=      outputs.hidden_states

									snake_case__  :						Union[str, Any]		=      5
									self.assertEqual(len(lowerCamelCase__)	,					lowerCamelCase__)

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

								snake_case__,					snake_case__  :						Union[str, Any]		=      self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									snake_case__  :						List[Any]		=      True
									check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)

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

									check_hidden_states_output(lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__)




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







								'''simple docstring'''




								snake_case__  :						Dict		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__)




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Optional[int]		=      self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__)




							@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)   ->	Any:







								'''simple docstring'''




								super().test_dataset_conversion()




							def        UpperCAmelCase (						self	,					lowerCamelCase__	,					lowerCamelCase__	,					lowerCamelCase__=2E-1	,					lowerCamelCase__=2E-1)   ->	Optional[Any]:







								'''simple docstring'''




								self.assertTrue(np.allclose(lowerCamelCase__	,					lowerCamelCase__	,					atol=lowerCamelCase__	,					rtol=lowerCamelCase__))




							@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)   ->	int:







								'''simple docstring'''




								snake_case__,					snake_case__  :						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":
										snake_case__  :						Dict		=      model_class(lowerCamelCase__)
										if getattr(lowerCamelCase__	,					"hf_compute_loss"	,					lowerCamelCase__):
											super().test_keras_fit()




							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__,					snake_case__  :						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":
										snake_case__  :						Any		=      5

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

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

										snake_case__  :						Optional[Any]		=      model(lowerCamelCase__	,					**lowerCamelCase__)[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
										snake_case__  :						Dict		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Dict		=      {"input_ids", "pixel_values", "input_features"}
										snake_case__  :						List[Any]		=      possible_input_names.intersection(set(lowerCamelCase__)).pop()
										snake_case__  :						List[Any]		=      prepared_for_class.pop(lowerCamelCase__)
										if "labels" in prepared_for_class:
											snake_case__  :						int		=      prepared_for_class["labels"].numpy()
											if len(labels.shape) > 1 and labels.shape[1] != 1:
												# labels[0] = -100
												snake_case__  :						Union[str, Any]		=      tf.convert_to_tensor(lowerCamelCase__)
												snake_case__  :						Tuple		=      model(lowerCamelCase__	,					**lowerCamelCase__)[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
										snake_case__  :						int		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)
										snake_case__  :						Union[str, Any]		=      model(lowerCamelCase__)[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
										snake_case__  :						str		=      self._prepare_for_class(inputs_dict.copy()	,					lowerCamelCase__	,					return_labels=lowerCamelCase__)

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

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

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

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

										snake_case__  :						List[str]		=      tuple(lowerCamelCase__)

										# Send to model
										snake_case__  :						int		=      model(tuple_input[:-1])[0]

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







							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									snake_case__  :						Optional[Any]		=      TFMobileViTModel.from_pretrained(lowerCamelCase__)
									self.assertIsNotNone(lowerCamelCase__)



def 			A__		(					)							->	Optional[Any]:

	'''simple docstring'''


	snake_case__  :						Any		=      Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
	return image



@require_tf
class 			SCREAMING_SNAKE_CASE_  (   unittest.TestCase):




							'''simple docstring'''





							@slow
							def        UpperCAmelCase (						self)   ->	str:







								'''simple docstring'''




								snake_case__  :						Union[str, Any]		=      TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small")

								snake_case__  :						List[str]		=      MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small")
								snake_case__  :						Dict		=      prepare_img()
								snake_case__  :						List[str]		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						Union[str, Any]		=      model(**lowerCamelCase__	,					training=lowerCamelCase__)

								# verify the logits
								snake_case__  :						str		=      tf.TensorShape((1, 1_000))
								self.assertEqual(outputs.logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant([-1.93_64, -1.23_27, -0.46_53])

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







							@slow
							def        UpperCAmelCase (						self)   ->	List[str]:







								'''simple docstring'''




								snake_case__  :						Dict		=      TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						Any		=      MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

								snake_case__  :						List[str]		=      prepare_img()
								snake_case__  :						Dict		=      image_processor(images=lowerCamelCase__	,					return_tensors="tf")

								# forward pass
								snake_case__  :						str		=      model(inputs.pixel_values	,					training=lowerCamelCase__)
								snake_case__  :						Dict		=      outputs.logits

								# verify the logits
								snake_case__  :						Union[str, Any]		=      tf.TensorShape((1, 21, 32, 32))
								self.assertEqual(logits.shape	,					lowerCamelCase__)

								snake_case__  :						List[Any]		=      tf.constant(
								    [
								        [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
								        [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
								        [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
								    ])

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







def      __UpperCAmelCase    (  snake_case_							:		str				):



	'''simple docstring'''



	UpperCAmelCase:					Tuple 						=     str(snake_case_				).strip()
	if not bin_string:
		raise ValueError("Empty string was passed to the function"				)
	UpperCAmelCase:					List[Any] 						=     bin_string[0] == "-"
	if is_negative:
		UpperCAmelCase:					Optional[int] 						=     bin_string[1:]
	if not all(char in "01" for char in bin_string				):
		raise ValueError("Non-binary value was passed to the function"				)
	UpperCAmelCase:					List[str] 						=     0
	for char in bin_string:
		UpperCAmelCase:					Union[str, Any] 						=     2 * decimal_number + int(snake_case_				)
	return -decimal_number if is_negative else decimal_number


if __name__ == "__main__":
	from doctest import testmod

	testmod()
