



'''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 		lowerCamelCase__   (    A  ):




					'''simple docstring'''



					def     __UpperCAmelCase  (	self					:						List[Any]       )	->							List[str]:



						'''simple docstring'''





						_lowercase       :							Optional[int]  	=		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 		lowerCamelCase__   :




					'''simple docstring'''



					def __init__(	self					:						Union[str, Any]  ,	UpperCamelCase_					:						Dict  ,	UpperCamelCase_					:						Tuple=13  ,	UpperCamelCase_					:						Tuple=32  ,	UpperCamelCase_					:						Dict=2  ,	UpperCamelCase_					:						int=3  ,	UpperCamelCase_					:						Optional[int]=640  ,	UpperCamelCase_					:						Optional[int]=4  ,	UpperCamelCase_					:						Dict="silu"  ,	UpperCamelCase_					:						List[str]=3  ,	UpperCamelCase_					:						int=32  ,	UpperCamelCase_					:						int=0.1  ,	UpperCamelCase_					:						int=0.1  ,	UpperCamelCase_					:						Union[str, Any]=0.1  ,	UpperCamelCase_					:						List[str]=0.02  ,	UpperCamelCase_					:						Any=True  ,	UpperCamelCase_					:						int=True  ,	UpperCamelCase_					:						Dict=10  ,	UpperCamelCase_					:						Tuple=None  ,	)	->							int:



						'''simple docstring'''





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




					def     __UpperCAmelCase  (	self					:						Optional[int]       )	->							Union[str, Any]:



						'''simple docstring'''





						_lowercase       :							Union[str, Any]  	=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

						_lowercase       :							str  	=		self.get_config()

						return config, pixel_values, labels, pixel_labels




					def     __UpperCAmelCase  (	self					:						int       )	->							int:



						'''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					:						Dict  ,	UpperCamelCase_					:						Dict  ,	UpperCamelCase_					:						Dict  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Tuple       )	->							List[str]:



						'''simple docstring'''





						_lowercase       :							List[Any]  	=		TFMobileViTModel(config=UpperCamelCase_       )
						_lowercase       :							Optional[int]  	=		model(UpperCamelCase_  ,	training=UpperCamelCase_       )
						_lowercase       :							List[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     __UpperCAmelCase  (	self					:						Dict  ,	UpperCamelCase_					:						Dict  ,	UpperCamelCase_					:						int  ,	UpperCamelCase_					:						Optional[int]  ,	UpperCamelCase_					:						List[Any]       )	->							str:



						'''simple docstring'''





						_lowercase       :							Tuple  	=		self.num_labels
						_lowercase       :							Optional[Any]  	=		TFMobileViTForImageClassification(UpperCamelCase_       )
						_lowercase       :							int  	=		model(UpperCamelCase_  ,	labels=UpperCamelCase_  ,	training=UpperCamelCase_       )
						self.parent.assertEqual(result.logits.shape  ,	(self.batch_size, self.num_labels)       )




					def     __UpperCAmelCase  (	self					:						Dict  ,	UpperCamelCase_					:						Tuple  ,	UpperCamelCase_					:						str  ,	UpperCamelCase_					:						Dict  ,	UpperCamelCase_					:						Optional[Any]       )	->							Optional[Any]:



						'''simple docstring'''





						_lowercase       :							str  	=		self.num_labels
						_lowercase       :							str  	=		TFMobileViTForSemanticSegmentation(UpperCamelCase_       )
						_lowercase       :							Dict  	=		self.image_size // self.output_stride

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

						_lowercase       :							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					:						List[str]       )	->							Optional[int]:



						'''simple docstring'''





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






