






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



				"""simple docstring"""



				def 					__magic_name__							(      self    :    Union[str, Any]):






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



				"""simple docstring"""



				def __init__(      self    :    Tuple			,		UpperCamelCase__    :    Optional[int]			,		UpperCamelCase__    :    Tuple=1_3			,		UpperCamelCase__    :    Any=3_2			,		UpperCamelCase__    :    str=2			,		UpperCamelCase__    :    Optional[Any]=3			,		UpperCamelCase__    :    Union[str, Any]=6_4_0			,		UpperCamelCase__    :    Optional[Any]=4			,		UpperCamelCase__    :    Optional[int]="silu"			,		UpperCamelCase__    :    Optional[int]=3			,		UpperCamelCase__    :    str=3_2			,		UpperCamelCase__    :    Optional[Any]=0.1			,		UpperCamelCase__    :    List[str]=0.1			,		UpperCamelCase__    :    List[str]=0.1			,		UpperCamelCase__    :    Union[str, Any]=0.02			,		UpperCamelCase__    :    int=True			,		UpperCamelCase__    :    Union[str, Any]=True			,		UpperCamelCase__    :    str=1_0			,		UpperCamelCase__    :    List[str]=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 					__magic_name__							(      self    :    int):






											'''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 					__magic_name__							(      self    :    Union[str, Any]):






											'''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 					__magic_name__							(      self    :    str			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Tuple			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    Union[str, Any]):






											'''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 					__magic_name__							(      self    :    Dict			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    List[Any]			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    int):






											'''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 					__magic_name__							(      self    :    Optional[Any]			,		UpperCamelCase__    :    Dict			,		UpperCamelCase__    :    List[str]			,		UpperCamelCase__    :    Optional[Any]			,		UpperCamelCase__    :    List[str]):






											'''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 					__magic_name__							(      self    :    Optional[int]):






											'''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    _lowerCAmelCase			(		lowercase_     ,      lowercase_     ,      unittest.TestCase      ):



				"""simple docstring"""



				_lowercase				:   Optional[int]      =  (
				    (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				_lowercase				:   List[str]      =  (
				    {
				        '''feature-extraction''': MobileViTModel,
				        '''image-classification''': MobileViTForImageClassification,
				        '''image-segmentation''': MobileViTForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				_lowercase				:   int      =  False
				_lowercase				:   int      =  False
				_lowercase				:   Optional[int]      =  False
				_lowercase				:   List[str]      =  False



				def 					__magic_name__							(      self    :    List[Any]):






											'''simple docstring'''







											snake_case__	  =       MobileViTModelTester(self)
											snake_case__	  =       MobileViTConfigTester(self			,		config_class=UpperCamelCase__			,		has_text_modality=UpperCamelCase__)



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											self.config_tester.run_common_tests()



				@unittest.skip(reason="""MobileViT does not use inputs_embeds""")
				def 					__magic_name__							(      self    :    Any):






											'''simple docstring'''







											pass



				@unittest.skip(reason="""MobileViT does not support input and output embeddings""")
				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											pass



				@unittest.skip(reason="""MobileViT does not output attentions""")
				def 					__magic_name__							(      self    :    Optional[Any]):






											'''simple docstring'''







											pass



				def 					__magic_name__							(      self    :    List[Any]):






											'''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 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											pass



				def 					__magic_name__							(      self    :    List[str]):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCamelCase__)



				def 					__magic_name__							(      self    :    Union[str, Any]):






											'''simple docstring'''







											def check_hidden_states_output(UpperCamelCase__    :    int			,		UpperCamelCase__    :    Any			,		UpperCamelCase__    :    Any):
																		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 					__magic_name__							(      self    :    Dict):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__)



				def 					__magic_name__							(      self    :    Tuple):






											'''simple docstring'''







											snake_case__	  =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase__)



				@slow
				def 					__magic_name__							(      self    :    List[Any]):






											'''simple docstring'''







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


def _UpperCAmelCase   (	):
							snake_case__	  =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
							return image



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



				"""simple docstring"""



				@cached_property
				def 					__magic_name__							(      self    :    List[Any]):






											'''simple docstring'''







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



				@slow
				def 					__magic_name__							(      self    :    str):






											'''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, 1_0_0_0))
											self.assertEqual(outputs.logits.shape			,		UpperCamelCase__)

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

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



				@slow
				def 					__magic_name__							(      self    :    List[Any]):






											'''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, 2_1, 3_2, 3_2))
											self.assertEqual(logits.shape			,		UpperCamelCase__)

											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=UpperCamelCase__			,		)

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



				@slow
				def 					__magic_name__							(      self    :    List[str]):






											'''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=[(5_0, 6_0)])
											snake_case__	  =       torch.Size((5_0, 6_0))
											self.assertEqual(segmentation[0].shape			,		UpperCamelCase__)

											snake_case__	  =       image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase__)
											snake_case__	  =       torch.Size((3_2, 3_2))
											self.assertEqual(segmentation[0].shape			,		UpperCamelCase__)








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


a__       =     {
    """configuration_lilt""": ["""LILT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """LiltConfig"""],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	a__       =     [
	    """LILT_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """LiltForQuestionAnswering""",
	    """LiltForSequenceClassification""",
	    """LiltForTokenClassification""",
	    """LiltModel""",
	    """LiltPreTrainedModel""",
	]

if TYPE_CHECKING:
	from .configuration_lilt import LILT_PRETRAINED_CONFIG_ARCHIVE_MAP, LiltConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_lilt import (
		    LILT_PRETRAINED_MODEL_ARCHIVE_LIST,
		    LiltForQuestionAnswering,
		    LiltForSequenceClassification,
		    LiltForTokenClassification,
		    LiltModel,
		    LiltPreTrainedModel,
		)

else:
	import sys

	a__       =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
