

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




  def   A__     (				self					)  -> List[Any]:
        '''simple docstring'''






        _lowercase	       =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     :




  def __init__(				self							,   lowerCAmelCase							,   lowerCAmelCase=13							,   lowerCAmelCase=32							,   lowerCAmelCase=2							,   lowerCAmelCase=3							,   lowerCAmelCase=640							,   lowerCAmelCase=4							,   lowerCAmelCase="silu"							,   lowerCAmelCase=3							,   lowerCAmelCase=32							,   lowerCAmelCase=0.1							,   lowerCAmelCase=0.1							,   lowerCAmelCase=0.1							,   lowerCAmelCase=0.02							,   lowerCAmelCase=True							,   lowerCAmelCase=True							,   lowerCAmelCase=10							,   lowerCAmelCase=None							,   )  -> Any:
        '''simple docstring'''






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




  def   A__     (				self					)  -> Optional[Any]:
        '''simple docstring'''






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

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

        _lowercase	       =self.get_config()

        return config, pixel_values, labels, pixel_labels




  def   A__     (				self					)  -> int:
        '''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   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)  -> Any:
        '''simple docstring'''






        _lowercase	       =MobileViTModel(config=__UpperCAmelCase					)
        model.to(__UpperCAmelCase					)
        model.eval()
        _lowercase	       =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   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)  -> Tuple:
        '''simple docstring'''






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




  def   A__     (				self							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					)  -> Optional[int]:
        '''simple docstring'''






        _lowercase	       =self.num_labels
        _lowercase	       =MobileViTForSemanticSegmentation(__UpperCAmelCase					)
        model.to(__UpperCAmelCase					)
        model.eval()
        _lowercase	       =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,
            )							,   )
        _lowercase	       =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   A__     (				self					)  -> Tuple:
        '''simple docstring'''






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





@require_torch
class  __lowerCAmelCase     (					SCREAMING_SNAKE_CASE			,			SCREAMING_SNAKE_CASE			,			unittest.TestCase							):
  _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   A__     (				self					)  -> str:
        '''simple docstring'''






        _lowercase	       =MobileViTModelTester(self					)
        _lowercase	       =MobileViTConfigTester(self							,   config_class=__UpperCAmelCase							,   has_text_modality=__UpperCAmelCase					)




  def   A__     (				self					)  -> int:
        '''simple docstring'''






        self.config_tester.run_common_tests()




  @unittest.skip(reason='MobileViT does not use inputs_embeds'					)
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='MobileViT does not support input and output embeddings'					)
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






        pass




  @unittest.skip(reason='MobileViT does not output attentions'					)
  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        pass




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






        _lowercase       ,       _lowercase	       =self.model_tester.prepare_config_and_inputs_for_common()

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

              _lowercase	       =['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   A__     (				self					)  -> Optional[int]:
        '''simple docstring'''






        pass




  def   A__     (				self					)  -> Dict:
        '''simple docstring'''






        _lowercase	       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__UpperCAmelCase					)




  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        def check_hidden_states_output(lowerCAmelCase							,   lowerCAmelCase							,   lowerCAmelCase					):
              _lowercase	       =model_class(__UpperCAmelCase					)
              model.to(__UpperCAmelCase					)
              model.eval()

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

              _lowercase	       =outputs.hidden_states

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

        _lowercase       ,       _lowercase	       =self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              _lowercase	       =True
              check_hidden_states_output(__UpperCAmelCase							,   __UpperCAmelCase							,   __UpperCAmelCase					)

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

              check_hidden_states_output(__UpperCAmelCase							,   __UpperCAmelCase							,   __UpperCAmelCase					)




  def   A__     (				self					)  -> Optional[int]:
        '''simple docstring'''






        _lowercase	       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase					)




  def   A__     (				self					)  -> str:
        '''simple docstring'''






        _lowercase	       =self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*__UpperCAmelCase					)




  @slow
  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






        for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowercase	       =MobileViTModel.from_pretrained(__UpperCAmelCase					)
              self.assertIsNotNone(__UpperCAmelCase					)
def      a      (			)    ->      Union[str, Any]:





      """simple docstring"""



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







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




  @cached_property
  def   A__     (				self					)  -> List[str]:
        '''simple docstring'''






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




  @slow
  def   A__     (				self					)  -> Any:
        '''simple docstring'''






        _lowercase	       =MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'					).to(__UpperCAmelCase					)

        _lowercase	       =self.default_image_processor
        _lowercase	       =prepare_img()
        _lowercase	       =image_processor(images=__UpperCAmelCase							,   return_tensors='pt'					).to(__UpperCAmelCase					)

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

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

        _lowercase	       =torch.tensor([-1.9364, -1.2327, -0.4653]					).to(__UpperCAmelCase					)

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




  @slow
  def   A__     (				self					)  -> Union[str, Any]:
        '''simple docstring'''






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

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

        _lowercase	       =prepare_img()
        _lowercase	       =image_processor(images=__UpperCAmelCase							,   return_tensors='pt'					).to(__UpperCAmelCase					)

        # forward pass
        with torch.no_grad():
              _lowercase	       =model(**__UpperCAmelCase					)
        _lowercase	       =outputs.logits

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

        _lowercase	       =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   A__     (				self					)  -> Tuple:
        '''simple docstring'''






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

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

        _lowercase	       =prepare_img()
        _lowercase	       =image_processor(images=__UpperCAmelCase							,   return_tensors='pt'					).to(__UpperCAmelCase					)

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

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

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

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










from typing import TYPE_CHECKING

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


UpperCAmelCase__				   =		{
    "configuration_groupvit": [
        "GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "GroupViTConfig",
        "GroupViTOnnxConfig",
        "GroupViTTextConfig",
        "GroupViTVisionConfig",
    ],
}

try:
     if not is_torch_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCAmelCase__				   =		[
         "GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
         "GroupViTModel",
         "GroupViTPreTrainedModel",
         "GroupViTTextModel",
         "GroupViTVisionModel",
     ]

try:
     if not is_tf_available():
          raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
     pass
else:
     UpperCAmelCase__				   =		[
         "TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST",
         "TFGroupViTModel",
         "TFGroupViTPreTrainedModel",
         "TFGroupViTTextModel",
         "TFGroupViTVisionModel",
     ]

if TYPE_CHECKING:
     from .configuration_groupvit import (
         GROUPVIT_PRETRAINED_CONFIG_ARCHIVE_MAP,
         GroupViTConfig,
         GroupViTOnnxConfig,
         GroupViTTextConfig,
         GroupViTVisionConfig,
     )

     try:
          if not is_torch_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_groupvit import (
              GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
              GroupViTModel,
              GroupViTPreTrainedModel,
              GroupViTTextModel,
              GroupViTVisionModel,
          )

     try:
          if not is_tf_available():
               raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
          pass
     else:
          from .modeling_tf_groupvit import (
              TF_GROUPVIT_PRETRAINED_MODEL_ARCHIVE_LIST,
              TFGroupViTModel,
              TFGroupViTPreTrainedModel,
              TFGroupViTTextModel,
              TFGroupViTVisionModel,
          )

else:
     import sys

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


