



"""simple docstring"""





import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    IMAGE_PROCESSOR_MAPPING,
    AutoConfig,
    AutoImageProcessor,
    CLIPConfig,
    CLIPImageProcessor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER


sys.path.append(str(Path(__file__).parent.parent.parent.parent / """utils"""))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_image_processing import CustomImageProcessor  # noqa E402
class    lowercase__     (					unittest.TestCase   ):







       '''simple docstring'''


       def   lowercase__       (							self    :						int					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							0



       def   lowercase__       (							self    :						int					)				->		str:


             '''simple docstring'''




             UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32"					)
             self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		List[str]:


             '''simple docstring'''




             with tempfile.TemporaryDirectory() as tmpdirname:
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "preprocessor_config.json"
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "config.json"
                   json.dump(
                       {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,       open(_UpperCAmelCase	,       "w"					)	,       )
                   json.dump({"model_type": "clip"}	,       open(_UpperCAmelCase	,       "w"					)					)

                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					)
                   self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)



       def   lowercase__       (							self    :						Any					)				->		Any:


             '''simple docstring'''




             with tempfile.TemporaryDirectory() as tmpdirname:
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "preprocessor_config.json"
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "config.json"
                   json.dump(
                       {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}	,       open(_UpperCAmelCase	,       "w"					)	,       )
                   json.dump({"model_type": "clip"}	,       open(_UpperCAmelCase	,       "w"					)					)

                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					)
                   self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)



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


             '''simple docstring'''




             with tempfile.TemporaryDirectory() as tmpdirname:
                   UpperCAmelCase_    				=							CLIPConfig()

                   # Create a dummy config file with image_proceesor_type
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "preprocessor_config.json"
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "config.json"
                   json.dump(
                       {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,       open(_UpperCAmelCase	,       "w"					)	,       )
                   json.dump({"model_type": "clip"}	,       open(_UpperCAmelCase	,       "w"					)					)

                   # remove image_processor_type to make sure config.json alone is enough to load image processor locally
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					).to_dict()

                   config_dict.pop("image_processor_type"					)
                   UpperCAmelCase_    				=							CLIPImageProcessor(**_UpperCAmelCase					)

                   # save in new folder
                   model_config.save_pretrained(_UpperCAmelCase					)
                   config.save_pretrained(_UpperCAmelCase					)

                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					)

                   # make sure private variable is not incorrectly saved
                   UpperCAmelCase_    				=							json.loads(config.to_json_string()					)
                   self.assertTrue("_processor_class" not in dict_as_saved					)

             self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)



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


             '''simple docstring'''




             with tempfile.TemporaryDirectory() as tmpdirname:
                   UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "preprocessor_config.json"
                   json.dump(
                       {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"}	,       open(_UpperCAmelCase	,       "w"					)	,       )

                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					)
                   self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)



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


             '''simple docstring'''




             with self.assertRaisesRegex(
                 _UpperCAmelCase	,       "clip-base is not a local folder and is not a valid model identifier"					):
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained("clip-base"					)



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


             '''simple docstring'''




             with self.assertRaisesRegex(
                 _UpperCAmelCase	,       r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"					):
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase	,       revision="aaaaaa"					)



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


             '''simple docstring'''




             with self.assertRaisesRegex(
                 _UpperCAmelCase	,       "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."	,       ):
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model"					)



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


             '''simple docstring'''




             with self.assertRaises(_UpperCAmelCase					):
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"					)
             # If remote code is disabled, we can't load this config.
             with self.assertRaises(_UpperCAmelCase					):
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(
                       "hf-internal-testing/test_dynamic_image_processor"	,       trust_remote_code=_UpperCAmelCase					)

             UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(
                 "hf-internal-testing/test_dynamic_image_processor"	,       trust_remote_code=_UpperCAmelCase					)
             self.assertEqual(image_processor.__class__.__name__	,       "NewImageProcessor"					)

             # Test image processor can be reloaded.
             with tempfile.TemporaryDirectory() as tmp_dir:
                   image_processor.save_pretrained(_UpperCAmelCase					)
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase	,       trust_remote_code=_UpperCAmelCase					)
             self.assertEqual(reloaded_image_processor.__class__.__name__	,       "NewImageProcessor"					)



       def   lowercase__       (							self    :						str					)				->		Any:


             '''simple docstring'''




             try:
                   AutoConfig.register("custom"	,       _UpperCAmelCase					)
                   AutoImageProcessor.register(_UpperCAmelCase	,       _UpperCAmelCase					)
                   # Trying to register something existing in the Transformers library will raise an error
                   with self.assertRaises(_UpperCAmelCase					):
                         AutoImageProcessor.register(_UpperCAmelCase	,       _UpperCAmelCase					)

                   with tempfile.TemporaryDirectory() as tmpdirname:
                         UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "preprocessor_config.json"
                         UpperCAmelCase_    				=							Path(_UpperCAmelCase					) / "config.json"
                         json.dump(
                             {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"}	,       open(_UpperCAmelCase	,       "w"					)	,       )
                         json.dump({"model_type": "clip"}	,       open(_UpperCAmelCase	,       "w"					)					)

                         UpperCAmelCase_    				=							CustomImageProcessor.from_pretrained(_UpperCAmelCase					)

                   # Now that the config is registered, it can be used as any other config with the auto-API
                   with tempfile.TemporaryDirectory() as tmp_dir:
                         image_processor.save_pretrained(_UpperCAmelCase					)
                         UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(_UpperCAmelCase					)
                         self.assertIsInstance(_UpperCAmelCase	,       _UpperCAmelCase					)

             finally:
                   if "custom" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["custom"]
                   if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                         del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]







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


             '''simple docstring'''




             class    lowercase__     (					SCREAMING_SNAKE_CASE   ):







                    '''simple docstring'''


                    UpperCamelCase		=  True

             try:
                   AutoConfig.register("custom"	,       _UpperCAmelCase					)
                   AutoImageProcessor.register(_UpperCAmelCase	,       _UpperCAmelCase					)
                   # If remote code is not set, the default is to use local
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor"					)
                   self.assertEqual(image_processor.__class__.__name__	,       "NewImageProcessor"					)
                   self.assertTrue(image_processor.is_local					)

                   # If remote code is disabled, we load the local one.
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(
                       "hf-internal-testing/test_dynamic_image_processor"	,       trust_remote_code=_UpperCAmelCase					)
                   self.assertEqual(image_processor.__class__.__name__	,       "NewImageProcessor"					)
                   self.assertTrue(image_processor.is_local					)

                   # If remote is enabled, we load from the Hub
                   UpperCAmelCase_    				=							AutoImageProcessor.from_pretrained(
                       "hf-internal-testing/test_dynamic_image_processor"	,       trust_remote_code=_UpperCAmelCase					)
                   self.assertEqual(image_processor.__class__.__name__	,       "NewImageProcessor"					)
                   self.assertTrue(not hasattr(_UpperCAmelCase	,       "is_local"					)					)

             finally:
                   if "custom" in CONFIG_MAPPING._extra_content:
                         del CONFIG_MAPPING._extra_content["custom"]
                   if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content:
                         del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]









