




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    __lowerCAmelCase       (							lowerCAmelCase):






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         lowercase    :List[Any]      	=						self.config_class(**self.inputs_dict				)
         self.parent.assertTrue(hasattr(_lowerCAmelCase       ,					"width_multiplier"				)				)







class    __lowerCAmelCase       :






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






       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         lowercase    :List[str]      	=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

         lowercase    :Union[str, Any]      	=						self.get_config()

         return config, pixel_values, labels, pixel_labels






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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]       ,					_lowerCAmelCase:					Dict       ,					_lowerCAmelCase:					Any       ,					_lowerCAmelCase:					Tuple       ,					_lowerCAmelCase:					Optional[int]				):
         lowercase    :Dict      	=						self.num_labels
         lowercase    :Optional[int]      	=						MobileViTVaForSemanticSegmentation(_lowerCAmelCase				)
         model.to(_lowerCAmelCase				)
         model.eval()
         lowercase    :Union[str, Any]      	=						model(_lowerCAmelCase				)
         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    :int      	=						model(_lowerCAmelCase       ,					labels=_lowerCAmelCase				)
         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 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :Dict      	=						self.prepare_config_and_inputs()
         lowercase	,    lowercase	,    lowercase	,    lowercase    :Union[str, Any]      	=						config_and_inputs
         lowercase    :int      	=						{"pixel_values": pixel_values}
         return config, inputs_dict







@require_torch
class    __lowerCAmelCase       (							lowerCAmelCase      , lowerCAmelCase      , unittest.TestCase):
       _a 					=						(
           (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )

       _a 					=						(
           {
               '''feature-extraction''': MobileViTVaModel,
               '''image-classification''': MobileViTVaForImageClassification,
               '''image-segmentation''': MobileViTVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       _a 					=						False
       _a 					=						False
       _a 					=						False
       _a 					=						False






       def 					SCREAMING_SNAKE_CASE    (   self:					Dict				):
         lowercase    :str      	=						MobileViTVaModelTester(self				)
         lowercase    :str      	=						MobileViTVaConfigTester(self       ,					config_class=_lowerCAmelCase       ,					has_text_modality=_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         self.config_tester.run_common_tests()






       @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"				)
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         pass






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






       @unittest.skip(reason="MobileViTV2 does not output attentions"				)
       def 					SCREAMING_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 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         pass






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






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase	,    lowercase    :Optional[Any]      	=						self.model_tester.prepare_config_and_inputs_for_common()

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

           lowercase    :Any      	=						["pixel_values"]
           self.assertListEqual(arg_names[:1]       ,					_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :Optional[int]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         def check_hidden_states_output(_lowerCAmelCase:					int       ,					_lowerCAmelCase:					List[Any]       ,					_lowerCAmelCase:					Optional[int]				):
           lowercase    :Dict      	=						model_class(_lowerCAmelCase				)
           model.to(_lowerCAmelCase				)
           model.eval()

           with torch.no_grad():
             lowercase    :int      	=						model(**self._prepare_for_class(_lowerCAmelCase       ,					_lowerCAmelCase				)				)

           lowercase    :Optional[Any]      	=						outputs.hidden_states

           lowercase    :List[str]      	=						5
           self.assertEqual(len(_lowerCAmelCase				)       ,					_lowerCAmelCase				)

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

         for model_class in self.all_model_classes:
           lowercase    :Optional[Any]      	=						True
           check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)

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

           check_hidden_states_output(_lowerCAmelCase       ,					_lowerCAmelCase       ,					_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         lowercase    :List[Any]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):
         lowercase    :List[Any]      	=						self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCAmelCase				)






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[int]				):
         for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase    :Optional[Any]      	=						MobileViTVaModel.from_pretrained(_lowerCAmelCase				)
           self.assertIsNotNone(_lowerCAmelCase				)







def       UpperCAmelCase__  (     ):
  lowercase    :Optional[int]      	=						Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
  return image







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






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






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         lowercase    :Optional[int]      	=						MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"				).to(
             _lowerCAmelCase				)

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

         # forward pass
         with torch.no_grad():
           lowercase    :int      	=						model(**_lowerCAmelCase				)

         # verify the logits
         lowercase    :Optional[int]      	=						torch.Size((1, 10_00)				)
         self.assertEqual(outputs.logits.shape       ,					_lowerCAmelCase				)

         lowercase    :List[str]      	=						torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]				).to(_lowerCAmelCase				)

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






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]				):
         lowercase    :Optional[Any]      	=						MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"				)
         lowercase    :Dict      	=						model.to(_lowerCAmelCase				)

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

         lowercase    :Union[str, Any]      	=						prepare_img()
         lowercase    :Optional[Any]      	=						image_processor(images=_lowerCAmelCase       ,					return_tensors="pt"				).to(_lowerCAmelCase				)

         # forward pass
         with torch.no_grad():
           lowercase    :Any      	=						model(**_lowerCAmelCase				)
         lowercase    :str      	=						outputs.logits

         # verify the logits
         lowercase    :Optional[int]      	=						torch.Size((1, 21, 32, 32)				)
         self.assertEqual(logits.shape       ,					_lowerCAmelCase				)

         lowercase    :Optional[int]      	=						torch.tensor(
             [
                 [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
                 [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
                 [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
             ]       ,					device=_lowerCAmelCase       ,					)

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






       @slow
       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :int      	=						MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"				)
         lowercase    :Any      	=						model.to(_lowerCAmelCase				)

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

         lowercase    :int      	=						prepare_img()
         lowercase    :Dict      	=						image_processor(images=_lowerCAmelCase       ,					return_tensors="pt"				).to(_lowerCAmelCase				)

         # forward pass
         with torch.no_grad():
           lowercase    :Tuple      	=						model(**_lowerCAmelCase				)

         lowercase    :Dict      	=						outputs.logits.detach().cpu()

         lowercase    :List[Any]      	=						image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase       ,					target_sizes=[(50, 60)]				)
         lowercase    :Tuple      	=						torch.Size((50, 60)				)
         self.assertEqual(segmentation[0].shape       ,					_lowerCAmelCase				)

         lowercase    :List[Any]      	=						image_processor.post_process_semantic_segmentation(outputs=_lowerCAmelCase				)
         lowercase    :Optional[int]      	=						torch.Size((32, 32)				)
         self.assertEqual(segmentation[0].shape       ,					_lowerCAmelCase				)









from abc import ABC, abstractmethod
from argparse import ArgumentParser




class    __lowerCAmelCase       (							lowerCAmelCase):






       @staticmethod
       @abstractmethod
       def 					SCREAMING_SNAKE_CASE    (   _lowerCAmelCase:					ArgumentParser				):
         raise NotImplementedError()






       @abstractmethod
       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):
         raise NotImplementedError()



