

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 SCREAMING_SNAKE_CASE      (    __A					):
  """simple docstring"""






  def 			SCREAMING_SNAKE_CASE       (     self					:       List[str]       )				->      Dict:






     """simple docstring"""







     __lowerCAmelCase    :     Optional[int]          =		self.config_class(**self.inputs_dict       )
     self.parent.assertTrue(hasattr(lowerCAmelCase			,				"""hidden_sizes"""       )       )
     self.parent.assertTrue(hasattr(lowerCAmelCase			,				"""neck_hidden_sizes"""       )       )
     self.parent.assertTrue(hasattr(lowerCAmelCase			,				"""num_attention_heads"""       )       )






class SCREAMING_SNAKE_CASE      :
  """simple docstring"""






  def __init__(     self					:       int			,				lowerCAmelCase					:       str			,				lowerCAmelCase					:       Union[str, Any]=13			,				lowerCAmelCase					:       Dict=32			,				lowerCAmelCase					:       Optional[Any]=2			,				lowerCAmelCase					:       str=3			,				lowerCAmelCase					:       Optional[Any]=6_40			,				lowerCAmelCase					:       List[str]=4			,				lowerCAmelCase					:       Optional[int]="silu"			,				lowerCAmelCase					:       Optional[int]=3			,				lowerCAmelCase					:       str=32			,				lowerCAmelCase					:       List[Any]=0.1			,				lowerCAmelCase					:       Optional[Any]=0.1			,				lowerCAmelCase					:       Optional[int]=0.1			,				lowerCAmelCase					:       Any=0.02			,				lowerCAmelCase					:       int=True			,				lowerCAmelCase					:       Dict=True			,				lowerCAmelCase					:       Dict=10			,				lowerCAmelCase					:       Optional[int]=None			,				)				->      Dict:






     """simple docstring"""







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







  def 			SCREAMING_SNAKE_CASE       (     self					:       Dict       )				->      Optional[Any]:






     """simple docstring"""







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

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

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

     return config, pixel_values, labels, pixel_labels







  def 			SCREAMING_SNAKE_CASE       (     self					:       Optional[Any]       )				->      Optional[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 			SCREAMING_SNAKE_CASE       (     self					:       Optional[Any]			,				lowerCAmelCase					:       Optional[Any]			,				lowerCAmelCase					:       Optional[int]			,				lowerCAmelCase					:       Optional[int]			,				lowerCAmelCase					:       Tuple       )				->      Any:






     """simple docstring"""







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






     """simple docstring"""







     __lowerCAmelCase    :     str          =		self.num_labels
     __lowerCAmelCase    :     Union[str, Any]          =		MobileViTForImageClassification(lowerCAmelCase       )
     model.to(lowerCAmelCase       )
     model.eval()
     __lowerCAmelCase    :     Optional[int]          =		model(lowerCAmelCase			,				labels=lowerCAmelCase       )
     self.parent.assertEqual(result.logits.shape			,				(self.batch_size, self.num_labels)       )







  def 			SCREAMING_SNAKE_CASE       (     self					:       Optional[int]			,				lowerCAmelCase					:       List[str]			,				lowerCAmelCase					:       Tuple			,				lowerCAmelCase					:       Optional[int]			,				lowerCAmelCase					:       Dict       )				->      int:






     """simple docstring"""







     __lowerCAmelCase    :     Union[str, Any]          =		self.num_labels
     __lowerCAmelCase    :     Union[str, Any]          =		MobileViTForSemanticSegmentation(lowerCAmelCase       )
     model.to(lowerCAmelCase       )
     model.eval()
     __lowerCAmelCase    :     Tuple          =		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,
         )			,				)
     __lowerCAmelCase    :     Tuple          =		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					:       Union[str, Any]       )				->      Optional[Any]:






     """simple docstring"""







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






