






'''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 UpperCAmelCase_       (     __A					):




      """simple docstring"""




      def 					A__   (			self      :		Optional[Any]		)	->	Tuple:


       '''simple docstring'''

       lowercase       : Dict						=self.config_class(**self.inputs_dict		)
       self.parent.assertTrue(hasattr(UpperCAmelCase  ,   '''hidden_sizes'''		)		)
       self.parent.assertTrue(hasattr(UpperCAmelCase  ,   '''neck_hidden_sizes'''		)		)
       self.parent.assertTrue(hasattr(UpperCAmelCase  ,   '''num_attention_heads'''		)		)





class UpperCAmelCase_       :




      """simple docstring"""




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


       '''simple docstring'''

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






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


       '''simple docstring'''

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

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

       lowercase       : int						=self.get_config()

       return config, pixel_values, labels, pixel_labels






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


       '''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 					A__   (			self      :		str  ,   UpperCAmelCase      :		str  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		Optional[int]		)	->	Union[str, Any]:


       '''simple docstring'''

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


       '''simple docstring'''

       lowercase       : Dict						=self.num_labels
       lowercase       : List[str]						=MobileViTForImageClassification(UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Dict						=model(UpperCAmelCase  ,   labels=UpperCAmelCase		)
       self.parent.assertEqual(result.logits.shape  ,   (self.batch_size, self.num_labels)		)






      def 					A__   (			self      :		Optional[int]  ,   UpperCAmelCase      :		Optional[int]  ,   UpperCAmelCase      :		Union[str, Any]  ,   UpperCAmelCase      :		int  ,   UpperCAmelCase      :		Dict		)	->	str:


       '''simple docstring'''

       lowercase       : Union[str, Any]						=self.num_labels
       lowercase       : List[str]						=MobileViTForSemanticSegmentation(UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase       : Any						=model(UpperCAmelCase		)
       self.parent.assertEqual(
           result.logits.shape  ,   (
               self.batch_size,
               self.num_labels,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )  ,   )
       lowercase       : Optional[int]						=model(UpperCAmelCase  ,   labels=UpperCAmelCase		)
       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 					A__   (			self      :		Optional[Any]		)	->	List[Any]:


       '''simple docstring'''

       lowercase       : str						=self.prepare_config_and_inputs()
       lowercase	,		lowercase	,		lowercase	,		lowercase       : List[str]						=config_and_inputs
       lowercase       : Dict						={'''pixel_values''': pixel_values}
       return config, inputs_dict





@require_torch
class UpperCAmelCase_       (     __A					,							__A					,							unittest.TestCase					):




      """simple docstring"""




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

      UpperCamelCase_             =      False
      UpperCamelCase_             =      False
      UpperCamelCase_             =      False
      UpperCamelCase_             =      False






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


       '''simple docstring'''

       lowercase       : Any						=MobileViTModelTester(self		)
       lowercase       : Dict						=MobileViTConfigTester(self  ,   config_class=UpperCAmelCase  ,   has_text_modality=UpperCAmelCase		)






      def 					A__   (			self      :		Tuple		)	->	Tuple:


       '''simple docstring'''

       self.config_tester.run_common_tests()






      @unittest.skip(reason='''MobileViT does not use inputs_embeds'''		)
      def 					A__   (			self      :		Tuple		)	->	Optional[int]:


       '''simple docstring'''

       pass






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


       '''simple docstring'''

       pass






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


       '''simple docstring'''

       pass






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


       '''simple docstring'''

       lowercase	,		lowercase       : Optional[int]						=self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowercase       : Tuple						=model_class(UpperCAmelCase		)
        lowercase       : Union[str, Any]						=inspect.signature(model.forward		)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowercase       : str						=[*signature.parameters.keys()]

        lowercase       : Optional[Any]						=['''pixel_values''']
        self.assertListEqual(arg_names[:1]  ,   UpperCAmelCase		)






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


       '''simple docstring'''

       pass






      def 					A__   (			self      :		Dict		)	->	Tuple:


       '''simple docstring'''

       lowercase       : Tuple						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase		)






      def 					A__   (			self      :		Tuple		)	->	int:


       '''simple docstring'''

       def check_hidden_states_output(UpperCAmelCase      :		Dict  ,   UpperCAmelCase      :		List[str]  ,   UpperCAmelCase      :		Optional[Any]		):
        lowercase       : Union[str, Any]						=model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()

        with torch.no_grad():
         lowercase       : Any						=model(**self._prepare_for_class(UpperCAmelCase  ,   UpperCAmelCase		)		)

        lowercase       : Optional[Any]						=outputs.hidden_states

        lowercase       : Dict						=5
        self.assertEqual(len(UpperCAmelCase		)  ,   UpperCAmelCase		)

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

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

       for model_class in self.all_model_classes:
        lowercase       : Dict						=True
        check_hidden_states_output(UpperCAmelCase  ,   UpperCAmelCase  ,   UpperCAmelCase		)

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

        check_hidden_states_output(UpperCAmelCase  ,   UpperCAmelCase  ,   UpperCAmelCase		)






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


       '''simple docstring'''

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






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


       '''simple docstring'''

       lowercase       : List[str]						=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase		)






      @slow
      def 					A__   (			self      :		List[str]		)	->	Optional[int]:


       '''simple docstring'''

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