@require_tf
class 		lowerCamelCase__   (    A						, A						, unittest.TestCase  ):




					'''simple docstring'''



					A_         =    (
					    (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
					    if is_tf_available()
					    else ()
					)
					A_         =    (
					    {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
					    if is_tf_available()
					    else {}
					)

					A_         =    False
					A_         =    False
					A_         =    False
					A_         =    False
					A_         =    False




					def     __UpperCAmelCase  (	self					:						Dict       )	->							str:



						'''simple docstring'''





						_lowercase       :							List[Any]  	=		TFMobileViTModelTester(self       )
						_lowercase       :							Optional[int]  	=		TFMobileViTConfigTester(self  ,	config_class=UpperCamelCase_  ,	has_text_modality=UpperCamelCase_       )




					def     __UpperCAmelCase  (	self					:						Optional[Any]       )	->							Optional[int]:



						'''simple docstring'''





						self.config_tester.run_common_tests()




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



						'''simple docstring'''





						pass




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



						'''simple docstring'''





						pass




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



						'''simple docstring'''





						pass




					def     __UpperCAmelCase  (	self					:						Dict       )	->							Dict:



						'''simple docstring'''





						_lowercase	,     _lowercase       :							Any  	=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							_lowercase       :							Dict  	=		model_class(UpperCamelCase_       )
							_lowercase       :							Tuple  	=		inspect.signature(model.call       )
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							_lowercase       :							Optional[int]  	=		[*signature.parameters.keys()]

							_lowercase       :							int  	=		['pixel_values']
							self.assertListEqual(arg_names[:1]  ,	UpperCamelCase_       )




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



						'''simple docstring'''





						_lowercase       :							str  	=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase_       )




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



						'''simple docstring'''





						def check_hidden_states_output(UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Optional[Any]  ,	UpperCamelCase_					:						Union[str, Any]       ):
							_lowercase       :							Optional[Any]  	=		model_class(UpperCamelCase_       )

							_lowercase       :							Optional[int]  	=		model(**self._prepare_for_class(UpperCamelCase_  ,	UpperCamelCase_       )       )

							_lowercase       :							Optional[Any]  	=		outputs.hidden_states

							_lowercase       :							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.
							_lowercase       :							List[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       )

						_lowercase	,     _lowercase       :							Optional[Any]  	=		self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							_lowercase       :							Optional[int]  	=		True
							check_hidden_states_output(UpperCamelCase_  ,	UpperCamelCase_  ,	UpperCamelCase_       )

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

							check_hidden_states_output(UpperCamelCase_  ,	UpperCamelCase_  ,	UpperCamelCase_       )




					def     __UpperCAmelCase  (	self					:						Dict       )	->							List[str]:



						'''simple docstring'''





						_lowercase       :							Optional[Any]  	=		self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCamelCase_       )




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



						'''simple docstring'''





						_lowercase       :							Any  	=		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					:						Any       )	->							int:



						'''simple docstring'''





						super().test_dataset_conversion()




					def     __UpperCAmelCase  (	self					:						List[str]  ,	UpperCamelCase_					:						List[Any]  ,	UpperCamelCase_					:						str  ,	UpperCamelCase_					:						int=2E-1  ,	UpperCamelCase_					:						Optional[int]=2E-1       )	->							Optional[int]:



						'''simple docstring'''





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



						'''simple docstring'''





						_lowercase	,     _lowercase       :							Tuple  	=		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":
								_lowercase       :							Dict  	=		model_class(UpperCamelCase_       )
								if getattr(UpperCamelCase_  ,	'hf_compute_loss'  ,	UpperCamelCase_       ):
									super().test_keras_fit()




					def     __UpperCAmelCase  (	self					:						Dict       )	->							Optional[Any]:



						'''simple docstring'''





						_lowercase	,     _lowercase       :							Union[str, 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":
								_lowercase       :							int  	=		5

							_lowercase       :							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
								_lowercase       :							Union[str, Any]  	=		self._prepare_for_class(inputs_dict.copy()  ,	UpperCamelCase_  ,	return_labels=UpperCamelCase_       )
								_lowercase       :							Union[str, Any]  	=		prepared_for_class[
								    sorted(prepared_for_class.keys() - inputs_dict.keys()  ,	reverse=UpperCamelCase_       )[0]
								]
								_lowercase       :							Union[str, Any]  	=		added_label.shape.as_list()[:1]

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

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

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

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

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

								for index, value in sorted_tuple_index_mapping:
									_lowercase       :							Union[str, Any]  	=		prepared_for_class[value]

								_lowercase       :							int  	=		tuple(UpperCamelCase_       )

								# Send to model
								_lowercase       :							List[str]  	=		model(tuple_input[:-1]       )[0]

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




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



						'''simple docstring'''





						for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							_lowercase       :							int  	=		TFMobileViTModel.from_pretrained(UpperCamelCase_       )
							self.assertIsNotNone(UpperCamelCase_       )







def     __UpperCamelCase					(				)			->      int:
	_lowercase       :							Dict  	=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
	return image






@require_tf
class 		lowerCamelCase__   (    unittest.TestCase  ):




					'''simple docstring'''



					@slow
					def     __UpperCAmelCase  (	self					:						str       )	->							Optional[Any]:



						'''simple docstring'''





						_lowercase       :							Optional[int]  	=		TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'       )

						_lowercase       :							Union[str, Any]  	=		MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'       )
						_lowercase       :							List[Any]  	=		prepare_img()
						_lowercase       :							Optional[Any]  	=		image_processor(images=UpperCamelCase_  ,	return_tensors='tf'       )

						# forward pass
						_lowercase       :							List[str]  	=		model(**UpperCamelCase_  ,	training=UpperCamelCase_       )

						# verify the logits
						_lowercase       :							Union[str, Any]  	=		tf.TensorShape((1, 1000)       )
						self.assertEqual(outputs.logits.shape  ,	UpperCamelCase_       )

						_lowercase       :							Tuple  	=		tf.constant([-1.93_64, -1.23_27, -0.46_53]       )

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




					@slow
					def     __UpperCAmelCase  (	self					:						List[Any]       )	->							List[Any]:



						'''simple docstring'''





						_lowercase       :							Tuple  	=		TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'       )

						_lowercase       :							List[str]  	=		MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'       )

						_lowercase       :							Optional[int]  	=		prepare_img()
						_lowercase       :							Optional[int]  	=		image_processor(images=UpperCamelCase_  ,	return_tensors='tf'       )

						# forward pass
						_lowercase       :							Any  	=		model(inputs.pixel_values  ,	training=UpperCamelCase_       )
						_lowercase       :							Union[str, Any]  	=		outputs.logits

						# verify the logits
						_lowercase       :							Dict  	=		tf.TensorShape((1, 21, 32, 32)       )
						self.assertEqual(logits.shape  ,	UpperCamelCase_       )

						_lowercase       :							str  	=		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]  ,	UpperCamelCase_  ,	rtol=1E-4  ,	atol=1E-4       )





'''simple docstring'''

from __future__ import annotations

_A					:     Union[str, Any]      ='''Alexander Joslin'''







def     __UpperCamelCase					(				_lowercase       )			->      int:

	if number <= 0:
		_lowercase       :							Optional[Any]  	=		f'''n must be greater than 0. Got n = {number}'''
		raise ValueError(_lowercase       )

	_lowercase       :							List[str]  	=		[number + 1] * (number + 1)

	# starting position
	_lowercase       :							str  	=		0
	for i in range(1,					_lowercase       ):
		_lowercase       :							Union[str, Any]  	=		min(table[i + 1],					table[i] + 1       )
		# check if out of bounds
		if i * 2 <= number:
			_lowercase       :							Optional[Any]  	=		min(table[i * 2],					table[i] + 1       )
		# check if out of bounds
		if i * 3 <= number:
			_lowercase       :							Any  	=		min(table[i * 3],					table[i] + 1       )
	return table[number]


if __name__ == "__main__":
		import doctest

		doctest.testmod()