@require_torch
class SCREAMING_SNAKE_CASE      (    __A  ,				__A  ,				unittest.TestCase					):
  """simple docstring"""






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

  lowerCamelCase       :     Tuple		 =False
  lowerCamelCase       :     Optional[Any]		 =False
  lowerCamelCase       :     str		 =False
  lowerCamelCase       :     List[Any]		 =False







  def 			SCREAMING_SNAKE_CASE       (     self					:       str       )				->      List[Any]:






     """simple docstring"""







     __lowerCAmelCase    :     Optional[int]          =		MobileViTModelTester(self       )
     __lowerCAmelCase    :     Tuple          =		MobileViTConfigTester(self			,				config_class=lowerCAmelCase			,				has_text_modality=lowerCAmelCase       )







  def 			SCREAMING_SNAKE_CASE       (     self					:       Tuple       )				->      Dict:






     """simple docstring"""







     self.config_tester.run_common_tests()







  @unittest.skip(reason="""MobileViT does not use inputs_embeds"""       )
  def 			SCREAMING_SNAKE_CASE       (     self					:       List[Any]       )				->      int:






     """simple docstring"""







     pass







  @unittest.skip(reason="""MobileViT does not support input and output embeddings"""       )
  def 			SCREAMING_SNAKE_CASE       (     self					:       Any       )				->      Tuple:






     """simple docstring"""







     pass







  @unittest.skip(reason="""MobileViT does not output attentions"""       )
  def 			SCREAMING_SNAKE_CASE       (     self					:       Union[str, Any]       )				->      str:






     """simple docstring"""







     pass







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






     """simple docstring"""







     __lowerCAmelCase    :     Dict          =		self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase    :     Union[str, Any]          =		["pixel_values"]
        self.assertListEqual(arg_names[:1]			,				lowerCAmelCase       )







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






     """simple docstring"""







     pass







  def 			SCREAMING_SNAKE_CASE       (     self					:       Tuple       )				->      List[str]:






     """simple docstring"""







     __lowerCAmelCase    :     Tuple          =		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase       )







  def 			SCREAMING_SNAKE_CASE       (     self					:       str       )				->      Tuple:






     """simple docstring"""







     def check_hidden_states_output(lowerCAmelCase					:       Tuple			,				lowerCAmelCase					:       Tuple			,				lowerCAmelCase					:       Optional[Any]       ):
        __lowerCAmelCase    :     str          =		model_class(lowerCAmelCase       )
        model.to(lowerCAmelCase       )
        model.eval()

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

        __lowerCAmelCase    :     List[str]          =		outputs.hidden_states

        __lowerCAmelCase    :     Optional[Any]          =		5
        self.assertEqual(len(lowerCAmelCase       )			,				lowerCAmelCase       )

        # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
        # with the width and height being successively divided by 2.
        __lowerCAmelCase    :     Union[str, Any]          =		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       )

     __lowerCAmelCase    :     Tuple          =		self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __lowerCAmelCase    :     Dict          =		True
        check_hidden_states_output(lowerCAmelCase			,				lowerCAmelCase			,				lowerCAmelCase       )

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

        check_hidden_states_output(lowerCAmelCase			,				lowerCAmelCase			,				lowerCAmelCase       )







  def 			SCREAMING_SNAKE_CASE       (     self					:       Tuple       )				->      int:






     """simple docstring"""







     __lowerCAmelCase    :     Dict          =		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase       )







  def 			SCREAMING_SNAKE_CASE       (     self					:       str       )				->      Tuple:






     """simple docstring"""







     __lowerCAmelCase    :     Dict          =		self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase       )







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






     """simple docstring"""







     for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __lowerCAmelCase    :     List[Any]          =		MobileViTModel.from_pretrained(lowerCAmelCase       )
        self.assertIsNotNone(lowerCAmelCase       )






def       snake_case_ ()     ->      Tuple:
   __lowerCAmelCase    :     Tuple          =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
   return image



