




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






      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  self.config_class(**self.inputs_dict       )
           self.parent.assertTrue(hasattr(lowercase__						,						"""width_multiplier"""       )       )







class      SCREAMING_SNAKE_CASE    :






      def __init__( self   :  Optional[int]						,						lowercase__   :  int						,						lowercase__   :  int=13						,						lowercase__   :  List[str]=64						,						lowercase__   :  List[Any]=2						,						lowercase__   :  List[str]=3						,						lowercase__   :  Any="swish"						,						lowercase__   :  Union[str, Any]=3						,						lowercase__   :  Optional[int]=32						,						lowercase__   :  Any=0.1						,						lowercase__   :  Tuple=0.02						,						lowercase__   :  int=True						,						lowercase__   :  Optional[Any]=True						,						lowercase__   :  str=10						,						lowercase__   :  Union[str, Any]=None						,						lowercase__   :  str=0.25						,						lowercase__   :  Tuple=0.0						,						lowercase__   :  Optional[Any]=0.0						,						):


           '''simple docstring'''

           a_     :							str     						=  parent
           a_     :							List[Any]     						=  batch_size
           a_     :							Optional[int]     						=  image_size
           a_     :							Optional[Any]     						=  patch_size
           a_     :							Tuple     						=  num_channels
           a_     :							Any     						=  make_divisible(512 * width_multiplier						,						divisor=8       )
           a_     :							Optional[Any]     						=  hidden_act
           a_     :							Optional[int]     						=  conv_kernel_size
           a_     :							Tuple     						=  output_stride
           a_     :							int     						=  classifier_dropout_prob
           a_     :							List[Any]     						=  use_labels
           a_     :							Optional[Any]     						=  is_training
           a_     :							int     						=  num_labels
           a_     :							int     						=  initializer_range
           a_     :							List[Any]     						=  scope
           a_     :							Optional[int]     						=  width_multiplier
           a_     :							str     						=  ffn_dropout
           a_     :							Any     						=  attn_dropout






      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							str     						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

           a_     :							Optional[int]     						=  None
           a_     :							int     						=  None
           if self.use_labels:
                a_     :							Dict     						=  ids_tensor([self.batch_size]						,						self.num_labels       )
                a_     :							str     						=  ids_tensor([self.batch_size, self.image_size, self.image_size]						,						self.num_labels       )

           a_     :							List[str]     						=  self.get_config()

           return config, pixel_values, labels, pixel_labels






      def 							lowercase_						( self   :  str       ):


           '''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 							lowercase_						( self   :  List[Any]						,						lowercase__   :  Tuple						,						lowercase__   :  Optional[int]						,						lowercase__   :  Dict						,						lowercase__   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[str]     						=  MobileViTVaModel(config=lowercase__       )
           model.to(lowercase__       )
           model.eval()
           a_     :							Any     						=  model(lowercase__       )
           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 							lowercase_						( self   :  int						,						lowercase__   :  int						,						lowercase__   :  Union[str, Any]						,						lowercase__   :  int						,						lowercase__   :  Dict       ):


           '''simple docstring'''

           a_     :							Dict     						=  self.num_labels
           a_     :							List[Any]     						=  MobileViTVaForImageClassification(lowercase__       )
           model.to(lowercase__       )
           model.eval()
           a_     :							Optional[Any]     						=  model(lowercase__						,						labels=lowercase__       )
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)       )






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  Dict						,						lowercase__   :  Any						,						lowercase__   :  str						,						lowercase__   :  List[Any]       ):


           '''simple docstring'''

           a_     :							Dict     						=  self.num_labels
           a_     :							Optional[Any]     						=  MobileViTVaForSemanticSegmentation(lowercase__       )
           model.to(lowercase__       )
           model.eval()
           a_     :							Tuple     						=  model(lowercase__       )
           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_     :							Optional[int]     						=  model(lowercase__						,						labels=lowercase__       )
           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 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.prepare_config_and_inputs()
           a_						,     a_						,     a_						,     a_     :							Any     						=  config_and_inputs
           a_     :							str     						=  {"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class      SCREAMING_SNAKE_CASE    (						snake_case_							,      snake_case_							,      unittest.TestCase				):
      __magic_name__  :       Union[str, Any]   							=					(
          (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
          if is_torch_available()
          else ()
      )

      __magic_name__  :       List[Any]   							=					(
          {
              '''feature-extraction''': MobileViTVaModel,
              '''image-classification''': MobileViTVaForImageClassification,
              '''image-segmentation''': MobileViTVaForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      __magic_name__  :       str   							=					False
      __magic_name__  :       Tuple   							=					False
      __magic_name__  :       Optional[int]   							=					False
      __magic_name__  :       Any   							=					False






      def 							lowercase_						( self   :  str       ):


           '''simple docstring'''

           a_     :							int     						=  MobileViTVaModelTester(self       )
           a_     :							List[Any]     						=  MobileViTVaConfigTester(self						,						config_class=lowercase__						,						has_text_modality=lowercase__       )






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           self.config_tester.run_common_tests()






      @unittest.skip(reason="""MobileViTV2 does not use inputs_embeds"""       )
      def 							lowercase_						( self   :  Union[str, Any]       ):


           '''simple docstring'''

           pass






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


           '''simple docstring'''

           pass






      @unittest.skip(reason="""MobileViTV2 does not output attentions"""       )
      def 							lowercase_						( self   :  Optional[int]       ):


           '''simple docstring'''

           pass






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


           '''simple docstring'''

           pass






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


           '''simple docstring'''

           pass






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           a_						,     a_     :							Tuple     						=  self.model_tester.prepare_config_and_inputs_for_common()

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

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






      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           a_     :							Any     						=  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowercase__       )






      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           def check_hidden_states_output(lowercase__   :  int						,						lowercase__   :  Union[str, Any]						,						lowercase__   :  int       ):
                a_     :							int     						=  model_class(lowercase__       )
                model.to(lowercase__       )
                model.eval()

                with torch.no_grad():
                     a_     :							Dict     						=  model(**self._prepare_for_class(lowercase__						,						lowercase__       )       )

                a_     :							List[Any]     						=  outputs.hidden_states

                a_     :							Optional[Any]     						=  5
                self.assertEqual(len(lowercase__       )						,						lowercase__       )

                # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
                # with the width and height being successively divided by 2.
                a_     :							Optional[int]     						=  2
                for i in range(len(lowercase__       )       ):
                     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_     :							Union[str, Any]     						=  self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                a_     :							List[str]     						=  True
                check_hidden_states_output(lowercase__						,						lowercase__						,						lowercase__       )

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

                check_hidden_states_output(lowercase__						,						lowercase__						,						lowercase__       )






      def 							lowercase_						( self   :  str       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*lowercase__       )






      def 							lowercase_						( self   :  Dict       ):


           '''simple docstring'''

           a_     :							List[str]     						=  self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*lowercase__       )






      @slow
      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                a_     :							Tuple     						=  MobileViTVaModel.from_pretrained(lowercase__       )
                self.assertIsNotNone(lowercase__       )



def  _SCREAMING_SNAKE_CASE     (      ):




     """simple docstring"""


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







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






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


           '''simple docstring'''

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






      @slow
      def 							lowercase_						( self   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  MobileViTVaForImageClassification.from_pretrained("""apple/mobilevitv2-1.0-imagenet1k-256"""       ).to(
               lowercase__       )

           a_     :							Union[str, Any]     						=  self.default_image_processor
           a_     :							Dict     						=  prepare_img()
           a_     :							Union[str, Any]     						=  image_processor(images=lowercase__						,						return_tensors="""pt"""       ).to(lowercase__       )

           # forward pass
           with torch.no_grad():
                a_     :							str     						=  model(**lowercase__       )

           # verify the logits
           a_     :							Optional[int]     						=  torch.Size((1, 1000)       )
           self.assertEqual(outputs.logits.shape						,						lowercase__       )

           a_     :							int     						=  torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]       ).to(lowercase__       )

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






      @slow
      def 							lowercase_						( self   :  Any       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""       )
           a_     :							int     						=  model.to(lowercase__       )

           a_     :							List[Any]     						=  MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""       )

           a_     :							Any     						=  prepare_img()
           a_     :							int     						=  image_processor(images=lowercase__						,						return_tensors="""pt"""       ).to(lowercase__       )

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

           # verify the logits
           a_     :							List[Any]     						=  torch.Size((1, 21, 32, 32)       )
           self.assertEqual(logits.shape						,						lowercase__       )

           a_     :							Any     						=  torch.tensor(
               [
                   [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                   [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                   [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
               ]						,						device=lowercase__						,						)

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






      @slow
      def 							lowercase_						( self   :  int       ):


           '''simple docstring'''

           a_     :							Any     						=  MobileViTVaForSemanticSegmentation.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""       )
           a_     :							int     						=  model.to(lowercase__       )

           a_     :							str     						=  MobileViTImageProcessor.from_pretrained("""shehan97/mobilevitv2-1.0-voc-deeplabv3"""       )

           a_     :							Optional[int]     						=  prepare_img()
           a_     :							List[Any]     						=  image_processor(images=lowercase__						,						return_tensors="""pt"""       ).to(lowercase__       )

           # forward pass
           with torch.no_grad():
                a_     :							List[Any]     						=  model(**lowercase__       )

           a_     :							Union[str, Any]     						=  outputs.logits.detach().cpu()

           a_     :							List[Any]     						=  image_processor.post_process_semantic_segmentation(outputs=lowercase__						,						target_sizes=[(50, 60)]       )
           a_     :							Optional[int]     						=  torch.Size((50, 60)       )
           self.assertEqual(segmentation[0].shape						,						lowercase__       )

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






'''simple docstring'''


from ..utils import DummyObject, requires_backends







class      SCREAMING_SNAKE_CASE    (						metaclass=snake_case_				):
      __magic_name__  :       Dict   							=					['''transformers''', '''torch''', '''note_seq''']






      def __init__( self   :  List[str]						,						*lowercase__   :  Dict						,						**lowercase__   :  int       ):


           '''simple docstring'''

           requires_backends(self						,						["""transformers""", """torch""", """note_seq"""]       )






      @classmethod
      def 							lowercase_						( cls   :  Dict						,						*lowercase__   :  List[str]						,						**lowercase__   :  str       ):


           '''simple docstring'''

           requires_backends(cls						,						["""transformers""", """torch""", """note_seq"""]       )






      @classmethod
      def 							lowercase_						( cls   :  str						,						*lowercase__   :  Optional[int]						,						**lowercase__   :  Any       ):


           '''simple docstring'''

           requires_backends(cls						,						["""transformers""", """torch""", """note_seq"""]       )
