
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     UpperCAmelCase						(		A_					):



   def 							_SCREAMING_SNAKE_CASE  (self						:   int					)						->      Any:


          '''simple docstring'''


          snake_case			:  Tuple     							= self.config_class(**self.inputs_dict					)
          self.parent.assertTrue(hasattr(snake_case__       ,		"width_multiplier"					)					)






class     UpperCAmelCase						:



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


          '''simple docstring'''


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



   def 							_SCREAMING_SNAKE_CASE  (self						:   Tuple					)						->      Optional[int]:


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

          snake_case			:  Tuple     							= None
          snake_case			:  List[str]     							= None
          if self.use_labels:
                 snake_case			:  Union[str, Any]     							= ids_tensor([self.batch_size]       ,		self.num_labels					)
                 snake_case			:  Optional[Any]     							= ids_tensor([self.batch_size, self.image_size, self.image_size]       ,		self.num_labels					)

          snake_case			:  Tuple     							= self.get_config()

          return config, pixel_values, labels, pixel_labels



   def 							_SCREAMING_SNAKE_CASE  (self						:   Tuple					)						->      List[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 							_SCREAMING_SNAKE_CASE  (self						:   List[str]       ,		snake_case__						:   Union[str, Any]       ,		snake_case__						:   Optional[Any]       ,		snake_case__						:   str       ,		snake_case__						:   Union[str, Any]					)						->      int:


          '''simple docstring'''


          snake_case			:  Dict     							= MobileViTVaModel(config=snake_case__					)
          model.to(snake_case__					)
          model.eval()
          snake_case			:  int     							= model(snake_case__					)
          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						:   Optional[int]       ,		snake_case__						:   List[str]       ,		snake_case__						:   List[Any]       ,		snake_case__						:   Tuple       ,		snake_case__						:   Any					)						->      Union[str, Any]:


          '''simple docstring'''


          snake_case			:  str     							= self.num_labels
          snake_case			:  Optional[Any]     							= MobileViTVaForImageClassification(snake_case__					)
          model.to(snake_case__					)
          model.eval()
          snake_case			:  Tuple     							= model(snake_case__       ,		labels=snake_case__					)
          self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.num_labels)					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Optional[int]       ,		snake_case__						:   List[Any]       ,		snake_case__						:   str       ,		snake_case__						:   List[Any]       ,		snake_case__						:   List[str]					)						->      Any:


          '''simple docstring'''


          snake_case			:  Union[str, Any]     							= self.num_labels
          snake_case			:  Union[str, Any]     							= MobileViTVaForSemanticSegmentation(snake_case__					)
          model.to(snake_case__					)
          model.eval()
          snake_case			:  Tuple     							= model(snake_case__					)
          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			:  Optional[int]     							= model(snake_case__       ,		labels=snake_case__					)
          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						:   Tuple					)						->      Any:


          '''simple docstring'''


          snake_case			:  str     							= self.prepare_config_and_inputs()
          snake_case							,   snake_case							,   snake_case							,   snake_case			:  Optional[int]     							= config_and_inputs
          snake_case			:  Dict     							= {"pixel_values": pixel_values}
          return config, inputs_dict






