



"""simple docstring"""




import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
			from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import MobileViTImageProcessor

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def 	_A     (   self		):







													'''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        UpperCAmelCase_  :

						'''simple docstring'''




						def __init__(   self				,							_A				,							_A=13				,							_A=32				,							_A=2				,							_A=3				,							_A=640				,							_A=4				,							_A="silu"				,							_A=3				,							_A=32				,							_A=0.1				,							_A=0.1				,							_A=0.1				,							_A=0.0_2				,							_A=True				,							_A=True				,							_A=10				,							_A=None				,							):







													'''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 	_A     (   self		):







													'''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 	_A     (   self		):







													'''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 	_A     (   self				,							_A				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= MobileViTModel(config=_A		)
													model.to(_A		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= model(_A		)
													self.parent.assertEqual(
													    result.last_hidden_state.shape				,							(
													        self.batch_size,
													        self.last_hidden_size,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)






						def 	_A     (   self				,							_A				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.num_labels
													__SCREAMING_SNAKE_CASE									= MobileViTForImageClassification(_A		)
													model.to(_A		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= model(_A				,							labels=_A		)
													self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.num_labels)		)






						def 	_A     (   self				,							_A				,							_A				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.num_labels
													__SCREAMING_SNAKE_CASE									= MobileViTForSemanticSegmentation(_A		)
													model.to(_A		)
													model.eval()
													__SCREAMING_SNAKE_CASE									= model(_A		)
													self.parent.assertEqual(
													    result.logits.shape				,							(
													        self.batch_size,
													        self.num_labels,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)
													__SCREAMING_SNAKE_CASE									= model(_A				,							labels=_A		)
													self.parent.assertEqual(
													    result.logits.shape				,							(
													        self.batch_size,
													        self.num_labels,
													        self.image_size // self.output_stride,
													        self.image_size // self.output_stride,
													    )				,							)






						def 	_A     (   self		):







													'''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_torch
class        UpperCAmelCase_  (       UpperCamelCase_   ,   UpperCamelCase_   ,   unittest.TestCase	):

						'''simple docstring'''




						UpperCamelCase__      :			List[Any]      =  (
						    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						UpperCamelCase__      :			List[Any]      =  (
						    {
						        '''feature-extraction''': MobileViTModel,
						        '''image-classification''': MobileViTForImageClassification,
						        '''image-segmentation''': MobileViTForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						UpperCamelCase__      :			Any      =  False
						UpperCamelCase__      :			str      =  False
						UpperCamelCase__      :			Tuple      =  False
						UpperCamelCase__      :			Optional[int]      =  False






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= MobileViTModelTester(self		)
													__SCREAMING_SNAKE_CASE									= MobileViTConfigTester(self				,							config_class=_A				,							has_text_modality=_A		)






						def 	_A     (   self		):







													'''simple docstring'''

													self.config_tester.run_common_tests()






						@unittest.skip(reason='MobileViT does not use inputs_embeds'		)
						def 	_A     (   self		):







													'''simple docstring'''

													pass






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







													'''simple docstring'''

													pass






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







													'''simple docstring'''

													pass






						def 	_A     (   self		):







													'''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.forward		)
																				# 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		)






						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'		)
						def 	_A     (   self		):







													'''simple docstring'''

													pass






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_A		)






						def 	_A     (   self		):







													'''simple docstring'''

													def check_hidden_states_output(_A				,							_A				,							_A		):
																				__SCREAMING_SNAKE_CASE									= model_class(_A		)
																				model.to(_A		)
																				model.eval()

																				with torch.no_grad():
																											__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 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_A		)






						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*_A		)






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				__SCREAMING_SNAKE_CASE									= MobileViTModel.from_pretrained(_A		)
																				self.assertIsNotNone(_A		)







def      __lowercase       (			)    ->			Any:
							__SCREAMING_SNAKE_CASE									= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
							return image

@require_torch
@require_vision
class        UpperCAmelCase_  (       unittest.TestCase	):

						'''simple docstring'''




						@cached_property
						def 	_A     (   self		):







													'''simple docstring'''

													return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'		) if is_vision_available() else None






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'		).to(_A		)

													__SCREAMING_SNAKE_CASE									= self.default_image_processor
													__SCREAMING_SNAKE_CASE									= prepare_img()
													__SCREAMING_SNAKE_CASE									= image_processor(images=_A				,							return_tensors='pt'		).to(_A		)

													# forward pass
													with torch.no_grad():
																				__SCREAMING_SNAKE_CASE									= model(**_A		)

													# verify the logits
													__SCREAMING_SNAKE_CASE									= torch.Size((1, 1_000)		)
													self.assertEqual(outputs.logits.shape				,							_A		)

													__SCREAMING_SNAKE_CASE									= torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]		).to(_A		)

													self.assertTrue(torch.allclose(outputs.logits[0, :3]				,							_A				,							atol=1e-4		)		)






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
													__SCREAMING_SNAKE_CASE									= model.to(_A		)

													__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='pt'		).to(_A		)

													# forward pass
													with torch.no_grad():
																				__SCREAMING_SNAKE_CASE									= model(**_A		)
													__SCREAMING_SNAKE_CASE									= outputs.logits

													# verify the logits
													__SCREAMING_SNAKE_CASE									= torch.Size((1, 21, 32, 32)		)
													self.assertEqual(logits.shape				,							_A		)

													__SCREAMING_SNAKE_CASE									= torch.tensor(
													    [
													        [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
													        [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_8_6_8, -9.7_1_3_2], [-11.0_405, -11.0_221, -10.7_318]],
													        [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
													    ]				,							device=_A				,							)

													self.assertTrue(torch.allclose(logits[0, :3, :3, :3]				,							_A				,							atol=1e-4		)		)






						@slow
						def 	_A     (   self		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'		)
													__SCREAMING_SNAKE_CASE									= model.to(_A		)

													__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='pt'		).to(_A		)

													# forward pass
													with torch.no_grad():
																				__SCREAMING_SNAKE_CASE									= model(**_A		)

													__SCREAMING_SNAKE_CASE									= outputs.logits.detach().cpu()

													__SCREAMING_SNAKE_CASE									= image_processor.post_process_semantic_segmentation(outputs=_A				,							target_sizes=[(50, 60)]		)
													__SCREAMING_SNAKE_CASE									= torch.Size((50, 60)		)
													self.assertEqual(segmentation[0].shape				,							_A		)

													__SCREAMING_SNAKE_CASE									= image_processor.post_process_semantic_segmentation(outputs=_A		)
													__SCREAMING_SNAKE_CASE									= torch.Size((32, 32)		)
													self.assertEqual(segmentation[0].shape				,							_A		)











from collections import deque

from .hash_table import HashTable

class        UpperCAmelCase_  (       UpperCamelCase_	):

						'''simple docstring'''




						def __init__(   self				,							*_A				,							**_A		):







													'''simple docstring'''

													super().__init__(*_A				,							**_A		)






						def 	_A     (   self				,							_A				,							_A		):







													'''simple docstring'''

													__SCREAMING_SNAKE_CASE									= deque([]		) if self.values[key] is None else self.values[key]
													self.values[key].appendleft(_A		)
													__SCREAMING_SNAKE_CASE									= self.values[key]






						def 	_A     (   self		):







													'''simple docstring'''

													return (
													    sum(self.charge_factor - len(_A		) for slot in self.values		)
													    / self.size_table
													    * self.charge_factor
													)






						def 	_A     (   self				,							_A				,							_A=None		):







													'''simple docstring'''

													if not (
													    len(self.values[key]		) == self.charge_factor and self.values.count(_A		) == 0
													):
																				return key
													return super()._collision_resolution(_A				,							_A		)






