


"""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 						_A  (  snake_case_  ):







    """simple docstring"""




    def      __snake_case							( self    :   str):
      a						:		List[Any]											=      self.config_class(**self.inputs_dict)
      self.parent.assertTrue(hasattr(__UpperCAmelCase    ,			"width_multiplier"))






class 						_A  :







    """simple docstring"""




    def __init__( self    :   Dict    ,			__UpperCAmelCase    :   Union[str, Any]    ,			__UpperCAmelCase    :   int=13    ,			__UpperCAmelCase    :   Optional[int]=64    ,			__UpperCAmelCase    :   Tuple=2    ,			__UpperCAmelCase    :   List[str]=3    ,			__UpperCAmelCase    :   Any="swish"    ,			__UpperCAmelCase    :   Any=3    ,			__UpperCAmelCase    :   str=32    ,			__UpperCAmelCase    :   Tuple=0.1    ,			__UpperCAmelCase    :   str=0.02    ,			__UpperCAmelCase    :   Union[str, Any]=True    ,			__UpperCAmelCase    :   List[str]=True    ,			__UpperCAmelCase    :   str=10    ,			__UpperCAmelCase    :   List[Any]=None    ,			__UpperCAmelCase    :   Any=0.25    ,			__UpperCAmelCase    :   List[str]=0.0    ,			__UpperCAmelCase    :   int=0.0    ,			):
      a						:		Optional[Any]											=      parent
      a						:		List[Any]											=      batch_size
      a						:		str											=      image_size
      a						:		Union[str, Any]											=      patch_size
      a						:		Tuple											=      num_channels
      a						:		Dict											=      make_divisible(512 * width_multiplier    ,			divisor=8)
      a						:		Optional[int]											=      hidden_act
      a						:		List[str]											=      conv_kernel_size
      a						:		Dict											=      output_stride
      a						:		Tuple											=      classifier_dropout_prob
      a						:		Union[str, Any]											=      use_labels
      a						:		Dict											=      is_training
      a						:		List[str]											=      num_labels
      a						:		Tuple											=      initializer_range
      a						:		Any											=      scope
      a						:		Union[str, Any]											=      width_multiplier
      a						:		str											=      ffn_dropout
      a						:		int											=      attn_dropout






    def      __snake_case							( self    :   Optional[int]):
      a						:		Union[str, Any]											=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      a						:		Any											=      None
      a						:		int											=      None
      if self.use_labels:
        a						:		Optional[Any]											=      ids_tensor([self.batch_size]    ,			self.num_labels)
        a						:		Optional[int]											=      ids_tensor([self.batch_size, self.image_size, self.image_size]    ,			self.num_labels)

      a						:		Optional[int]											=      self.get_config()

      return config, pixel_values, labels, pixel_labels






    def      __snake_case							( self    :   str):
      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      __snake_case							( self    :   Tuple    ,			__UpperCAmelCase    :   Optional[int]    ,			__UpperCAmelCase    :   Optional[Any]    ,			__UpperCAmelCase    :   Any    ,			__UpperCAmelCase    :   List[str]):
      a						:		Any											=      MobileViTVaModel(config=__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		Union[str, Any]											=      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      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   Optional[Any]    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   Any):
      a						:		List[str]											=      self.num_labels
      a						:		Any											=      MobileViTVaForImageClassification(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[str]											=      model(__UpperCAmelCase    ,			labels=__UpperCAmelCase)
      self.parent.assertEqual(result.logits.shape    ,			(self.batch_size, self.num_labels))






    def      __snake_case							( self    :   str    ,			__UpperCAmelCase    :   int    ,			__UpperCAmelCase    :   List[str]    ,			__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   int):
      a						:		int											=      self.num_labels
      a						:		str											=      MobileViTVaForSemanticSegmentation(__UpperCAmelCase)
      model.to(__UpperCAmelCase)
      model.eval()
      a						:		List[Any]											=      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,
          )    ,			)
      a						:		Dict											=      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      __snake_case							( self    :   Optional[Any]):
      a						:		Optional[Any]											=      self.prepare_config_and_inputs()
      a							,		a							,		a							,		a						:		str											=      config_and_inputs
      a						:		List[str]											=      {"pixel_values": pixel_values}
      return config, inputs_dict






@require_torch
class 						_A  (  snake_case_   ,snake_case_   ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase	:							List[Any]     =	(
        (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
        if is_torch_available()
        else ()
    )

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

    UpperCAmelCase	:							Dict     =	False
    UpperCAmelCase	:							List[str]     =	False
    UpperCAmelCase	:							str     =	False
    UpperCAmelCase	:							Optional[Any]     =	False






    def      __snake_case							( self    :   str):
      a						:		int											=      MobileViTVaModelTester(self)
      a						:		Union[str, Any]											=      MobileViTVaConfigTester(self    ,			config_class=__UpperCAmelCase    ,			has_text_modality=__UpperCAmelCase)






    def      __snake_case							( self    :   Optional[int]):
      self.config_tester.run_common_tests()






    @unittest.skip(reason="MobileViTV2 does not use inputs_embeds")
    def      __snake_case							( self    :   str):
      pass






    @unittest.skip(reason="MobileViTV2 does not support input and output embeddings")
    def      __snake_case							( self    :   List[Any]):
      pass






    @unittest.skip(reason="MobileViTV2 does not output attentions")
    def      __snake_case							( self    :   List[Any]):
      pass






    @require_torch_multi_gpu
    @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run.")
    def      __snake_case							( self    :   Optional[int]):
      pass






    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
    def      __snake_case							( self    :   List[str]):
      pass






    def      __snake_case							( self    :   Tuple):
      a							,		a						:		int											=      self.model_tester.prepare_config_and_inputs_for_common()

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

        a						:		Optional[int]											=      ["pixel_values"]
        self.assertListEqual(arg_names[:1]    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   Optional[Any]):
      a						:		Dict											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase)






    def      __snake_case							( self    :   List[Any]):
      def check_hidden_states_output(__UpperCAmelCase    :   Dict    ,			__UpperCAmelCase    :   str    ,			__UpperCAmelCase    :   Optional[int]):
        a						:		List[str]											=      model_class(__UpperCAmelCase)
        model.to(__UpperCAmelCase)
        model.eval()

        with torch.no_grad():
          a						:		int											=      model(**self._prepare_for_class(__UpperCAmelCase    ,			__UpperCAmelCase))

        a						:		Dict											=      outputs.hidden_states

        a						:		List[Any]											=      5
        self.assertEqual(len(__UpperCAmelCase)    ,			__UpperCAmelCase)

        # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        a						:		Union[str, Any]											=      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)

      a							,		a						:		Any											=      self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        a						:		Optional[int]											=      True
        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        a						:		Optional[Any]											=      True

        check_hidden_states_output(__UpperCAmelCase    ,			__UpperCAmelCase    ,			__UpperCAmelCase)






    def      __snake_case							( self    :   List[str]):
      a						:		Tuple											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase)






    def      __snake_case							( self    :   Optional[int]):
      a						:		str											=      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase)






    @slow
    def      __snake_case							( self    :   Optional[int]):
      for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a						:		int											=      MobileViTVaModel.from_pretrained(__UpperCAmelCase)
        self.assertIsNotNone(__UpperCAmelCase)






def 					lowercase      (    )->				Union[str, Any]:
  '''simple docstring'''







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







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







    """simple docstring"""




    @cached_property
    def      __snake_case							( self    :   Any):
      return (
          MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256")
          if is_vision_available()
          else None
      )






    @slow
    def      __snake_case							( self    :   Any):
      a						:		List[Any]											=      MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256").to(
          __UpperCAmelCase)

      a						:		Optional[Any]											=      self.default_image_processor
      a						:		Optional[Any]											=      prepare_img()
      a						:		Any											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Optional[int]											=      model(**__UpperCAmelCase)

      # verify the logits
      a						:		Dict											=      torch.Size((1, 1000))
      self.assertEqual(outputs.logits.shape    ,			__UpperCAmelCase)

      a						:		str											=      torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]).to(__UpperCAmelCase)

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






    @slow
    def      __snake_case							( self    :   List[Any]):
      a						:		Tuple											=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")
      a						:		Optional[int]											=      model.to(__UpperCAmelCase)

      a						:		Union[str, Any]											=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")

      a						:		Dict											=      prepare_img()
      a						:		List[str]											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Union[str, Any]											=      model(**__UpperCAmelCase)
      a						:		Any											=      outputs.logits

      # verify the logits
      a						:		str											=      torch.Size((1, 21, 32, 32))
      self.assertEqual(logits.shape    ,			__UpperCAmelCase)

      a						:		Union[str, Any]											=      torch.tensor(
          [
              [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
              [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
              [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
          ]    ,			device=__UpperCAmelCase    ,			)

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






    @slow
    def      __snake_case							( self    :   Tuple):
      a						:		Optional[Any]											=      MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")
      a						:		Optional[Any]											=      model.to(__UpperCAmelCase)

      a						:		Any											=      MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3")

      a						:		Optional[Any]											=      prepare_img()
      a						:		Dict											=      image_processor(images=__UpperCAmelCase    ,			return_tensors="pt").to(__UpperCAmelCase)

      # forward pass
      with torch.no_grad():
        a						:		Tuple											=      model(**__UpperCAmelCase)

      a						:		str											=      outputs.logits.detach().cpu()

      a						:		Dict											=      image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase    ,			target_sizes=[(50, 60)])
      a						:		Dict											=      torch.Size((50, 60))
      self.assertEqual(segmentation[0].shape    ,			__UpperCAmelCase)

      a						:		str											=      image_processor.post_process_semantic_segmentation(outputs=__UpperCAmelCase)
      a						:		Union[str, Any]											=      torch.Size((32, 32))
      self.assertEqual(segmentation[0].shape    ,			__UpperCAmelCase)








"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_dpt import DPTImageProcessor


__lowercase    =				logging.get_logger(__name__)






class 						_A  (  _a  ):







    """simple docstring"""




    def __init__( self    :   List[Any]    ,			*__UpperCAmelCase    :   int    ,			**__UpperCAmelCase    :   List[Any]):
      warnings.warn(
          "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
          " use DPTImageProcessor instead."    ,			__UpperCAmelCase    ,			)
      super().__init__(*__UpperCAmelCase    ,			**__UpperCAmelCase)






