





'''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       a_   (				_lowerCAmelCase							):





     def 							lowercase__      ( self		:					str						):





        """simple docstring"""




        lowercase_			:List[Any]    			= self.config_class(**self.inputs_dict						)
        self.parent.assertTrue(hasattr(__a	,      "width_multiplier"						)						)







class       a_   :





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





        """simple docstring"""




        lowercase_			:Optional[int]    			= parent
        lowercase_			:List[Any]    			= batch_size
        lowercase_			:Any    			= image_size
        lowercase_			:int    			= patch_size
        lowercase_			:int    			= num_channels
        lowercase_			:Tuple    			= make_divisible(512 * width_multiplier	,      divisor=8						)
        lowercase_			:int    			= hidden_act
        lowercase_			:Any    			= conv_kernel_size
        lowercase_			:int    			= output_stride
        lowercase_			:str    			= classifier_dropout_prob
        lowercase_			:Union[str, Any]    			= use_labels
        lowercase_			:Dict    			= is_training
        lowercase_			:Union[str, Any]    			= num_labels
        lowercase_			:int    			= initializer_range
        lowercase_			:List[str]    			= scope
        lowercase_			:Union[str, Any]    			= width_multiplier
        lowercase_			:List[str]    			= ffn_dropout
        lowercase_			:Any    			= attn_dropout





     def 							lowercase__      ( self		:					List[str]						):





        """simple docstring"""




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

        lowercase_			:Tuple    			= None
        lowercase_			:Optional[Any]    			= 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_			:Optional[int]    			= self.get_config()

        return config, pixel_values, labels, pixel_labels





     def 							lowercase__      ( self		:					Optional[Any]						):





        """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		:					str	,      lowercase		:					Optional[int]	,      lowercase		:					str	,      lowercase		:					Tuple	,      lowercase		:					List[Any]						):





        """simple docstring"""




        lowercase_			:Union[str, Any]    			= MobileViTVaModel(config=__a						)
        model.to(__a						)
        model.eval()
        lowercase_			:Any    			= model(__a						)
        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		:					str	,      lowercase		:					Any	,      lowercase		:					Optional[int]	,      lowercase		:					List[str]	,      lowercase		:					Tuple						):





        """simple docstring"""




        lowercase_			:int    			= self.num_labels
        lowercase_			:Tuple    			= MobileViTVaForImageClassification(__a						)
        model.to(__a						)
        model.eval()
        lowercase_			:int    			= model(__a	,      labels=__a						)
        self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)						)





     def 							lowercase__      ( self		:					List[Any]	,      lowercase		:					Optional[Any]	,      lowercase		:					Dict	,      lowercase		:					Dict	,      lowercase		:					List[str]						):





        """simple docstring"""




        lowercase_			:Any    			= self.num_labels
        lowercase_			:List[Any]    			= MobileViTVaForSemanticSegmentation(__a						)
        model.to(__a						)
        model.eval()
        lowercase_			:List[str]    			= model(__a						)
        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_			:Tuple    			= model(__a	,      labels=__a						)
        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		:					Union[str, Any]						):





        """simple docstring"""




        lowercase_			:Dict    			= self.prepare_config_and_inputs()
        lowercase_			,							lowercase_			,							lowercase_			,							lowercase_			:int    			= config_and_inputs
        lowercase_			:Optional[int]    			= {"pixel_values": pixel_values}
        return config, inputs_dict







@require_torch
class       a_   (				_lowerCAmelCase	,						_lowerCAmelCase	,						unittest.TestCase							):
     __A      =			(
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

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

     __A      =			False
     __A      =			False
     __A      =			False
     __A      =			False





     def 							lowercase__      ( self		:					List[str]						):





        """simple docstring"""




        lowercase_			:List[Any]    			= MobileViTVaModelTester(self						)
        lowercase_			:Tuple    			= MobileViTVaConfigTester(self	,      config_class=__a	,      has_text_modality=__a						)





     def 							lowercase__      ( self		:					Optional[int]						):





        """simple docstring"""




        self.config_tester.run_common_tests()





     @unittest.skip(reason="MobileViTV2 does not use inputs_embeds"						)
     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        pass





     @unittest.skip(reason="MobileViTV2 does not support input and output embeddings"						)
     def 							lowercase__      ( self		:					Union[str, Any]						):





        """simple docstring"""




        pass





     @unittest.skip(reason="MobileViTV2 does not output attentions"						)
     def 							lowercase__      ( self		:					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		:					Any						):





        """simple docstring"""




        pass





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





        """simple docstring"""




        pass





     def 							lowercase__      ( self		:					Tuple						):





        """simple docstring"""




        lowercase_			,							lowercase_			:Dict    			= self.model_tester.prepare_config_and_inputs_for_common()

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

           lowercase_			:str    			= ["pixel_values"]
           self.assertListEqual(arg_names[:1]	,      __a						)





     def 							lowercase__      ( self		:					int						):





        """simple docstring"""




        lowercase_			:List[Any]    			= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__a						)





     def 							lowercase__      ( self		:					int						):





        """simple docstring"""




        def check_hidden_states_output(lowercase		:					Tuple	,      lowercase		:					Optional[int]	,      lowercase		:					str						):
           lowercase_			:List[Any]    			= model_class(__a						)
           model.to(__a						)
           model.eval()

           with torch.no_grad():
              lowercase_			:Any    			= model(**self._prepare_for_class(__a	,      __a						)						)

           lowercase_			:Union[str, Any]    			= outputs.hidden_states

           lowercase_			:List[str]    			= 5
           self.assertEqual(len(__a						)	,      __a						)

           # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
           # with the width and height being successively divided by 2.
           lowercase_			:Tuple    			= 2
           for i in range(len(__a						)						):
              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_			:str    			= self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowercase_			:Tuple    			= True
           check_hidden_states_output(__a	,      __a	,      __a						)

           # check that output_hidden_states also work using config
           del inputs_dict["output_hidden_states"]
           lowercase_			:Optional[int]    			= True

           check_hidden_states_output(__a	,      __a	,      __a						)





     def 							lowercase__      ( self		:					List[str]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*__a						)





     def 							lowercase__      ( self		:					Dict						):





        """simple docstring"""




        lowercase_			:Union[str, Any]    			= self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*__a						)







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





        """simple docstring"""




        for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase_			:Tuple    			= MobileViTVaModel.from_pretrained(__a						)
           self.assertIsNotNone(__a						)







def 							UpperCAmelCase_  (						):
   lowercase_			:Optional[int]    			= Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
   return image


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





     @cached_property
     def 							lowercase__      ( self		:					Dict						):





        """simple docstring"""




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





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





        """simple docstring"""




        lowercase_			:Optional[Any]    			= MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"						).to(
            __a						)

        lowercase_			:int    			= self.default_image_processor
        lowercase_			:List[Any]    			= prepare_img()
        lowercase_			:List[Any]    			= image_processor(images=__a	,      return_tensors="pt"						).to(__a						)

        # forward pass
        with torch.no_grad():
           lowercase_			:Dict    			= model(**__a						)

        # verify the logits
        lowercase_			:Optional[Any]    			= torch.Size((1, 1_000)						)
        self.assertEqual(outputs.logits.shape	,      __a						)

        lowercase_			:Dict    			= torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]						).to(__a						)

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





     @slow
     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:Any    			= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)
        lowercase_			:Optional[Any]    			= model.to(__a						)

        lowercase_			:int    			= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)

        lowercase_			:str    			= prepare_img()
        lowercase_			:Any    			= image_processor(images=__a	,      return_tensors="pt"						).to(__a						)

        # forward pass
        with torch.no_grad():
           lowercase_			:Tuple    			= model(**__a						)
        lowercase_			:Dict    			= outputs.logits

        # verify the logits
        lowercase_			:Optional[int]    			= torch.Size((1, 21, 32, 32)						)
        self.assertEqual(logits.shape	,      __a						)

        lowercase_			:Dict    			= torch.tensor(
            [
                [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
                [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
                [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
            ]	,      device=__a	,      )

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







     @slow
     def 							lowercase__      ( self		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:int    			= MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)
        lowercase_			:int    			= model.to(__a						)

        lowercase_			:Union[str, Any]    			= MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"						)

        lowercase_			:List[Any]    			= prepare_img()
        lowercase_			:Dict    			= image_processor(images=__a	,      return_tensors="pt"						).to(__a						)

        # forward pass
        with torch.no_grad():
           lowercase_			:Optional[Any]    			= model(**__a						)

        lowercase_			:Optional[Any]    			= outputs.logits.detach().cpu()

        lowercase_			:Dict    			= image_processor.post_process_semantic_segmentation(outputs=__a	,      target_sizes=[(50, 60)]						)
        lowercase_			:List[str]    			= torch.Size((50, 60)						)
        self.assertEqual(segmentation[0].shape	,      __a						)

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




"""simple docstring"""





from __future__ import annotations



def       lowerCamelCase__		(			__snake_case,     __snake_case,     __snake_case	)							->		int | float:


					"""simple docstring"""





					if len(__snake_case	) == 0:
										raise ValueError('''find_max() arg is an empty sequence'''	)
					if (
					    left >= len(__snake_case	)
					    or left < -len(__snake_case	)
					    or right >= len(__snake_case	)
					    or right < -len(__snake_case	)
					):
										raise IndexError('''list index out of range'''	)
					if left == right:
										return nums[left]
					_UpperCamelCase							 =  (left + right) >> 1  # the middle
					_UpperCamelCase							 =  find_max(__snake_case,     __snake_case,     __snake_case	)  # find max in range[left, mid]
					_UpperCamelCase							 =  find_max(__snake_case,     mid + 1,     __snake_case	)  # find max in range[mid + 1, right]

					return left_max if left_max >= right_max else right_max


if __name__ == "__main__":
				import doctest

				doctest.testmod(verbose=True)






