"""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 SCREAMING_SNAKE_CASE  (     _SCREAMING_SNAKE_CASE						):







 """simple docstring"""


 def 							_lowerCAmelCase					( self		:   str					)					->      str:




    '''simple docstring'''






    a__  					=		self.config_class(**self.inputs_dict					)
    self.parent.assertTrue(hasattr(_snake_case       , 'hidden_sizes'					)					)
    self.parent.assertTrue(hasattr(_snake_case       , 'neck_hidden_sizes'					)					)
    self.parent.assertTrue(hasattr(_snake_case       , 'num_attention_heads'					)					)

class SCREAMING_SNAKE_CASE  :







 """simple docstring"""


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




    '''simple docstring'''






    a__  					=		parent
    a__  					=		batch_size
    a__  					=		image_size
    a__  					=		patch_size
    a__  					=		num_channels
    a__  					=		last_hidden_size
    a__  					=		num_attention_heads
    a__  					=		hidden_act
    a__  					=		conv_kernel_size
    a__  					=		output_stride
    a__  					=		hidden_dropout_prob
    a__  					=		attention_probs_dropout_prob
    a__  					=		classifier_dropout_prob
    a__  					=		use_labels
    a__  					=		is_training
    a__  					=		num_labels
    a__  					=		initializer_range
    a__  					=		scope


 def 							_lowerCAmelCase					( self		:   int					)					->      Dict:




    '''simple docstring'''






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

    a__  					=		None
    a__  					=		None
    if self.use_labels:
       a__  					=		ids_tensor([self.batch_size]       , self.num_labels					)
       a__  					=		ids_tensor([self.batch_size, self.image_size, self.image_size]       , self.num_labels					)

    a__  					=		self.get_config()

    return config, pixel_values, labels, pixel_labels


 def 							_lowerCAmelCase					( self		:   Union[str, Any]					)					->      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 							_lowerCAmelCase					( self		:   List[str]       , _snake_case		:   Any       , _snake_case		:   Dict       , _snake_case		:   Union[str, Any]       , _snake_case		:   Optional[Any]					)					->      Optional[Any]:




    '''simple docstring'''






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




    '''simple docstring'''






    a__  					=		self.num_labels
    a__  					=		MobileViTForImageClassification(_snake_case					)
    model.to(_snake_case					)
    model.eval()
    a__  					=		model(_snake_case       , labels=_snake_case					)
    self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_labels)					)


 def 							_lowerCAmelCase					( self		:   Union[str, Any]       , _snake_case		:   Optional[Any]       , _snake_case		:   Optional[Any]       , _snake_case		:   Union[str, Any]       , _snake_case		:   List[str]					)					->      Union[str, Any]:




    '''simple docstring'''






    a__  					=		self.num_labels
    a__  					=		MobileViTForSemanticSegmentation(_snake_case					)
    model.to(_snake_case					)
    model.eval()
    a__  					=		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,
        )       , )
    a__  					=		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 							_lowerCAmelCase					( self		:   Optional[Any]					)					->      Tuple:




    '''simple docstring'''






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

@require_torch
class SCREAMING_SNAKE_CASE  (     _SCREAMING_SNAKE_CASE ,   _SCREAMING_SNAKE_CASE ,   unittest.TestCase						):







 """simple docstring"""


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

 a_							:						Union[str, Any]	      =False
 a_							:						Any	      =False
 a_							:						str	      =False
 a_							:						List[Any]	      =False


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




    '''simple docstring'''






    a__  					=		MobileViTModelTester(self					)
    a__  					=		MobileViTConfigTester(self       , config_class=_snake_case       , has_text_modality=_snake_case					)


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




    '''simple docstring'''






    self.config_tester.run_common_tests()


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




    '''simple docstring'''






    pass


 @unittest.skip(reason='MobileViT does not support input and output embeddings'					)
 def 							_lowerCAmelCase					( self		:   Dict					)					->      int:




    '''simple docstring'''






    pass


 @unittest.skip(reason='MobileViT does not output attentions'					)
 def 							_lowerCAmelCase					( self		:   List[Any]					)					->      Optional[int]:




    '''simple docstring'''






    pass


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




    '''simple docstring'''






    a__  					=		self.model_tester.prepare_config_and_inputs_for_common()

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

       a__  					=		["""pixel_values"""]
       self.assertListEqual(arg_names[:1]       , _snake_case					)


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




    '''simple docstring'''






    pass


 def 							_lowerCAmelCase					( self		:   Any					)					->      Dict:




    '''simple docstring'''






    a__  					=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*_snake_case					)


 def 							_lowerCAmelCase					( self		:   Dict					)					->      Optional[int]:




    '''simple docstring'''






    def check_hidden_states_output(_snake_case		:   Optional[Any]       , _snake_case		:   Optional[int]       , _snake_case		:   Optional[int]					):
       a__  					=		model_class(_snake_case					)
       model.to(_snake_case					)
       model.eval()

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

       a__  					=		outputs.hidden_states

       a__  					=		5
       self.assertEqual(len(_snake_case					)       , _snake_case					)

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

    a__  					=		self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       a__  					=		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"]
       a__  					=		True

       check_hidden_states_output(_snake_case       , _snake_case       , _snake_case					)


 def 							_lowerCAmelCase					( self		:   str					)					->      Dict:




    '''simple docstring'''






    a__  					=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*_snake_case					)


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




    '''simple docstring'''






    a__  					=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_semantic_segmentation(*_snake_case					)



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




    '''simple docstring'''






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





def 	_lowerCamelCase			(			)				->  int:


   '''simple docstring'''


   a__  					=		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 							_lowerCAmelCase					( self		:   Optional[int]					)					->      Tuple:




    '''simple docstring'''






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


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




    '''simple docstring'''






    a__  					=		MobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'					).to(_snake_case					)

    a__  					=		self.default_image_processor
    a__  					=		prepare_img()
    a__  					=		image_processor(images=_snake_case       , return_tensors='pt'					).to(_snake_case					)

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

    # verify the logits
    a__  					=		torch.Size((1, 1000)					)
    self.assertEqual(outputs.logits.shape       , _snake_case					)

    a__  					=		torch.tensor([-1.9364, -1.2327, -0.4653]					).to(_snake_case					)

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


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




    '''simple docstring'''






    a__  					=		MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'					)
    a__  					=		model.to(_snake_case					)

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

    a__  					=		prepare_img()
    a__  					=		image_processor(images=_snake_case       , return_tensors='pt'					).to(_snake_case					)

    # forward pass
    with torch.no_grad():
       a__  					=		model(**_snake_case					)
    a__  					=		outputs.logits

    # verify the logits
    a__  					=		torch.Size((1, 21, 32, 32)					)
    self.assertEqual(logits.shape       , _snake_case					)

    a__  					=		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=_snake_case       , )

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



 @slow
 def 							_lowerCAmelCase					( self		:   Union[str, Any]					)					->      Optional[Any]:




    '''simple docstring'''






    a__  					=		MobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'					)
    a__  					=		model.to(_snake_case					)

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

    a__  					=		prepare_img()
    a__  					=		image_processor(images=_snake_case       , return_tensors='pt'					).to(_snake_case					)

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

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

    a__  					=		image_processor.post_process_semantic_segmentation(outputs=_snake_case       , target_sizes=[(50, 60)]					)
    a__  					=		torch.Size((50, 60)					)
    self.assertEqual(segmentation[0].shape       , _snake_case					)

    a__  					=		image_processor.post_process_semantic_segmentation(outputs=_snake_case					)
    a__  					=		torch.Size((32, 32)					)
    self.assertEqual(segmentation[0].shape       , _snake_case					)






'''simple docstring'''






from collections.abc import Callable






class   __snake_case			:







    """simple docstring"""



    def __init__(  self       :    Tuple       ,		lowerCamelCase       :    Callable | None = None						)  ->    None:
      # Stores actual heap items.
      lowerCAmelCase_     : list     =  []
      # Stores indexes of each item for supporting updates and deletion.
      lowerCAmelCase_     : dict     =  {}
      # Stores current size of heap.
      lowerCAmelCase_     : List[Any]     =  0
      # Stores function used to evaluate the score of an item on which basis ordering
      # will be done.
      lowerCAmelCase_     : Tuple     =  key or (lambda lowerCamelCase						: x)

    def __lowercase  (  self       :    Optional[Any]       ,		lowerCamelCase       :    int						)  ->    int | None:
      return int((i - 1) / 2						) if i > 0 else None

    def __lowercase  (  self       :    Union[str, Any]       ,		lowerCamelCase       :    int						)  ->    int | None:
      lowerCAmelCase_     : List[str]     =  int(2 * i + 1						)
      return left if 0 < left < self.size else None

    def __lowercase  (  self       :    Optional[Any]       ,		lowerCamelCase       :    int						)  ->    int | None:
      lowerCAmelCase_     : List[Any]     =  int(2 * i + 2						)
      return right if 0 < right < self.size else None

    def __lowercase  (  self       :    List[str]       ,		lowerCamelCase       :    int       ,		lowerCamelCase       :    int						)  ->    None:
      lowerCAmelCase_,				lowerCAmelCase_     : Union[str, Any]     =  (
          self.pos_map[self.arr[j][0]],
          self.pos_map[self.arr[i][0]],
      )
      # Then swap the items in the list.
      lowerCAmelCase_,				lowerCAmelCase_     : List[Any]     =  self.arr[j], self.arr[i]

    def __lowercase  (  self       :    Tuple       ,		lowerCamelCase       :    int       ,		lowerCamelCase       :    int						)  ->    bool:
      return self.arr[i][1] < self.arr[j][1]

    def __lowercase  (  self       :    int       ,		lowerCamelCase       :    int						)  ->    int:
      lowerCAmelCase_     : List[str]     =  self._left(lowerCamelCase						)
      lowerCAmelCase_     : Optional[Any]     =  self._right(lowerCamelCase						)
      lowerCAmelCase_     : Tuple     =  i

      if left is not None and not self._cmp(lowerCamelCase       ,		lowerCamelCase						):
        lowerCAmelCase_     : int     =  left
      if right is not None and not self._cmp(lowerCamelCase       ,		lowerCamelCase						):
        lowerCAmelCase_     : Optional[Any]     =  right

      return valid_parent

    def __lowercase  (  self       :    List[Any]       ,		lowerCamelCase       :    int						)  ->    None:
      lowerCAmelCase_     : Tuple     =  self._parent(lowerCamelCase						)
      while parent is not None and not self._cmp(lowerCamelCase       ,		lowerCamelCase						):
        self._swap(lowerCamelCase       ,		lowerCamelCase						)
        lowerCAmelCase_,				lowerCAmelCase_     : str     =  parent, self._parent(lowerCamelCase						)

    def __lowercase  (  self       :    Tuple       ,		lowerCamelCase       :    int						)  ->    None:
      lowerCAmelCase_     : Optional[Any]     =  self._get_valid_parent(lowerCamelCase						)
      while valid_parent != index:
        self._swap(lowerCamelCase       ,		lowerCamelCase						)
        lowerCAmelCase_,				lowerCAmelCase_     : int     =  valid_parent, self._get_valid_parent(lowerCamelCase						)

    def __lowercase  (  self       :    Optional[Any]       ,		lowerCamelCase       :    int       ,		lowerCamelCase       :    int						)  ->    None:
      if item not in self.pos_map:
        return
      lowerCAmelCase_     : Dict     =  self.pos_map[item]
      lowerCAmelCase_     : Dict     =  [item, self.key(lowerCamelCase						)]
      # Make sure heap is right in both up and down direction.
      # Ideally only one of them will make any change.
      self._heapify_up(lowerCamelCase						)
      self._heapify_down(lowerCamelCase						)

    def __lowercase  (  self       :    int       ,		lowerCamelCase       :    int						)  ->    None:
      if item not in self.pos_map:
        return
      lowerCAmelCase_     : List[str]     =  self.pos_map[item]
      del self.pos_map[item]
      lowerCAmelCase_     : Tuple     =  self.arr[self.size - 1]
      lowerCAmelCase_     : List[str]     =  index
      self.size -= 1
      # Make sure heap is right in both up and down direction. Ideally only one
      # of them will make any change- so no performance loss in calling both.
      if self.size > index:
        self._heapify_up(lowerCamelCase						)
        self._heapify_down(lowerCamelCase						)

    def __lowercase  (  self       :    List[Any]       ,		lowerCamelCase       :    int       ,		lowerCamelCase       :    int						)  ->    None:
      lowerCAmelCase_     : Any     =  len(self.arr						)
      if arr_len == self.size:
        self.arr.append([item, self.key(lowerCamelCase						)]						)
      else:
        lowerCAmelCase_     : str     =  [item, self.key(lowerCamelCase						)]
      lowerCAmelCase_     : Optional[Any]     =  self.size
      self.size += 1
      self._heapify_up(self.size - 1						)

    def __lowercase  (  self       :    str						)  ->    tuple | None:
      return self.arr[0] if self.size else None





    def __lowercase  (  self       :    Optional[Any]						)  ->    tuple | None:
      lowerCAmelCase_     : int     =  self.get_top()
      if top_item_tuple:
        self.delete_item(top_item_tuple[0]						)
      return top_item_tuple







def 							UpperCamelCase_     (       ):
  '''simple docstring'''







if __name__ == "__main__":
  import doctest

  doctest.testmod()