def 				lowercase_					(     )							->   Optional[Any]:



 """simple docstring"""




 lowercase       : Optional[int]						=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
 return image





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




      """simple docstring"""




      @cached_property
      def 					A__   (			self      :		Dict		)	->	Optional[int]:


       '''simple docstring'''

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






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


       '''simple docstring'''

       lowercase       : int						=MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''		).to(UpperCAmelCase		)

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

       # forward pass
       with torch.no_grad():
        lowercase       : str						=model(**UpperCAmelCase		)

       # verify the logits
       lowercase       : Optional[Any]						=torch.Size((1, 1000)		)
       self.assertEqual(outputs.logits.shape  ,   UpperCAmelCase		)

       lowercase       : Tuple						=torch.tensor([-1.9_3_6_4, -1.2_3_2_7, -0.4_6_5_3]		).to(UpperCAmelCase		)

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






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


       '''simple docstring'''

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

       lowercase       : List[Any]						=MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''		)

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

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

       # verify the logits
       lowercase       : Tuple						=torch.Size((1, 21, 32, 32)		)
       self.assertEqual(logits.shape  ,   UpperCAmelCase		)

       lowercase       : int						=torch.tensor(
           [
               [[6.9_7_1_3, 6.9_7_8_6, 7.2_4_2_2], [7.2_8_9_3, 7.2_8_2_5, 7.4_4_4_6], [7.6_5_8_0, 7.8_7_9_7, 7.9_4_2_0]],
               [[-1_0.6_8_6_9, -1_0.3_2_5_0, -1_0.3_4_7_1], [-1_0.4_2_2_8, -9.9_8_6_8, -9.7_1_3_2], [-1_1.0_4_0_5, -1_1.0_2_2_1, -1_0.7_3_1_8]],
               [[-3.3_0_8_9, -2.8_5_3_9, -2.6_7_4_0], [-3.2_7_0_6, -2.5_6_2_1, -2.5_1_0_8], [-3.2_5_3_4, -2.6_6_1_5, -2.6_6_5_1]],
           ]  ,   device=UpperCAmelCase  ,   )

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






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


       '''simple docstring'''

       lowercase       : Any						=MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''		)
       lowercase       : Any						=model.to(UpperCAmelCase		)

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

       lowercase       : str						=prepare_img()
       lowercase       : Tuple						=image_processor(images=UpperCAmelCase  ,   return_tensors='''pt'''		).to(UpperCAmelCase		)

       # forward pass
       with torch.no_grad():
        lowercase       : str						=model(**UpperCAmelCase		)

       lowercase       : List[str]						=outputs.logits.detach().cpu()

       lowercase       : int						=image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase  ,   target_sizes=[(50, 60)]		)
       lowercase       : Dict						=torch.Size((50, 60)		)
       self.assertEqual(segmentation[0].shape  ,   UpperCAmelCase		)

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







from __future__ import annotations



def       _lowerCAmelCase    (				lowerCAmelCase_				:int		,    lowerCAmelCase_				:int				)->list[str]:
   '''simple docstring'''






   if partitions <= 0:
      raise ValueError("partitions must be a positive number!"				)
   if partitions > number_of_bytes:
      raise ValueError("partitions can not > number_of_bytes!"				)
   snake_case_            =       number_of_bytes // partitions
   snake_case_            =       []
   for i in range(lowerCAmelCase_				):
      snake_case_            =       i * bytes_per_partition + 1
      snake_case_            =       (
          number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
      )
      allocation_list.append(F'''{start_bytes}-{end_bytes}'''				)
   return allocation_list


if __name__ == "__main__":
   import doctest

   doctest.testmod()




