


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   A__							(						UpperCamelCase__					):




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


										"""simple docstring"""





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

class   A__							:




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


										"""simple docstring"""





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




						def 							__UpperCamelCase			(    self   : Any					)							->       int:


										"""simple docstring"""





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

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

										_SCREAMING_SNAKE_CASE     					=self.get_config()

										return config, pixel_values, labels, pixel_labels




						def 							__UpperCamelCase			(    self   : List[str]					)							->       List[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   : Dict			,      _a   : str			,      _a   : Dict			,      _a   : Any			,      _a   : Optional[int]					)							->       Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=TFMobileViTModel(config=_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a			,      training=_a					)
										_SCREAMING_SNAKE_CASE     					=_SCREAMING_SNAKE_CASE     					=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   : Tuple			,      _a   : Union[str, Any]			,      _a   : Optional[int]			,      _a   : List[Any]			,      _a   : Dict					)							->       str:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.num_labels
										_SCREAMING_SNAKE_CASE     					=TFMobileViTForImageClassification(_a					)
										_SCREAMING_SNAKE_CASE     					=model(_a			,      labels=_a			,      training=_a					)
										self.parent.assertEqual(result.logits.shape			,      (self.batch_size, self.num_labels)					)




						def 							__UpperCamelCase			(    self   : Any			,      _a   : List[str]			,      _a   : List[str]			,      _a   : Union[str, Any]			,      _a   : Any					)							->       Dict:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.num_labels
										_SCREAMING_SNAKE_CASE     					=TFMobileViTForSemanticSegmentation(_a					)
										_SCREAMING_SNAKE_CASE     					=_SCREAMING_SNAKE_CASE     					=self.image_size // self.output_stride

										_SCREAMING_SNAKE_CASE     					=model(_a			,      training=_a					)
										self.parent.assertEqual(
										    result.logits.shape			,      (self.batch_size, self.num_labels, expected_height, expected_width)					)

										_SCREAMING_SNAKE_CASE     					=model(_a			,      labels=_a			,      training=_a					)
										self.parent.assertEqual(
										    result.logits.shape			,      (self.batch_size, self.num_labels, expected_height, expected_width)					)




						def 							__UpperCamelCase			(    self   : str					)							->       str:


										"""simple docstring"""





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

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

						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False
						UpperCAmelCase     =  False




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=TFMobileViTModelTester(self					)
										_SCREAMING_SNAKE_CASE     					=TFMobileViTConfigTester(self			,      config_class=_a			,      has_text_modality=_a					)




						def 							__UpperCamelCase			(    self   : Dict					)							->       Dict:


										"""simple docstring"""





										self.config_tester.run_common_tests()




						@unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Any:


										"""simple docstring"""





										pass




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


										"""simple docstring"""





										pass




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


										"""simple docstring"""





										pass




						def 							__UpperCamelCase			(    self   : int					)							->       Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

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

														_SCREAMING_SNAKE_CASE     					=['''pixel_values''']
														self.assertListEqual(arg_names[:1]			,      _a					)




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*_a					)




						def 							__UpperCamelCase			(    self   : List[str]					)							->       Optional[int]:


										"""simple docstring"""





										def check_hidden_states_output(_a   : Dict			,      _a   : int			,      _a   : Optional[int]					):
														_SCREAMING_SNAKE_CASE     					=model_class(_a					)

														_SCREAMING_SNAKE_CASE     					=model(**self._prepare_for_class(_a			,      _a					)					)

														_SCREAMING_SNAKE_CASE     					=outputs.hidden_states

														_SCREAMING_SNAKE_CASE     					=5
														self.assertEqual(len(_a					)			,      _a					)

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

										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
														_SCREAMING_SNAKE_CASE     					=True
														check_hidden_states_output(_a			,      _a			,      _a					)

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

														check_hidden_states_output(_a			,      _a			,      _a					)




						def 							__UpperCamelCase			(    self   : int					)							->       int:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*_a					)




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_semantic_segmentation(*_a					)




						@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					)							->       List[str]:


										"""simple docstring"""





										super().test_dataset_conversion()




						def 							__UpperCamelCase			(    self   : Optional[int]			,      _a   : str			,      _a   : Any			,      _a   : Optional[Any]=2E-1			,      _a   : Optional[int]=2E-1					)							->       Tuple:


										"""simple docstring"""





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




						@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   : Union[str, Any]					)							->       List[str]:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE					,			_SCREAMING_SNAKE_CASE     					=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":
																		_SCREAMING_SNAKE_CASE     					=model_class(_a					)
																		if getattr(_a			,      '''hf_compute_loss'''			,      _a					):
																						super().test_keras_fit()




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


										"""simple docstring"""





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

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

																		# Test that model correctly compute the loss with kwargs
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(inputs_dict.copy()			,      _a			,      return_labels=_a					)
																		_SCREAMING_SNAKE_CASE     					={'''input_ids''', '''pixel_values''', '''input_features'''}
																		_SCREAMING_SNAKE_CASE     					=possible_input_names.intersection(set(_a					)					).pop()
																		_SCREAMING_SNAKE_CASE     					=prepared_for_class.pop(_a					)

																		_SCREAMING_SNAKE_CASE     					=model(_a			,      **_a					)[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
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(inputs_dict.copy()			,      _a			,      return_labels=_a					)
																		_SCREAMING_SNAKE_CASE     					={'''input_ids''', '''pixel_values''', '''input_features'''}
																		_SCREAMING_SNAKE_CASE     					=possible_input_names.intersection(set(_a					)					).pop()
																		_SCREAMING_SNAKE_CASE     					=prepared_for_class.pop(_a					)
																		if "labels" in prepared_for_class:
																						_SCREAMING_SNAKE_CASE     					=prepared_for_class['''labels'''].numpy()
																						if len(labels.shape					) > 1 and labels.shape[1] != 1:
																										# labels[0] = -100
																										_SCREAMING_SNAKE_CASE     					=tf.convert_to_tensor(_a					)
																										_SCREAMING_SNAKE_CASE     					=model(_a			,      **_a					)[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
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(inputs_dict.copy()			,      _a			,      return_labels=_a					)
																		_SCREAMING_SNAKE_CASE     					=model(_a					)[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
																		_SCREAMING_SNAKE_CASE     					=self._prepare_for_class(inputs_dict.copy()			,      _a			,      return_labels=_a					)

																		# Get keys that were added with the _prepare_for_class function
																		_SCREAMING_SNAKE_CASE     					=prepared_for_class.keys() - inputs_dict.keys()
																		_SCREAMING_SNAKE_CASE     					=inspect.signature(model.call					).parameters
																		_SCREAMING_SNAKE_CASE     					=list(signature.keys()					)

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

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

																		for index, value in sorted_tuple_index_mapping:
																						_SCREAMING_SNAKE_CASE     					=prepared_for_class[value]

																		_SCREAMING_SNAKE_CASE     					=tuple(_a					)

																		# Send to model
																		_SCREAMING_SNAKE_CASE     					=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[Any]					)							->       Any:


										"""simple docstring"""





										for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														_SCREAMING_SNAKE_CASE     					=TFMobileViTModel.from_pretrained(_a					)
														self.assertIsNotNone(_a					)







def   lowerCamelCase(				):
				_SCREAMING_SNAKE_CASE     					=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
				return image


@require_tf
class   A__							(						unittest.TestCase					):




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''					)

										_SCREAMING_SNAKE_CASE     					=MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''					)
										_SCREAMING_SNAKE_CASE     					=prepare_img()
										_SCREAMING_SNAKE_CASE     					=image_processor(images=_a			,      return_tensors='''tf'''					)

										# forward pass
										_SCREAMING_SNAKE_CASE     					=model(**_a			,      training=_a					)

										# verify the logits
										_SCREAMING_SNAKE_CASE     					=tf.TensorShape((1, 1000)					)
										self.assertEqual(outputs.logits.shape			,      _a					)

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

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




						@slow
						def 							__UpperCamelCase			(    self   : Union[str, Any]					)							->       Tuple:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

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

										_SCREAMING_SNAKE_CASE     					=prepare_img()
										_SCREAMING_SNAKE_CASE     					=image_processor(images=_a			,      return_tensors='''tf'''					)

										# forward pass
										_SCREAMING_SNAKE_CASE     					=model(inputs.pixel_values			,      training=_a					)
										_SCREAMING_SNAKE_CASE     					=outputs.logits

										# verify the logits
										_SCREAMING_SNAKE_CASE     					=tf.TensorShape((1, 21, 32, 32)					)
										self.assertEqual(logits.shape			,      _a					)

										_SCREAMING_SNAKE_CASE     					=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]			,      _a			,      rtol=1E-4			,      atol=1E-4					)



