

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 				lowercase       ( lowercase_    ):




				def 					a							(      self ):
											snake_case_           =					self.config_class(**self.inputs_dict )
											self.parent.assertTrue(hasattr(snake_case   ,     'hidden_sizes' ) )
											self.parent.assertTrue(hasattr(snake_case   ,     'neck_hidden_sizes' ) )
											self.parent.assertTrue(hasattr(snake_case   ,     'num_attention_heads' ) )







class 				lowercase       :




				def __init__(      self   ,     snake_case   ,     snake_case=13   ,     snake_case=32   ,     snake_case=2   ,     snake_case=3   ,     snake_case=640   ,     snake_case=4   ,     snake_case="silu"   ,     snake_case=3   ,     snake_case=32   ,     snake_case=0.1   ,     snake_case=0.1   ,     snake_case=0.1   ,     snake_case=0.02   ,     snake_case=True   ,     snake_case=True   ,     snake_case=10   ,     snake_case=None   ,     ):
											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 					a							(      self ):
											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 					a							(      self ):
											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   ,     snake_case   ,     snake_case   ,     snake_case   ,     snake_case ):
											snake_case_           =					MobileViTModel(config=snake_case )
											model.to(snake_case )
											model.eval()
											snake_case_           =					model(snake_case )
											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   ,     snake_case   ,     snake_case   ,     snake_case   ,     snake_case ):
											snake_case_           =					self.num_labels
											snake_case_           =					MobileViTForImageClassification(snake_case )
											model.to(snake_case )
											model.eval()
											snake_case_           =					model(snake_case   ,     labels=snake_case )
											self.parent.assertEqual(result.logits.shape   ,     (self.batch_size, self.num_labels) )




				def 					a							(      self   ,     snake_case   ,     snake_case   ,     snake_case   ,     snake_case ):
											snake_case_           =					self.num_labels
											snake_case_           =					MobileViTForSemanticSegmentation(snake_case )
											model.to(snake_case )
											model.eval()
											snake_case_           =					model(snake_case )
											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(snake_case   ,     labels=snake_case )
											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 ):
											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 				lowercase       ( lowercase_			,						lowercase_			,						unittest.TestCase    ):
				__SCREAMING_SNAKE_CASE      :				Dict     =    (
				    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				__SCREAMING_SNAKE_CASE      :				Tuple     =    (
				    {
				        '''feature-extraction''': MobileViTModel,
				        '''image-classification''': MobileViTForImageClassification,
				        '''image-segmentation''': MobileViTForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				__SCREAMING_SNAKE_CASE      :				int     =    False
				__SCREAMING_SNAKE_CASE      :				Any     =    False
				__SCREAMING_SNAKE_CASE      :				Tuple     =    False
				__SCREAMING_SNAKE_CASE      :				Tuple     =    False




				def 					a							(      self ):
											snake_case_           =					MobileViTModelTester(self )
											snake_case_           =					MobileViTConfigTester(self   ,     config_class=snake_case   ,     has_text_modality=snake_case )




				def 					a							(      self ):
											self.config_tester.run_common_tests()




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




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




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




				def 					a							(      self ):
											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(snake_case )
																		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]   ,     snake_case )




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




				def 					a							(      self ):
											snake_case_           =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case )




				def 					a							(      self ):
											def check_hidden_states_output(snake_case   ,     snake_case   ,     snake_case ):
																		snake_case_           =					model_class(snake_case )
																		model.to(snake_case )
																		model.eval()

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

																		snake_case_           =					outputs.hidden_states

																		snake_case_           =					5
																		self.assertEqual(len(snake_case )   ,     snake_case )

																		# 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(snake_case ) ):
																									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(snake_case   ,     snake_case   ,     snake_case )

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

																		check_hidden_states_output(snake_case   ,     snake_case   ,     snake_case )




				def 					a							(      self ):
											snake_case_           =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*snake_case )




				def 					a							(      self ):
											snake_case_           =					self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*snake_case )




				@slow
				def 					a							(      self ):
											for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		snake_case_           =					MobileViTModel.from_pretrained(snake_case )
																		self.assertIsNotNone(snake_case )





def       __lowerCamelCase			(				):







							'''simple docstring'''






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







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




				@cached_property
				def 					a							(      self ):
											return MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small' ) if is_vision_available() else None




				@slow
				def 					a							(      self ):
											snake_case_           =					MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small' ).to(snake_case )

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

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

											# verify the logits
											snake_case_           =					torch.Size((1, 1000) )
											self.assertEqual(outputs.logits.shape   ,     snake_case )

											snake_case_           =					torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(snake_case )

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




				@slow
				def 					a							(      self ):
											snake_case_           =					MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
											snake_case_           =					model.to(snake_case )

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

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

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

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

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

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




				@slow
				def 					a							(      self ):
											snake_case_           =					MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small' )
											snake_case_           =					model.to(snake_case )

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

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

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

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

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

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







import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING


_UpperCAmelCase	:     Dict		       = logging.get_logger(__name__)







class 				lowercase       ( lowercase_    ):
				__SCREAMING_SNAKE_CASE      :				Any     =    '''upernet'''




				def __init__(      self   ,     snake_case=None   ,     snake_case=512   ,     snake_case=0.02   ,     snake_case=[1, 2, 3, 6]   ,     snake_case=True   ,     snake_case=0.4   ,     snake_case=384   ,     snake_case=256   ,     snake_case=1   ,     snake_case=False   ,     snake_case=255   ,     **snake_case   ,     ):
											super().__init__(**snake_case )

											if backbone_config is None:
																		logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' )
																		snake_case_           =					CONFIG_MAPPING['resnet'](out_features=['stage1', 'stage2', 'stage3', 'stage4'] )
											elif isinstance(snake_case   ,     snake_case ):
																		snake_case_           =					backbone_config.get('model_type' )
																		snake_case_           =					CONFIG_MAPPING[backbone_model_type]
																		snake_case_           =					config_class.from_dict(snake_case )

											snake_case_           =					backbone_config
											snake_case_           =					hidden_size
											snake_case_           =					initializer_range
											snake_case_           =					pool_scales
											snake_case_           =					use_auxiliary_head
											snake_case_           =					auxiliary_loss_weight
											snake_case_           =					auxiliary_in_channels
											snake_case_           =					auxiliary_channels
											snake_case_           =					auxiliary_num_convs
											snake_case_           =					auxiliary_concat_input
											snake_case_           =					loss_ignore_index




				def 					a							(      self ):
											snake_case_           =					copy.deepcopy(self.__dict__ )
											snake_case_           =					self.backbone_config.to_dict()
											snake_case_           =					self.__class__.model_type
											return output




