


'''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 			a       (	_a ):


     """simple docstring"""






     def 				lowerCamelCase__				(       self  :	int    )		->							str:
          __UpperCAmelCase			:				List[Any]													=    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 			a       :


     """simple docstring"""






     def __init__(       self  :	int							,				snake_case  :	Optional[Any]							,				snake_case  :	Any=13							,				snake_case  :	Tuple=32							,				snake_case  :	Dict=2							,				snake_case  :	Dict=3							,				snake_case  :	List[Any]=640							,				snake_case  :	List[str]=4							,				snake_case  :	Any="silu"							,				snake_case  :	Union[str, Any]=3							,				snake_case  :	Tuple=32							,				snake_case  :	Optional[int]=0.1							,				snake_case  :	Optional[Any]=0.1							,				snake_case  :	Dict=0.1							,				snake_case  :	str=0.02							,				snake_case  :	Optional[Any]=True							,				snake_case  :	Dict=True							,				snake_case  :	Dict=10							,				snake_case  :	Optional[int]=None							,				)		->							Tuple:
          __UpperCAmelCase			:				List[Any]													=    parent
          __UpperCAmelCase			:				Optional[Any]													=    batch_size
          __UpperCAmelCase			:				Tuple													=    image_size
          __UpperCAmelCase			:				int													=    patch_size
          __UpperCAmelCase			:				Any													=    num_channels
          __UpperCAmelCase			:				Dict													=    last_hidden_size
          __UpperCAmelCase			:				Any													=    num_attention_heads
          __UpperCAmelCase			:				Optional[int]													=    hidden_act
          __UpperCAmelCase			:				List[str]													=    conv_kernel_size
          __UpperCAmelCase			:				List[str]													=    output_stride
          __UpperCAmelCase			:				Any													=    hidden_dropout_prob
          __UpperCAmelCase			:				Tuple													=    attention_probs_dropout_prob
          __UpperCAmelCase			:				List[Any]													=    classifier_dropout_prob
          __UpperCAmelCase			:				List[Any]													=    use_labels
          __UpperCAmelCase			:				List[Any]													=    is_training
          __UpperCAmelCase			:				Any													=    num_labels
          __UpperCAmelCase			:				Optional[Any]													=    initializer_range
          __UpperCAmelCase			:				str													=    scope

     def 				lowerCamelCase__				(       self  :	Dict    )		->							List[str]:
          __UpperCAmelCase			:				Dict													=    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

          __UpperCAmelCase			:				List[Any]													=    self.get_config()

          return config, pixel_values, labels, pixel_labels

     def 				lowerCamelCase__				(       self  :	Tuple    )		->							Union[str, Any]:
          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  :	Optional[int]							,				snake_case  :	Optional[Any]							,				snake_case  :	Optional[int]							,				snake_case  :	Union[str, Any]							,				snake_case  :	Any    )		->							Tuple:
          __UpperCAmelCase			:				Any													=    MobileViTModel(config=snake_case    )
          model.to(snake_case    )
          model.eval()
          __UpperCAmelCase			:				Tuple													=    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  :	Dict							,				snake_case  :	Union[str, Any]							,				snake_case  :	str							,				snake_case  :	Dict							,				snake_case  :	Tuple    )		->							Any:
          __UpperCAmelCase			:				List[Any]													=    self.num_labels
          __UpperCAmelCase			:				Optional[Any]													=    MobileViTForImageClassification(snake_case    )
          model.to(snake_case    )
          model.eval()
          __UpperCAmelCase			:				Any													=    model(snake_case							,				labels=snake_case    )
          self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.num_labels)    )

     def 				lowerCamelCase__				(       self  :	List[Any]							,				snake_case  :	int							,				snake_case  :	int							,				snake_case  :	Any							,				snake_case  :	Dict    )		->							Tuple:
          __UpperCAmelCase			:				Union[str, Any]													=    self.num_labels
          __UpperCAmelCase			:				List[str]													=    MobileViTForSemanticSegmentation(snake_case    )
          model.to(snake_case    )
          model.eval()
          __UpperCAmelCase			:				Optional[int]													=    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,
              )							,				)
          __UpperCAmelCase			:				Optional[Any]													=    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  :	Dict    )		->							Tuple:
          __UpperCAmelCase			:				Optional[Any]													=    self.prepare_config_and_inputs()
          __UpperCAmelCase							,     __UpperCAmelCase							,     __UpperCAmelCase							,     __UpperCAmelCase			:				Any													=    config_and_inputs
          __UpperCAmelCase			:				Optional[int]													=    {'''pixel_values''': pixel_values}
          return config, inputs_dict



@require_torch
class 			a       (	_a			,						_a			,						unittest.TestCase ):


     """simple docstring"""






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

     SCREAMING_SNAKE_CASE :				Optional[Any]							     =     False
     SCREAMING_SNAKE_CASE :				int							     =     False
     SCREAMING_SNAKE_CASE :				List[Any]							     =     False
     SCREAMING_SNAKE_CASE :				int							     =     False

     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							Optional[Any]:
          __UpperCAmelCase			:				Optional[int]													=    MobileViTModelTester(self    )
          __UpperCAmelCase			:				Optional[int]													=    MobileViTConfigTester(self							,				config_class=snake_case							,				has_text_modality=snake_case    )

     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							Any:
          self.config_tester.run_common_tests()

     @unittest.skip(reason='''MobileViT does not use inputs_embeds'''    )
     def 				lowerCamelCase__				(       self  :	List[str]    )		->							Union[str, Any]:
          pass

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

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

     def 				lowerCamelCase__				(       self  :	Any    )		->							Optional[int]:
          __UpperCAmelCase							,     __UpperCAmelCase			:				str													=    self.model_tester.prepare_config_and_inputs_for_common()

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

               __UpperCAmelCase			:				str													=    ['''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  :	Any    )		->							Optional[int]:
          pass

     def 				lowerCamelCase__				(       self  :	str    )		->							Any:
          __UpperCAmelCase			:				Tuple													=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case    )

     def 				lowerCamelCase__				(       self  :	List[str]    )		->							Dict:
          def check_hidden_states_output(snake_case  :	str							,				snake_case  :	Optional[int]							,				snake_case  :	Any    ):
               __UpperCAmelCase			:				Union[str, Any]													=    model_class(snake_case    )
               model.to(snake_case    )
               model.eval()

               with torch.no_grad():
                    __UpperCAmelCase			:				Tuple													=    model(**self._prepare_for_class(snake_case							,				snake_case    )    )

               __UpperCAmelCase			:				str													=    outputs.hidden_states

               __UpperCAmelCase			:				Dict													=    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.
               __UpperCAmelCase			:				int													=    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    )

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

          for model_class in self.all_model_classes:
               __UpperCAmelCase			:				List[Any]													=    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"]
               __UpperCAmelCase			:				List[Any]													=    True

               check_hidden_states_output(snake_case							,				snake_case							,				snake_case    )

     def 				lowerCamelCase__				(       self  :	Tuple    )		->							Dict:
          __UpperCAmelCase			:				Optional[Any]													=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case    )

     def 				lowerCamelCase__				(       self  :	Union[str, Any]    )		->							List[Any]:
          __UpperCAmelCase			:				Tuple													=    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*snake_case    )






     @slow
     def 				lowerCamelCase__				(       self  :	Optional[Any]    )		->							Optional[int]:
          for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase			:				Optional[int]													=    MobileViTModel.from_pretrained(snake_case    )
               self.assertIsNotNone(snake_case    )