@require_torch
class     UpperCAmelCase						(		A_			,A_			,unittest.TestCase					):
   A__   :						Optional[int]			=	(
       (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )

   A__   :						Optional[int]			=	(
       {
           "feature-extraction": MobileViTVaModel,
           "image-classification": MobileViTVaForImageClassification,
           "image-segmentation": MobileViTVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   A__   :						int			=	False
   A__   :						Union[str, Any]			=	False
   A__   :						int			=	False
   A__   :						str			=	False



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      Optional[int]:


          '''simple docstring'''


          snake_case			:  Tuple     							= MobileViTVaModelTester(self					)
          snake_case			:  str     							= MobileViTVaConfigTester(self       ,		config_class=snake_case__       ,		has_text_modality=snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Any					)						->      Optional[Any]:


          '''simple docstring'''


          self.config_tester.run_common_tests()



   @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"					)
   def 							_SCREAMING_SNAKE_CASE  (self						:   Any					)						->      Dict:


          '''simple docstring'''


          pass



   @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"					)
   def 							_SCREAMING_SNAKE_CASE  (self						:   int					)						->      str:


          '''simple docstring'''


          pass



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


          '''simple docstring'''


          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						:   str					)						->      List[Any]:


          '''simple docstring'''


          pass



   @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."					)
   def 							_SCREAMING_SNAKE_CASE  (self						:   int					)						->      Union[str, Any]:


          '''simple docstring'''


          pass



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[Any]					)						->      Any:


          '''simple docstring'''


          snake_case							,   snake_case			:  Union[str, Any]     							= self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case			:  str     							= ["pixel_values"]
                 self.assertListEqual(arg_names[:1]       ,		snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[str]					)						->      Optional[int]:


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      str:


          '''simple docstring'''


          def check_hidden_states_output(snake_case__						:   List[Any]       ,		snake_case__						:   List[str]       ,		snake_case__						:   List[Any]					):
                 snake_case			:  List[Any]     							= model_class(snake_case__					)
                 model.to(snake_case__					)
                 model.eval()

                 with torch.no_grad():
                        snake_case			:  List[Any]     							= model(**self._prepare_for_class(snake_case__       ,		snake_case__					)					)

                 snake_case			:  str     							= outputs.hidden_states

                 snake_case			:  Optional[int]     							= 5
                 self.assertEqual(len(snake_case__					)       ,		snake_case__					)

                 # 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			:  List[str]     							= 2
                 for i in range(len(snake_case__					)					):
                        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			:  Dict     							= self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 snake_case			:  Any     							= True
                 check_hidden_states_output(snake_case__       ,		snake_case__       ,		snake_case__					)

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

                 check_hidden_states_output(snake_case__       ,		snake_case__       ,		snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[Any]					)						->      Optional[int]:


          '''simple docstring'''


          snake_case			:  Any     							= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case__					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Dict					)						->      Tuple:


          '''simple docstring'''


          snake_case			:  Tuple     							= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__					)



   @slow
   def 							_SCREAMING_SNAKE_CASE  (self						:   Union[str, Any]					)						->      Dict:


          '''simple docstring'''


          for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case			:  Optional[int]     							= MobileViTVaModel.from_pretrained(snake_case__					)
                 self.assertIsNotNone(snake_case__					)



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






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



   @cached_property
   def 							_SCREAMING_SNAKE_CASE  (self						:   List[str]					)						->      Dict:


          '''simple docstring'''


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



   @slow
   def 							_SCREAMING_SNAKE_CASE  (self						:   Dict					)						->      str:


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					).to(
              snake_case__					)

          snake_case			:  Optional[int]     							= self.default_image_processor
          snake_case			:  Optional[Any]     							= prepare_img()
          snake_case			:  List[str]     							= image_processor(images=snake_case__       ,		return_tensors="pt"					).to(snake_case__					)

          # forward pass
          with torch.no_grad():
                 snake_case			:  List[str]     							= model(**snake_case__					)

          # verify the logits
          snake_case			:  str     							= torch.Size((1, 10_00)					)
          self.assertEqual(outputs.logits.shape       ,		snake_case__					)

          snake_case			:  Tuple     							= torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01]					).to(snake_case__					)

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



   @slow
   def 							_SCREAMING_SNAKE_CASE  (self						:   Any					)						->      Dict:


          '''simple docstring'''


          snake_case			:  Dict     							= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
          snake_case			:  Any     							= model.to(snake_case__					)

          snake_case			:  Tuple     							= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

          snake_case			:  Any     							= prepare_img()
          snake_case			:  str     							= image_processor(images=snake_case__       ,		return_tensors="pt"					).to(snake_case__					)

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

          # verify the logits
          snake_case			:  Any     							= torch.Size((1, 21, 32, 32)					)
          self.assertEqual(logits.shape       ,		snake_case__					)

          snake_case			:  str     							= 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=snake_case__       ,		)

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



   @slow
   def 							_SCREAMING_SNAKE_CASE  (self						:   Any					)						->      List[Any]:


          '''simple docstring'''


          snake_case			:  Optional[Any]     							= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
          snake_case			:  str     							= model.to(snake_case__					)

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

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

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

          snake_case			:  Optional[int]     							= outputs.logits.detach().cpu()

          snake_case			:  Optional[Any]     							= image_processor.post_process_semantic_segmentation(outputs=snake_case__       ,		target_sizes=[(50, 60)]					)
          snake_case			:  Any     							= torch.Size((50, 60)					)
          self.assertEqual(segmentation[0].shape       ,		snake_case__					)

          snake_case			:  Optional[int]     							= image_processor.post_process_semantic_segmentation(outputs=snake_case__					)
          snake_case			:  Dict     							= torch.Size((32, 32)					)
          self.assertEqual(segmentation[0].shape       ,		snake_case__					)







__lowerCamelCase				=			{
    0: """0""",
    1: """1""",
    2: """2""",
    3: """3""",
    4: """4""",
    5: """5""",
    6: """6""",
    7: """7""",
    8: """8""",
    9: """9""",
    10: """a""",
    11: """b""",
    12: """c""",
    13: """d""",
    14: """e""",
    15: """f""",
}


def      UpperCamelCase   (       __lowerCamelCase	:					float       ):
       assert type(__lowerCamelCase       ) in (int, float) and decimal == int(__lowerCamelCase       )
       snake_case			:  str     							= int(__lowerCamelCase       )
       snake_case			:  str     							= ""
       snake_case			:  str     							= False
       if decimal < 0:
              snake_case			:  Optional[Any]     							= True
              decimal *= -1
       while decimal > 0:
              snake_case							,   snake_case			:  Union[str, Any]     							= divmod(__lowerCamelCase							,   16       )
              snake_case			:  Tuple     							= values[remainder] + hexadecimal
       snake_case			:  Tuple     							= "0x" + hexadecimal
       if negative:
              snake_case			:  Any     							= "-" + hexadecimal
       return hexadecimal


if __name__ == "__main__":
   import doctest

   doctest.testmod()





