




"""simple docstring"""


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       lowercase(  __a				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						self.config_class(**self.inputs_dict	)
   self.parent.assertTrue(hasattr(a_,   """hidden_sizes"""	)	)
   self.parent.assertTrue(hasattr(a_,   """neck_hidden_sizes"""	)	)
   self.parent.assertTrue(hasattr(a_,   """num_attention_heads"""	)	)







class       lowercase:







 '''simple docstring'''





 def __init__(       self:	Dict,   a_:	str,   a_:	Tuple=13,   a_:	List[str]=32,   a_:	Dict=2,   a_:	Optional[int]=3,   a_:	Union[str, Any]=640,   a_:	Tuple=4,   a_:	Optional[Any]="silu",   a_:	Tuple=3,   a_:	str=32,   a_:	Optional[Any]=0.1,   a_:	Any=0.1,   a_:	Optional[Any]=0.1,   a_:	int=0.02,   a_:	int=True,   a_:	int=True,   a_:	Union[str, Any]=10,   a_:	Optional[Any]=None,   ):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						parent
   _snake_case							:	Tuple			=						batch_size
   _snake_case							:	Any			=						image_size
   _snake_case							:	List[Any]			=						patch_size
   _snake_case							:	List[Any]			=						num_channels
   _snake_case							:	Optional[Any]			=						last_hidden_size
   _snake_case							:	Tuple			=						num_attention_heads
   _snake_case							:	Optional[Any]			=						hidden_act
   _snake_case							:	int			=						conv_kernel_size
   _snake_case							:	Dict			=						output_stride
   _snake_case							:	Any			=						hidden_dropout_prob
   _snake_case							:	int			=						attention_probs_dropout_prob
   _snake_case							:	Optional[Any]			=						classifier_dropout_prob
   _snake_case							:	str			=						use_labels
   _snake_case							:	List[Any]			=						is_training
   _snake_case							:	Any			=						num_labels
   _snake_case							:	Union[str, Any]			=						initializer_range
   _snake_case							:	Any			=						scope


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Tuple			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

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

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

   return config, pixel_values, labels, pixel_labels


 def 				UpperCamelCase_     (       self:	Any	):




   '''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 				UpperCamelCase_     (       self:	List[str],   a_:	Any,   a_:	Optional[int],   a_:	Dict,   a_:	Any	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						MobileViTModel(config=a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	Optional[Any]			=						model(a_	)
   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 				UpperCamelCase_     (       self:	Dict,   a_:	Optional[int],   a_:	Tuple,   a_:	List[str],   a_:	List[Any]	):




   '''simple docstring'''



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


 def 				UpperCamelCase_     (       self:	str,   a_:	Any,   a_:	Union[str, Any],   a_:	Tuple,   a_:	int	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						self.num_labels
   _snake_case							:	Tuple			=						MobileViTForSemanticSegmentation(a_	)
   model.to(a_	)
   model.eval()
   _snake_case							:	int			=						model(a_	)
   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							:	Tuple			=						model(a_,   labels=a_	)
   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 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   _snake_case							:	Any			=						self.prepare_config_and_inputs()
   _snake_case	,      _snake_case	,      _snake_case	,      _snake_case							:	Any			=						config_and_inputs
   _snake_case							:	Any			=						{"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_torch
class       lowercase(  __a ,    __a ,    unittest.TestCase				):







 '''simple docstring'''





 lowercase__				      =      (
     (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 lowercase__				      =      (
     {
         "feature-extraction": MobileViTModel,
         "image-classification": MobileViTForImageClassification,
         "image-segmentation": MobileViTForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False
 lowercase__				      =      False


 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						MobileViTModelTester(self	)
   _snake_case							:	Dict			=						MobileViTConfigTester(self,   config_class=a_,   has_text_modality=a_	)


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   self.config_tester.run_common_tests()


 @unittest.skip(reason="""MobileViT does not use inputs_embeds"""	)
 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   pass


 @unittest.skip(reason="""MobileViT does not support input and output embeddings"""	)
 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   pass


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




   '''simple docstring'''



   pass


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''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							:	Any			=						model_class(a_	)
     _snake_case							:	Union[str, Any]			=						inspect.signature(model.forward	)
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     _snake_case							:	List[Any]			=						[*signature.parameters.keys()]

     _snake_case							:	List[Any]			=						["""pixel_values"""]
     self.assertListEqual(arg_names[:1],   a_	)


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




   '''simple docstring'''



   pass


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	int			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_	)


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



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

     with torch.no_grad():
       _snake_case							:	Union[str, Any]			=						model(**self._prepare_for_class(a_,   a_	)	)

     _snake_case							:	List[Any]			=						outputs.hidden_states

     _snake_case							:	Any			=						5
     self.assertEqual(len(a_	),   a_	)

     # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
     # with the width and height being successively divided by 2.
     _snake_case							:	Union[str, Any]			=						2
     for i in range(len(a_	)	):
       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							:	List[Any]			=						True
     check_hidden_states_output(a_,   a_,   a_	)

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

     check_hidden_states_output(a_,   a_,   a_	)


 def 				UpperCamelCase_     (       self:	Tuple	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*a_	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Dict			=						self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*a_	)


 @slow
 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:	List[str]			=						MobileViTModel.from_pretrained(a_	)
     self.assertIsNotNone(a_	)







def       UpperCAmelCase__ ():
  """simple docstring"""

  _snake_case							:	Optional[Any]			=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
  return image






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







 '''simple docstring'''





 @cached_property
 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



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


 @slow
 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""	).to(a_	)

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

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

   # verify the logits
   _snake_case							:	List[str]			=						torch.Size((1, 1_000)	)
   self.assertEqual(outputs.logits.shape,   a_	)

   _snake_case							:	str			=						torch.tensor([-1.9_364, -1.2_327, -0.4_653]	).to(a_	)

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


 @slow
 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[int]			=						MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""	)
   _snake_case							:	Union[str, Any]			=						model.to(a_	)

   _snake_case							:	int			=						MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""	)

   _snake_case							:	List[Any]			=						prepare_img()
   _snake_case							:	str			=						image_processor(images=a_,   return_tensors="""pt"""	).to(a_	)

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

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

   _snake_case							:	Optional[Any]			=						torch.tensor(
       [
           [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
           [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
           [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
       ],   device=a_,   )

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


 @slow
 def 				UpperCamelCase_     (       self:	str	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""	)
   _snake_case							:	Dict			=						model.to(a_	)

   _snake_case							:	str			=						MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""	)

   _snake_case							:	Any			=						prepare_img()
   _snake_case							:	Tuple			=						image_processor(images=a_,   return_tensors="""pt"""	).to(a_	)

   # forward pass
   with torch.no_grad():
     _snake_case							:	Tuple			=						model(**a_	)

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

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

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








"""simple docstring"""


from abc import ABC, abstractmethod
from argparse import ArgumentParser






class       lowercase(  __a				):







 '''simple docstring'''





 @staticmethod
 @abstractmethod
 def 				UpperCamelCase_     (       a_:	ArgumentParser	):




   '''simple docstring'''



   raise NotImplementedError()


 @abstractmethod
 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   raise NotImplementedError()


