





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  A__    (							__UpperCAmelCase	):




   """simple docstring"""



   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	List[Any] =				self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(lowercase					,  'hidden_sizes'))
          self.parent.assertTrue(hasattr(lowercase					,  'neck_hidden_sizes'))
          self.parent.assertTrue(hasattr(lowercase					,  'num_attention_heads'))





class  A__    :




   """simple docstring"""



   def __init__(					self					,  lowercase					,  lowercase=13					,  lowercase=32					,  lowercase=2					,  lowercase=3					,  lowercase=640					,  lowercase=4					,  lowercase="silu"					,  lowercase=3					,  lowercase=32					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=0.1					,  lowercase=0.02					,  lowercase=True					,  lowercase=True					,  lowercase=10					,  lowercase=None					,  )			->						Dict:







          '''simple docstring'''

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

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	int =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          a__						:	Optional[Any] =				self.get_config()

          return config, pixel_values, labels, pixel_labels

   def 							__lowercase		(					self)			->						Union[str, 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 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						List[Any]:







          '''simple docstring'''

          a__						:	Dict =				MobileViTModel(config=lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	Optional[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					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Optional[Any] =				self.num_labels
          a__						:	Optional[Any] =				MobileViTForImageClassification(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	List[Any] =				model(lowercase					,  labels=lowercase)
          self.parent.assertEqual(result.logits.shape					,  (self.batch_size, self.num_labels))

   def 							__lowercase		(					self					,  lowercase					,  lowercase					,  lowercase					,  lowercase)			->						List[str]:







          '''simple docstring'''

          a__						:	Dict =				self.num_labels
          a__						:	str =				MobileViTForSemanticSegmentation(lowercase)
          model.to(lowercase)
          model.eval()
          a__						:	int =				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__						:	Any =				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)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	int =				self.prepare_config_and_inputs()
          a__ ,							a__ ,							a__ ,							a__						:	str =				config_and_inputs
          a__						:	Tuple =				{'pixel_values': pixel_values}
          return config, inputs_dict





@require_torch
class  A__    (							__UpperCAmelCase ,  __UpperCAmelCase ,  unittest.TestCase	):




   """simple docstring"""



   __A   :				List[str]         =  (
       (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __A   :				Dict         =  (
       {
           '''feature-extraction''': MobileViTModel,
           '''image-classification''': MobileViTForImageClassification,
           '''image-segmentation''': MobileViTForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A   :				Optional[int]         =  False
   __A   :				Tuple         =  False
   __A   :				Union[str, Any]         =  False
   __A   :				Optional[int]         =  False

   def 							__lowercase		(					self)			->						Any:







          '''simple docstring'''

          a__						:	Optional[int] =				MobileViTModelTester(self)
          a__						:	str =				MobileViTConfigTester(self					,  config_class=lowercase					,  has_text_modality=lowercase)

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







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='MobileViT does not use inputs_embeds')
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          pass

   @unittest.skip(reason='MobileViT does not support input and output embeddings')
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

          pass

   @unittest.skip(reason='MobileViT does not output attentions')
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__ ,							a__						:	Optional[Any] =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 a__						:	str =				['pixel_values']
                 self.assertListEqual(arg_names[:1]					,  lowercase)

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







          '''simple docstring'''

          pass

   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          a__						:	int =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase)

   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          def check_hidden_states_output(lowercase					,  lowercase					,  lowercase):
                 a__						:	List[str] =				model_class(lowercase)
                 model.to(lowercase)
                 model.eval()

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

                 a__						:	Any =				outputs.hidden_states

                 a__						:	Any =				5
                 self.assertEqual(len(lowercase)					,  lowercase)

                 # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
                 # with the width and height being successively divided by 2.
                 a__						:	str =				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__						:	Tuple =				self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__						:	Any =				True
                 check_hidden_states_output(lowercase					,  lowercase					,  lowercase)

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

                 check_hidden_states_output(lowercase					,  lowercase					,  lowercase)

   def 							__lowercase		(					self)			->						List[str]:







          '''simple docstring'''

          a__						:	int =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase)

   def 							__lowercase		(					self)			->						Union[str, Any]:







          '''simple docstring'''

          a__						:	Any =				self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*lowercase)

   @slow
   def 							__lowercase		(					self)			->						Optional[int]:







          '''simple docstring'''

          for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 a__						:	Optional[int] =				MobileViTModel.from_pretrained(lowercase)
                 self.assertIsNotNone(lowercase)



def A_	(		)  ->		Dict:
       a__						:	Optional[int] =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
       return image





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




   """simple docstring"""



   @cached_property
   def 							__lowercase		(					self)			->						List[Any]:







          '''simple docstring'''

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

   @slow
   def 							__lowercase		(					self)			->						int:







          '''simple docstring'''

          a__						:	Union[str, Any] =				MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small').to(lowercase)

          a__						:	List[Any] =				self.default_image_processor
          a__						:	List[str] =				prepare_img()
          a__						:	Any =				image_processor(images=lowercase					,  return_tensors='pt').to(lowercase)

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

          # verify the logits
          a__						:	List[str] =				torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape					,  lowercase)

          a__						:	List[Any] =				torch.tensor([-1.93_64, -1.23_27, -0.46_53]).to(lowercase)

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

   @slow
   def 							__lowercase		(					self)			->						Optional[Any]:







          '''simple docstring'''

          a__						:	str =				MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small')
          a__						:	Optional[int] =				model.to(lowercase)

          a__						:	str =				MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small')

          a__						:	str =				prepare_img()
          a__						:	Optional[Any] =				image_processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          # forward pass
          with torch.no_grad():
                 a__						:	Optional[Any] =				model(**lowercase)
          a__						:	List[Any] =				outputs.logits

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

          a__						:	List[Any] =				torch.tensor(
              [
                  [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
                  [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
                  [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
              ]					,  device=lowercase					,  )

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

   @slow
   def 							__lowercase		(					self)			->						str:







          '''simple docstring'''

          a__						:	List[Any] =				MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small')
          a__						:	str =				model.to(lowercase)

          a__						:	int =				MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small')

          a__						:	str =				prepare_img()
          a__						:	Dict =				image_processor(images=lowercase					,  return_tensors='pt').to(lowercase)

          # forward pass
          with torch.no_grad():
                 a__						:	Dict =				model(**lowercase)

          a__						:	str =				outputs.logits.detach().cpu()

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

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









from math import loga



def A_	(		A__				)  ->		int:
       if a < 0:
              raise ValueError('Input value must be a positive integer'				)
       elif isinstance(A__		,      A__				):
              raise TypeError('Input value must be a \'int\' type'				)
       return 0 if (a == 0) else int(loga(a & -a				)				)


if __name__ == "__main__":
    import doctest

    doctest.testmod()