@require_torch
@require_vision
class SCREAMING_SNAKE_CASE      (    unittest.TestCase					):
  """simple docstring"""






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






     """simple docstring"""







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







  @slow
  def 			SCREAMING_SNAKE_CASE       (     self					:       Dict       )				->      Tuple:






     """simple docstring"""







     __lowerCAmelCase    :     int          =		MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""       ).to(lowerCAmelCase       )

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

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

     # verify the logits
     __lowerCAmelCase    :     Tuple          =		torch.Size((1, 10_00)       )
     self.assertEqual(outputs.logits.shape			,				lowerCAmelCase       )

     __lowerCAmelCase    :     Union[str, Any]          =		torch.tensor([-1.9364, -1.2327, -0.4653]       ).to(lowerCAmelCase       )

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







  @slow
  def 			SCREAMING_SNAKE_CASE       (     self					:       int       )				->      Dict:






     """simple docstring"""







     __lowerCAmelCase    :     List[Any]          =		MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""       )
     __lowerCAmelCase    :     Optional[int]          =		model.to(lowerCAmelCase       )

     __lowerCAmelCase    :     Union[str, Any]          =		MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""       )

     __lowerCAmelCase    :     Tuple          =		prepare_img()
     __lowerCAmelCase    :     Tuple          =		image_processor(images=lowerCAmelCase			,				return_tensors="""pt"""       ).to(lowerCAmelCase       )

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase    :     Optional[int]          =		model(**lowerCAmelCase       )
     __lowerCAmelCase    :     Optional[int]          =		outputs.logits

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

     __lowerCAmelCase    :     Any          =		torch.tensor(
         [
             [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
             [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
             [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
         ]			,				device=lowerCAmelCase			,				)

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







  @slow
  def 			SCREAMING_SNAKE_CASE       (     self					:       Dict       )				->      List[str]:






     """simple docstring"""







     __lowerCAmelCase    :     Optional[int]          =		MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""       )
     __lowerCAmelCase    :     List[str]          =		model.to(lowerCAmelCase       )

     __lowerCAmelCase    :     Dict          =		MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""       )

     __lowerCAmelCase    :     Optional[int]          =		prepare_img()
     __lowerCAmelCase    :     List[str]          =		image_processor(images=lowerCAmelCase			,				return_tensors="""pt"""       ).to(lowerCAmelCase       )

     # forward pass
     with torch.no_grad():
        __lowerCAmelCase    :     Optional[int]          =		model(**lowerCAmelCase       )

     __lowerCAmelCase    :     int          =		outputs.logits.detach().cpu()

     __lowerCAmelCase    :     int          =		image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase			,				target_sizes=[(50, 60)]       )
     __lowerCAmelCase    :     List[str]          =		torch.Size((50, 60)       )
     self.assertEqual(segmentation[0].shape			,				lowerCAmelCase       )

     __lowerCAmelCase    :     int          =		image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase       )
     __lowerCAmelCase    :     Tuple          =		torch.Size((32, 32)       )
     self.assertEqual(segmentation[0].shape			,				lowerCAmelCase       )





from operator import delitem, getitem, setitem

import pytest

from data_structures.hashing.hash_map import HashMap

def 			lowerCamelCase__			(       _a):
	return getitem, k

def 			lowerCamelCase__			(       _a				,      _a):
	return setitem, k, v

def 			lowerCamelCase__			(       _a):
	return delitem, k

def 			lowerCamelCase__			(       _a				,      _a				,      *_a):
	try:
		return fun(_a				,      *_a), None
	except Exception as e:
		return None, e


a_      =     (
    _set('key_a', 'val_a'),
    _set('key_b', 'val_b'),
)

a_      =     [
    _set('key_a', 'val_a'),
    _set('key_a', 'val_b'),
]

a_      =     [
    _set('key_a', 'val_a'),
    _set('key_b', 'val_b'),
    _del('key_a'),
    _del('key_b'),
    _set('key_a', 'val_a'),
    _del('key_a'),
]

a_      =     [
    _get('key_a'),
    _del('key_a'),
    _set('key_a', 'val_a'),
    _del('key_a'),
    _del('key_a'),
    _get('key_a'),
]

a_      =     [
    *[_set(x, x) for x in range(5)],  # guaranteed upsize
]

a_      =     [
    *[_set(x, x) for x in range(5)],  # guaranteed upsize
    *[_del(x) for x in range(5)],
    _set('key_a', 'val_b'),
]

@pytest.mark.parametrize(
    "operations"				,      (
        pytest.param(_add_items				,      id="add items"),
        pytest.param(_overwrite_items				,      id="overwrite items"),
        pytest.param(_delete_items				,      id="delete items"),
        pytest.param(_access_absent_items				,      id="access absent items"),
        pytest.param(_add_with_resize_up				,      id="add with resize up"),
        pytest.param(_add_with_resize_down				,      id="add with resize down"),
    )				,      )
def 			lowerCamelCase__			(       _a):
	SCREAMING_SNAKE_CASE :   Dict					  =							HashMap(initial_block_size=4)
	SCREAMING_SNAKE_CASE :   List[str]					  =							{}
	for _, (fun, *args) in enumerate(_a):
		SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							_run_operation(_a				,      _a				,      *_a)
		SCREAMING_SNAKE_CASE  ,SCREAMING_SNAKE_CASE :   List[Any]					  =							_run_operation(_a				,      _a				,      *_a)
		assert my_res == py_res
		assert str(_a) == str(_a)
		assert set(_a) == set(_a)
		assert len(_a) == len(_a)
		assert set(my.items()) == set(py.items())


def 			lowerCamelCase__			(       ):
	def is_public(_a) -> bool:
		return not name.startswith("_")

	SCREAMING_SNAKE_CASE :   List[str]					  =							{name for name in dir({}) if is_public(_a)}
	SCREAMING_SNAKE_CASE :   Union[str, Any]					  =							{name for name in dir(HashMap()) if is_public(_a)}

	assert dict_public_names > hash_public_names