from __future__ import annotations

from collections.abc import Iterator
from typing import Any

class   A__							:




						def __init__(    self   : List[Any]			,      _a   : Any					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=data
										_SCREAMING_SNAKE_CASE     					=None




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


										"""simple docstring"""





										return f"{self.data}"

class   A__							:




						def __init__(    self   : Optional[Any]					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=None
										_SCREAMING_SNAKE_CASE     					=None




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=self.front
										while node:
														yield node.data
														_SCREAMING_SNAKE_CASE     					=node.next




						def __len__(    self   : List[Any]					)							->       int:


										"""simple docstring"""





										return len(tuple(iter(self					)					)					)




						def __str__(    self   : int					)							->       str:


										"""simple docstring"""





										return " <- ".join(str(_a					) for item in self					)




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


										"""simple docstring"""





										return len(self					) == 0




						def 							__UpperCamelCase			(    self   : int			,      _a   : Any					)							->       None:


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=Node(_a					)
										if self.is_empty():
														_SCREAMING_SNAKE_CASE     					=_SCREAMING_SNAKE_CASE     					=node
										else:
														assert isinstance(self.rear			,      _a					)
														_SCREAMING_SNAKE_CASE     					=node
														_SCREAMING_SNAKE_CASE     					=node




						def 							__UpperCamelCase			(    self   : Dict					)							->       Any:


										"""simple docstring"""





										if self.is_empty():
														raise IndexError('''dequeue from empty queue'''					)
										assert isinstance(self.front			,      _a					)
										_SCREAMING_SNAKE_CASE     					=self.front
										_SCREAMING_SNAKE_CASE     					=self.front.next
										if self.front is None:
														_SCREAMING_SNAKE_CASE     					=None
										return node.data




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


										"""simple docstring"""





										_SCREAMING_SNAKE_CASE     					=_SCREAMING_SNAKE_CASE     					=None


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

							testmod()