"""simple docstring"""





import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
  from transformers.models.mobilevitva.modeling_mobilevitva import (
      MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
      make_divisible,
  )


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor
class    lowercase__     (					SCREAMING_SNAKE_CASE   ):







       '''simple docstring'''


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


             '''simple docstring'''




             UpperCAmelCase_    				=							self.config_class(**self.inputs_dict					)
             self.parent.assertTrue(hasattr(_UpperCAmelCase	,       "width_multiplier"					)					)



class    lowercase__     :







       '''simple docstring'''


       def __init__(							self    :						Optional[Any]	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Optional[int]=13	,       _UpperCAmelCase    :						Any=64	,       _UpperCAmelCase    :						Union[str, Any]=2	,       _UpperCAmelCase    :						Any=3	,       _UpperCAmelCase    :						Dict="swish"	,       _UpperCAmelCase    :						List[Any]=3	,       _UpperCAmelCase    :						int=32	,       _UpperCAmelCase    :						str=0.1	,       _UpperCAmelCase    :						Tuple=0.02	,       _UpperCAmelCase    :						List[Any]=True	,       _UpperCAmelCase    :						Any=True	,       _UpperCAmelCase    :						int=10	,       _UpperCAmelCase    :						Optional[int]=None	,       _UpperCAmelCase    :						Any=0.25	,       _UpperCAmelCase    :						Any=0.0	,       _UpperCAmelCase    :						Optional[int]=0.0	,       )				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							parent
             UpperCAmelCase_    				=							batch_size
             UpperCAmelCase_    				=							image_size
             UpperCAmelCase_    				=							patch_size
             UpperCAmelCase_    				=							num_channels
             UpperCAmelCase_    				=							make_divisible(512 * width_multiplier	,       divisor=8					)
             UpperCAmelCase_    				=							hidden_act
             UpperCAmelCase_    				=							conv_kernel_size
             UpperCAmelCase_    				=							output_stride
             UpperCAmelCase_    				=							classifier_dropout_prob
             UpperCAmelCase_    				=							use_labels
             UpperCAmelCase_    				=							is_training
             UpperCAmelCase_    				=							num_labels
             UpperCAmelCase_    				=							initializer_range
             UpperCAmelCase_    				=							scope
             UpperCAmelCase_    				=							width_multiplier
             UpperCAmelCase_    				=							ffn_dropout
             UpperCAmelCase_    				=							attn_dropout



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


             '''simple docstring'''




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

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

             UpperCAmelCase_    				=							self.get_config()

             return config, pixel_values, labels, pixel_labels



       def   lowercase__       (							self    :						Tuple					)				->		Tuple:


             '''simple docstring'''




             return MobileViTVaConfig(
                 image_size=self.image_size	,       patch_size=self.patch_size	,       num_channels=self.num_channels	,       hidden_act=self.hidden_act	,       conv_kernel_size=self.conv_kernel_size	,       output_stride=self.output_stride	,       classifier_dropout_prob=self.classifier_dropout_prob	,       initializer_range=self.initializer_range	,       width_multiplier=self.width_multiplier	,       ffn_dropout=self.ffn_dropout_prob	,       attn_dropout=self.attn_dropout_prob	,       )



       def   lowercase__       (							self    :						List[str]	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						Optional[Any]	,       _UpperCAmelCase    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaModel(config=_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							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   lowercase__       (							self    :						Optional[int]	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Any	,       _UpperCAmelCase    :						str	,       _UpperCAmelCase    :						Tuple					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.num_labels
             UpperCAmelCase_    				=							MobileViTVaForImageClassification(_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							model(_UpperCAmelCase	,       labels=_UpperCAmelCase					)
             self.parent.assertEqual(result.logits.shape	,       (self.batch_size, self.num_labels)					)



       def   lowercase__       (							self    :						Any	,       _UpperCAmelCase    :						int	,       _UpperCAmelCase    :						Optional[int]	,       _UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Tuple					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.num_labels
             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation(_UpperCAmelCase					)
             model.to(_UpperCAmelCase					)
             model.eval()
             UpperCAmelCase_    				=							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,
                 )	,       )
             UpperCAmelCase_    				=							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   lowercase__       (							self    :						List[str]					)				->		Tuple:


             '''simple docstring'''




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



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







       '''simple docstring'''


       UpperCamelCase		=  (
           (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )

       UpperCamelCase		=  (
           {
               '''feature-extraction''': MobileViTVaModel,
               '''image-classification''': MobileViTVaForImageClassification,
               '''image-segmentation''': MobileViTVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       UpperCamelCase		=  False
       UpperCamelCase		=  False
       UpperCamelCase		=  False
       UpperCamelCase		=  False



       def   lowercase__       (							self    :						str					)				->		Dict:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaModelTester(self					)
             UpperCAmelCase_    				=							MobileViTVaConfigTester(self	,       config_class=_UpperCAmelCase	,       has_text_modality=_UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		List[str]:


             '''simple docstring'''




             self.config_tester.run_common_tests()



       @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"					)
       def   lowercase__       (							self    :						List[Any]					)				->		List[str]:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"					)
       def   lowercase__       (							self    :						Tuple					)				->		Dict:


             '''simple docstring'''




             pass



       @unittest.skip(reason="MobileViTV2 does not output attentions"					)
       def   lowercase__       (							self    :						Optional[int]					)				->		List[Any]:


             '''simple docstring'''




             pass



       @require_torch_multi_gpu
       @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."					)
       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             pass



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


             '''simple docstring'''




             pass



       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_				,					UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs_for_common()

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

                   UpperCAmelCase_    				=							["pixel_values"]
                   self.assertListEqual(arg_names[:1]	,       _UpperCAmelCase					)



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


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*_UpperCAmelCase					)



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


             '''simple docstring'''




             def check_hidden_states_output(_UpperCAmelCase    :						List[Any]	,       _UpperCAmelCase    :						Union[str, Any]	,       _UpperCAmelCase    :						int					):
                   UpperCAmelCase_    				=							model_class(_UpperCAmelCase					)
                   model.to(_UpperCAmelCase					)
                   model.eval()

                   with torch.no_grad():
                         UpperCAmelCase_    				=							model(**self._prepare_for_class(_UpperCAmelCase	,       _UpperCAmelCase					)					)

                   UpperCAmelCase_    				=							outputs.hidden_states

                   UpperCAmelCase_    				=							5
                   self.assertEqual(len(_UpperCAmelCase					)	,       _UpperCAmelCase					)

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

             UpperCAmelCase_				,					UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   UpperCAmelCase_    				=							True
                   check_hidden_states_output(_UpperCAmelCase	,       _UpperCAmelCase	,       _UpperCAmelCase					)

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   UpperCAmelCase_    				=							True

                   check_hidden_states_output(_UpperCAmelCase	,       _UpperCAmelCase	,       _UpperCAmelCase					)



       def   lowercase__       (							self    :						int					)				->		int:


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase					)



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


             '''simple docstring'''




             UpperCAmelCase_    				=							self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*_UpperCAmelCase					)







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


             '''simple docstring'''




             for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   UpperCAmelCase_    				=							MobileViTVaModel.from_pretrained(_UpperCAmelCase					)
                   self.assertIsNotNone(_UpperCAmelCase					)



def      a__			(   ):
      UpperCAmelCase_    				=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
      return image


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







       '''simple docstring'''


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


             '''simple docstring'''




             return (
                 MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					)
                 if is_vision_available()
                 else None
             )



       @slow
       def   lowercase__       (							self    :						Union[str, Any]					)				->		Tuple:


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"					).to(
                 _UpperCAmelCase					)

             UpperCAmelCase_    				=							self.default_image_processor
             UpperCAmelCase_    				=							prepare_img()
             UpperCAmelCase_    				=							image_processor(images=_UpperCAmelCase	,       return_tensors="pt"					).to(_UpperCAmelCase					)

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_    				=							model(**_UpperCAmelCase					)

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

             UpperCAmelCase_    				=							torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]					).to(_UpperCAmelCase					)

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



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


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
             UpperCAmelCase_    				=							model.to(_UpperCAmelCase					)

             UpperCAmelCase_    				=							MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

             UpperCAmelCase_    				=							prepare_img()
             UpperCAmelCase_    				=							image_processor(images=_UpperCAmelCase	,       return_tensors="pt"					).to(_UpperCAmelCase					)

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_    				=							model(**_UpperCAmelCase					)
             UpperCAmelCase_    				=							outputs.logits

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

             UpperCAmelCase_    				=							torch.tensor(
                 [
                     [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                     [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                     [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
                 ]	,       device=_UpperCAmelCase	,       )

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







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


             '''simple docstring'''




             UpperCAmelCase_    				=							MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)
             UpperCAmelCase_    				=							model.to(_UpperCAmelCase					)

             UpperCAmelCase_    				=							MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"					)

             UpperCAmelCase_    				=							prepare_img()
             UpperCAmelCase_    				=							image_processor(images=_UpperCAmelCase	,       return_tensors="pt"					).to(_UpperCAmelCase					)

             # forward pass
             with torch.no_grad():
                   UpperCAmelCase_    				=							model(**_UpperCAmelCase					)

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

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

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




