

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available


A											=     {'configuration_yolos': ['YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'YolosConfig', 'YolosOnnxConfig']}

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		A											=     ['YolosFeatureExtractor']
		A											=     ['YolosImageProcessor']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		A											=     [
		    'YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'YolosForObjectDetection',
		    'YolosModel',
		    'YolosPreTrainedModel',
		]


if TYPE_CHECKING:
		from .configuration_yolos import YOLOS_PRETRAINED_CONFIG_ARCHIVE_MAP, YolosConfig, YolosOnnxConfig

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_yolos import YolosFeatureExtractor
				from .image_processing_yolos import YolosImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_yolos import (
				    YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST,
				    YolosForObjectDetection,
				    YolosModel,
				    YolosPreTrainedModel,
				)


else:
		import sys

		A											=     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



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






			"""simple docstring"""




			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= 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 SCREAMING_SNAKE_CASE  :






			"""simple docstring"""




			def __init__(    self ,				__UpperCamelCase ,				__UpperCamelCase=13 ,				__UpperCamelCase=32 ,				__UpperCamelCase=2 ,				__UpperCamelCase=3 ,				__UpperCamelCase=6_40 ,				__UpperCamelCase=4 ,				__UpperCamelCase="silu" ,				__UpperCamelCase=3 ,				__UpperCamelCase=32 ,				__UpperCamelCase=0.1 ,				__UpperCamelCase=0.1 ,				__UpperCamelCase=0.1 ,				__UpperCamelCase=0.02 ,				__UpperCamelCase=True ,				__UpperCamelCase=True ,				__UpperCamelCase=10 ,				__UpperCamelCase=None ,				):

				"""simple docstring"""


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


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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

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

				snake_case_      		= self.get_config()

				return config, pixel_values, labels, pixel_labels


			def 			__lowerCAmelCase (    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 			__lowerCAmelCase (    self ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							):

				"""simple docstring"""


				snake_case_      		= MobileViTModel(config=__UpperCamelCase							)
				model.to(__UpperCamelCase							)
				model.eval()
				snake_case_      		= model(__UpperCamelCase							)
				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 			__lowerCAmelCase (    self ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							):

				"""simple docstring"""


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


			def 			__lowerCAmelCase (    self ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							):

				"""simple docstring"""


				snake_case_      		= self.num_labels
				snake_case_      		= MobileViTForSemanticSegmentation(__UpperCamelCase							)
				model.to(__UpperCamelCase							)
				model.eval()
				snake_case_      		= model(__UpperCamelCase							)
				self.parent.assertEqual(
				    result.logits.shape ,				(
				        self.batch_size,
				        self.num_labels,
				        self.image_size // self.output_stride,
				        self.image_size // self.output_stride,
				    ) ,				)
				snake_case_      		= model(__UpperCamelCase ,				labels=__UpperCamelCase							)
				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 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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







@require_torch
class SCREAMING_SNAKE_CASE  (		__snake_case							,						__snake_case							,						unittest.TestCase							):






			"""simple docstring"""




			__A						  =  (
			    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			__A						  =  (
			    {
			        """feature-extraction""": MobileViTModel,
			        """image-classification""": MobileViTForImageClassification,
			        """image-segmentation""": MobileViTForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			__A						  =  False
			__A						  =  False
			__A						  =  False
			__A						  =  False


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= MobileViTModelTester(self							)
				snake_case_      		= MobileViTConfigTester(self ,				config_class=__UpperCamelCase ,				has_text_modality=__UpperCamelCase							)


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				self.config_tester.run_common_tests()


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

				"""simple docstring"""


				pass


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

				"""simple docstring"""


				pass


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

				"""simple docstring"""


				pass


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_		,       snake_case_      		= self.model_tester.prepare_config_and_inputs_for_common()

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

					snake_case_      		= ['pixel_values']
					self.assertListEqual(arg_names[:1] ,				__UpperCamelCase							)


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

				"""simple docstring"""


				pass


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__UpperCamelCase							)


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				def check_hidden_states_output(__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							):
					snake_case_      		= model_class(__UpperCamelCase							)
					model.to(__UpperCamelCase							)
					model.eval()

					with torch.no_grad():
						snake_case_      		= model(**self._prepare_for_class(__UpperCamelCase ,				__UpperCamelCase							)							)

					snake_case_      		= outputs.hidden_states

					snake_case_      		= 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.
					snake_case_      		= 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							)

				snake_case_		,       snake_case_      		= self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					snake_case_      		= True
					check_hidden_states_output(__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							)

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

					check_hidden_states_output(__UpperCamelCase ,				__UpperCamelCase ,				__UpperCamelCase							)


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase							)


			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCamelCase							)







			@slow
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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







def a():





	'''simple docstring'''
	snake_case_      		= Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
	return image






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






			"""simple docstring"""




			@cached_property
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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


			@slow
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


				snake_case_      		= MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'							).to(__UpperCamelCase							)

				snake_case_      		= self.default_image_processor
				snake_case_      		= prepare_img()
				snake_case_      		= image_processor(images=__UpperCamelCase ,				return_tensors='pt'							).to(__UpperCamelCase							)

				# forward pass
				with torch.no_grad():
					snake_case_      		= model(**__UpperCamelCase							)

				# verify the logits
				snake_case_      		= torch.Size((1, 10_00)							)
				self.assertEqual(outputs.logits.shape ,				__UpperCamelCase							)

				snake_case_      		= torch.tensor([-1.9364, -1.2327, -0.4653]							).to(__UpperCamelCase							)

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


			@slow
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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

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

				snake_case_      		= prepare_img()
				snake_case_      		= image_processor(images=__UpperCamelCase ,				return_tensors='pt'							).to(__UpperCamelCase							)

				# forward pass
				with torch.no_grad():
					snake_case_      		= model(**__UpperCamelCase							)
				snake_case_      		= outputs.logits

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

				snake_case_      		= torch.tensor(
				    [
				        [[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]],
				    ] ,				device=__UpperCamelCase ,				)

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







			@slow
			def 			__lowerCAmelCase (    self							):

				"""simple docstring"""


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

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

				snake_case_      		= prepare_img()
				snake_case_      		= image_processor(images=__UpperCamelCase ,				return_tensors='pt'							).to(__UpperCamelCase							)

				# forward pass
				with torch.no_grad():
					snake_case_      		= model(**__UpperCamelCase							)

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

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

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