




'''simple docstring'''





import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
		from transformers.models.mobilevitva.modeling_mobilevitva import (
		    MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
		    make_divisible,
		)


if is_vision_available():
		from PIL import Image

		from transformers import MobileViTImageProcessor




class  _snake_case		(	lowercase_							):




			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										snake_case_						=      self.config_class(**self.inputs_dict							)
										self.parent.assertTrue(hasattr(a__				,							"width_multiplier"							)							)




class  _snake_case		:




			def __init__(					self				,							a__				,							a__=13				,							a__=64				,							a__=2				,							a__=3				,							a__="swish"				,							a__=3				,							a__=32				,							a__=0.1				,							a__=0.0_2				,							a__=True				,							a__=True				,							a__=10				,							a__=None				,							a__=0.2_5				,							a__=0.0				,							a__=0.0				,							)				->				Dict:

										'''simple docstring'''




										snake_case_						=      parent
										snake_case_						=      batch_size
										snake_case_						=      image_size
										snake_case_						=      patch_size
										snake_case_						=      num_channels
										snake_case_						=      make_divisible(512 * width_multiplier				,							divisor=8							)
										snake_case_						=      hidden_act
										snake_case_						=      conv_kernel_size
										snake_case_						=      output_stride
										snake_case_						=      classifier_dropout_prob
										snake_case_						=      use_labels
										snake_case_						=      is_training
										snake_case_						=      num_labels
										snake_case_						=      initializer_range
										snake_case_						=      scope
										snake_case_						=      width_multiplier
										snake_case_						=      ffn_dropout
										snake_case_						=      attn_dropout




			def    lowerCAmelCase__				(					self							)				->				Optional[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    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




										return MobileViTVaConfig(
										    image_size=self.image_size				,							patch_size=self.patch_size				,							num_channels=self.num_channels				,							hidden_act=self.hidden_act				,							conv_kernel_size=self.conv_kernel_size				,							output_stride=self.output_stride				,							classifier_dropout_prob=self.classifier_dropout_prob				,							initializer_range=self.initializer_range				,							width_multiplier=self.width_multiplier				,							ffn_dropout=self.ffn_dropout_prob				,							attn_dropout=self.attn_dropout_prob				,							)




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__				,							a__							)				->				int:

										'''simple docstring'''




										snake_case_						=      MobileViTVaModel(config=a__							)
										model.to(a__							)
										model.eval()
										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    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__				,							a__							)				->				Union[str, Any]:

										'''simple docstring'''




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




			def    lowerCAmelCase__				(					self				,							a__				,							a__				,							a__				,							a__							)				->				List[str]:

										'''simple docstring'''




										snake_case_						=      self.num_labels
										snake_case_						=      MobileViTVaForSemanticSegmentation(a__							)
										model.to(a__							)
										model.eval()
										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,
										    )				,							)
										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    lowerCAmelCase__				(					self							)				->				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  _snake_case		(	lowercase_						,						lowercase_						,						unittest.TestCase							):
			lowerCAmelCase_     :      int						       =    (
			    (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)

			lowerCAmelCase_     :      Dict						       =    (
			    {
			        "feature-extraction": MobileViTVaModel,
			        "image-classification": MobileViTVaForImageClassification,
			        "image-segmentation": MobileViTVaForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			lowerCAmelCase_     :      Dict						       =    False
			lowerCAmelCase_     :      List[Any]						       =    False
			lowerCAmelCase_     :      List[Any]						       =    False
			lowerCAmelCase_     :      int						       =    False




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

										'''simple docstring'''




										snake_case_						=      MobileViTVaModelTester(self							)
										snake_case_						=      MobileViTVaConfigTester(self				,							config_class=a__				,							has_text_modality=a__							)




			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										self.config_tester.run_common_tests()




			@unittest.skip(reason="MobileViTV2 does not use inputs_embeds"							)
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										pass




			@unittest.skip(reason="MobileViTV2 does not support input and output embeddings"							)
			def    lowerCAmelCase__				(					self							)				->				Optional[Any]:

										'''simple docstring'''




										pass




			@unittest.skip(reason="MobileViTV2 does not output attentions"							)
			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										pass




			@require_torch_multi_gpu
			@unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."							)
			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										pass




			@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."							)
			def    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




										pass




			def    lowerCAmelCase__				(					self							)				->				Union[str, 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(a__							)
																	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]				,							a__							)




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




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




			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




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

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

																	snake_case_						=      outputs.hidden_states

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

																	# MobileViTV2'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(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							)

										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(a__				,							a__				,							a__							)

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

																	check_hidden_states_output(a__				,							a__				,							a__							)




			def    lowerCAmelCase__				(					self							)				->				Any:

										'''simple docstring'''




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




			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




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




			@slow
			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	snake_case_						=      MobileViTVaModel.from_pretrained(a__							)
																	self.assertIsNotNone(a__							)


def      UpperCamelCase_(	):

							'''simple docstring'''






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




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




			@cached_property
			def    lowerCAmelCase__				(					self							)				->				int:

										'''simple docstring'''




										return (
										    MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"							)
										    if is_vision_available()
										    else None
										)




			@slow
			def    lowerCAmelCase__				(					self							)				->				Dict:

										'''simple docstring'''




										snake_case_						=      MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"							).to(
										    a__							)

										snake_case_						=      self.default_image_processor
										snake_case_						=      prepare_img()
										snake_case_						=      image_processor(images=a__				,							return_tensors="pt"							).to(a__							)

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

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

										snake_case_						=      torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]							).to(a__							)

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




			@slow
			def    lowerCAmelCase__				(					self							)				->				List[str]:

										'''simple docstring'''




										snake_case_						=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"							)
										snake_case_						=      model.to(a__							)

										snake_case_						=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"							)

										snake_case_						=      prepare_img()
										snake_case_						=      image_processor(images=a__				,							return_tensors="pt"							).to(a__							)

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

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

										snake_case_						=      torch.tensor(
										    [
										        [[7.0_8_6_3, 7.1_5_2_5, 6.8_2_0_1], [6.6_9_3_1, 6.8_7_7_0, 6.8_9_3_3], [6.2_9_7_8, 7.0_3_6_6, 6.9_6_3_6]],
										        [[-3.7_1_3_4, -3.6_7_1_2, -3.6_6_7_5], [-3.5_8_2_5, -3.3_5_4_9, -3.4_7_7_7], [-3.3_4_3_5, -3.3_9_7_9, -3.2_8_5_7]],
										        [[-2.9_3_2_9, -2.8_0_0_3, -2.7_3_6_9], [-3.0_5_6_4, -2.4_7_8_0, -2.0_2_0_7], [-2.6_8_8_9, -1.9_2_9_8, -1.7_6_4_0]],
										    ]				,							device=a__				,							)

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




			@slow
			def    lowerCAmelCase__				(					self							)				->				str:

										'''simple docstring'''




										snake_case_						=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"							)
										snake_case_						=      model.to(a__							)

										snake_case_						=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"							)

										snake_case_						=      prepare_img()
										snake_case_						=      image_processor(images=a__				,							return_tensors="pt"							).to(a__							)

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

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

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

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







'''simple docstring'''
from typing import TYPE_CHECKING

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


lowerCamelCase :      int					 =     {"configuration_glpn": ["GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP", "GLPNConfig"]}

try:
     if not is_vision_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCamelCase :      int					 =     ["GLPNFeatureExtractor"]
     lowerCamelCase :      Optional[int]					 =     ["GLPNImageProcessor"]

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     lowerCamelCase :      Union[str, Any]					 =     [
         "GLPN_PRETRAINED_MODEL_ARCHIVE_LIST",
         "GLPNForDepthEstimation",
         "GLPNLayer",
         "GLPNModel",
         "GLPNPreTrainedModel",
     ]


if TYPE_CHECKING:
     from .configuration_glpn import GLPN_PRETRAINED_CONFIG_ARCHIVE_MAP, GLPNConfig

     try:
          if not is_vision_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .feature_extraction_glpn import GLPNFeatureExtractor
          from .image_processing_glpn import GLPNImageProcessor

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_glpn import (
              GLPN_PRETRAINED_MODEL_ARCHIVE_LIST,
              GLPNForDepthEstimation,
              GLPNLayer,
              GLPNModel,
              GLPNPreTrainedModel,
          )


else:
     import sys

     lowerCamelCase :      List[Any]					 =     _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