def 			_a			(		):





     '''simple docstring'''






     __UpperCAmelCase			:				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 				lowerCamelCase__				(       self  :	Union[str, Any]    )		->							Optional[Any]:
          return MobileViTImageProcessor.from_pretrained('''apple/mobilevit-xx-small'''    ) if is_vision_available() else None

     @slow
     def 				lowerCamelCase__				(       self  :	int    )		->							List[str]:
          __UpperCAmelCase			:				str													=    MobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''    ).to(snake_case    )

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

          # forward pass
          with torch.no_grad():
               __UpperCAmelCase			:				Tuple													=    model(**snake_case    )

          # verify the logits
          __UpperCAmelCase			:				List[Any]													=    torch.Size((1, 1000)    )
          self.assertEqual(outputs.logits.shape							,				snake_case    )

          __UpperCAmelCase			:				Optional[Any]													=    torch.tensor([-1.9_364, -1.2_327, -0.4_653]    ).to(snake_case    )

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

     @slow
     def 				lowerCamelCase__				(       self  :	Optional[int]    )		->							Any:
          __UpperCAmelCase			:				Dict													=    MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''    )
          __UpperCAmelCase			:				Dict													=    model.to(snake_case    )

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

          __UpperCAmelCase			:				Any													=    prepare_img()
          __UpperCAmelCase			:				Tuple													=    image_processor(images=snake_case							,				return_tensors='''pt'''    ).to(snake_case    )

          # forward pass
          with torch.no_grad():
               __UpperCAmelCase			:				Any													=    model(**snake_case    )
          __UpperCAmelCase			:				List[str]													=    outputs.logits

          # verify the logits
          __UpperCAmelCase			:				Union[str, Any]													=    torch.Size((1, 21, 32, 32)    )
          self.assertEqual(logits.shape							,				snake_case    )

          __UpperCAmelCase			:				Tuple													=    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=snake_case							,				)

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






     @slow
     def 				lowerCamelCase__				(       self  :	int    )		->							Union[str, Any]:
          __UpperCAmelCase			:				Optional[int]													=    MobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''    )
          __UpperCAmelCase			:				Tuple													=    model.to(snake_case    )

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

          __UpperCAmelCase			:				Optional[int]													=    prepare_img()
          __UpperCAmelCase			:				Dict													=    image_processor(images=snake_case							,				return_tensors='''pt'''    ).to(snake_case    )

          # forward pass
          with torch.no_grad():
               __UpperCAmelCase			:				Any													=    model(**snake_case    )

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

          __UpperCAmelCase			:				List[Any]													=    image_processor.post_process_semantic_segmentation(outputs=snake_case							,				target_sizes=[(50, 60)]    )
          __UpperCAmelCase			:				Tuple													=    torch.Size((50, 60)    )
          self.assertEqual(segmentation[0].shape							,				snake_case    )

          __UpperCAmelCase			:				Optional[int]													=    image_processor.post_process_semantic_segmentation(outputs=snake_case    )
          __UpperCAmelCase			:				List[str]													=    torch.Size((32, 32)    )
          self.assertEqual(segmentation[0].shape							,				snake_case    )



'''simple docstring'''



from __future__ import annotations




def 			_a			(		_lowercase      :			list						):





     '''simple docstring'''






     if not nums:
          raise ValueError('''List is empty'''						)
     return sum(_lowercase						) / len(_lowercase						)


if __name__ == "__main__":
      import doctest

      doctest.testmod()