





import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
       from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileNetVaImageProcessor





class 			lowerCAmelCase__( __lowercase    ):






       '''simple docstring'''


       def     UpperCamelCase_			(      self							)			->     Optional[Any]:
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.config_class(**self.inputs_dict							)
            self.parent.assertTrue(hasattr(__lowerCamelCase    ,						"tf_padding"							)							)
            self.parent.assertTrue(hasattr(__lowerCamelCase    ,						"depth_multiplier"							)							)





class 			lowerCAmelCase__:






       '''simple docstring'''


       def __init__(      self    ,						__lowerCamelCase    ,						__lowerCamelCase=1_3    ,						__lowerCamelCase=3    ,						__lowerCamelCase=3_2    ,						__lowerCamelCase=0.25    ,						__lowerCamelCase=8    ,						__lowerCamelCase=8    ,						__lowerCamelCase=6    ,						__lowerCamelCase=3_2    ,						__lowerCamelCase=True    ,						__lowerCamelCase=True    ,						__lowerCamelCase=True    ,						__lowerCamelCase="relu6"    ,						__lowerCamelCase=1_2_8_0    ,						__lowerCamelCase=0.1    ,						__lowerCamelCase=0.02    ,						__lowerCamelCase=True    ,						__lowerCamelCase=True    ,						__lowerCamelCase=1_0    ,						__lowerCamelCase=None    ,						)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							parent
            _SCREAMING_SNAKE_CASE       :	List[str]						    =							batch_size
            _SCREAMING_SNAKE_CASE       :	int						    =							num_channels
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							image_size
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							depth_multiplier
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							depth_divisible_by
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							min_depth
            _SCREAMING_SNAKE_CASE       :	str						    =							expand_ratio
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							tf_padding
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							output_stride
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							first_layer_is_expansion
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							finegrained_output
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							hidden_act
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier							)
            _SCREAMING_SNAKE_CASE       :	int						    =							classifier_dropout_prob
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							use_labels
            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							is_training
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							num_labels
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							initializer_range
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							scope




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	int						    =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

            _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							None
            _SCREAMING_SNAKE_CASE       :	Dict						    =							None
            if self.use_labels:
                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							ids_tensor([self.batch_size]    ,						self.num_labels							)
                 _SCREAMING_SNAKE_CASE       :	List[str]						    =							ids_tensor([self.batch_size, self.image_size, self.image_size]    ,						self.num_labels							)

            _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.get_config()

            return config, pixel_values, labels, pixel_labels




       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            return MobileNetVaConfig(
                num_channels=self.num_channels    ,						image_size=self.image_size    ,						depth_multiplier=self.depth_multiplier    ,						depth_divisible_by=self.depth_divisible_by    ,						min_depth=self.min_depth    ,						expand_ratio=self.expand_ratio    ,						output_stride=self.output_stride    ,						first_layer_is_expansion=self.first_layer_is_expansion    ,						finegrained_output=self.finegrained_output    ,						hidden_act=self.hidden_act    ,						tf_padding=self.tf_padding    ,						classifier_dropout_prob=self.classifier_dropout_prob    ,						initializer_range=self.initializer_range    ,						)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     List[str]:
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							MobileNetVaModel(config=__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							model(__lowerCamelCase							)
            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,
                )    ,						)
            self.parent.assertEqual(
                result.pooler_output.shape    ,						(self.batch_size, self.last_hidden_size)    ,						)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.num_labels
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							MobileNetVaForImageClassification(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							model(__lowerCamelCase    ,						labels=__lowerCamelCase							)
            self.parent.assertEqual(result.logits.shape    ,						(self.batch_size, self.num_labels)							)




       def     UpperCamelCase_			(      self    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	Dict						    =							self.num_labels
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							MobileNetVaForSemanticSegmentation(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							model(__lowerCamelCase							)
            self.parent.assertEqual(
                result.logits.shape    ,						(
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                )    ,						)
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							model(__lowerCamelCase    ,						labels=__lowerCamelCase							)
            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     UpperCamelCase_			(      self							)			->     List[str]:
            _SCREAMING_SNAKE_CASE       :	int						    =							self.prepare_config_and_inputs()
            _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	Optional[int]						    =							config_and_inputs
            _SCREAMING_SNAKE_CASE       :	str						    =							{"pixel_values": pixel_values}
            return config, inputs_dict





@require_torch
class 			lowerCAmelCase__( __lowercase  ,     __lowercase  ,     unittest.TestCase    ):






       '''simple docstring'''


       __snake_case 			=    (
           (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       __snake_case 			=    (
           {
               'feature-extraction': MobileNetVaModel,
               'image-classification': MobileNetVaForImageClassification,
               'image-segmentation': MobileNetVaForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       __snake_case 			=    False
       __snake_case 			=    False
       __snake_case 			=    False
       __snake_case 			=    False




       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							MobileNetVaModelTester(self							)
            _SCREAMING_SNAKE_CASE       :	Any						    =							MobileNetVaConfigTester(self    ,						config_class=__lowerCamelCase    ,						has_text_modality=__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     int:
            self.config_tester.run_common_tests()




       @unittest.skip(reason="MobileNetV2 does not use inputs_embeds"							)
       def     UpperCamelCase_			(      self							)			->     List[Any]:
            pass




       @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"							)
       def     UpperCamelCase_			(      self							)			->     Optional[Any]:
            pass




       @unittest.skip(reason="MobileNetV2 does not output attentions"							)
       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            pass




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	int						    =							self.model_tester.prepare_config_and_inputs_for_common()

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

                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							["pixel_values"]
                 self.assertListEqual(arg_names[:1]    ,						__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     Any:
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            def check_hidden_states_output(__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							):
                 _SCREAMING_SNAKE_CASE       :	int						    =							model_class(__lowerCamelCase							)
                 model.to(__lowerCamelCase							)
                 model.eval()

                 with torch.no_grad():
                      _SCREAMING_SNAKE_CASE       :	Tuple						    =							model(**self._prepare_for_class(__lowerCamelCase    ,						__lowerCamelCase							)							)

                 _SCREAMING_SNAKE_CASE       :	Any						    =							outputs.hidden_states

                 _SCREAMING_SNAKE_CASE       :	List[Any]						    =							1_6
                 self.assertEqual(len(__lowerCamelCase							)    ,						__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE    ,			_SCREAMING_SNAKE_CASE       :	Any						    =							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 _SCREAMING_SNAKE_CASE       :	Dict						    =							True
                 check_hidden_states_output(__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							True

                 check_hidden_states_output(__lowerCamelCase    ,						__lowerCamelCase    ,						__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     Optional[Any]:
            _SCREAMING_SNAKE_CASE       :	List[Any]						    =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)




       def     UpperCamelCase_			(      self							)			->     Tuple:
            _SCREAMING_SNAKE_CASE       :	str						    =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase							)







       @slow
       def     UpperCamelCase_			(      self							)			->     Optional[int]:
            for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _SCREAMING_SNAKE_CASE       :	Any						    =							MobileNetVaModel.from_pretrained(__lowerCamelCase							)
                 self.assertIsNotNone(__lowerCamelCase							)






def     lowerCamelCase__			():
     _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
     return image





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






       '''simple docstring'''


       @cached_property
       def     UpperCamelCase_			(      self							)			->     Dict:
            return (
                MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"							) if is_vision_available() else None
            )




       @slow
       def     UpperCamelCase_			(      self							)			->     Dict:
            _SCREAMING_SNAKE_CASE       :	int						    =							MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"							).to(__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	str						    =							self.default_image_processor
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							prepare_img()
            _SCREAMING_SNAKE_CASE       :	str						    =							image_processor(images=__lowerCamelCase    ,						return_tensors="pt"							).to(__lowerCamelCase							)

            # forward pass
            with torch.no_grad():
                 _SCREAMING_SNAKE_CASE       :	str						    =							model(**__lowerCamelCase							)

            # verify the logits
            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.Size((1, 1_0_0_1)							)
            self.assertEqual(outputs.logits.shape    ,						__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							torch.tensor([0.2445, -1.1993, 0.1905]							).to(__lowerCamelCase							)

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







       @slow
       def     UpperCamelCase_			(      self							)			->     Union[str, Any]:
            _SCREAMING_SNAKE_CASE       :	Union[str, Any]						    =							MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)
            _SCREAMING_SNAKE_CASE       :	str						    =							model.to(__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	str						    =							MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"							)

            _SCREAMING_SNAKE_CASE       :	Optional[int]						    =							prepare_img()
            _SCREAMING_SNAKE_CASE       :	str						    =							image_processor(images=__lowerCamelCase    ,						return_tensors="pt"							).to(__lowerCamelCase							)

            # forward pass
            with torch.no_grad():
                 _SCREAMING_SNAKE_CASE       :	int						    =							model(**__lowerCamelCase							)
            _SCREAMING_SNAKE_CASE       :	Tuple						    =							outputs.logits

            # verify the logits
            _SCREAMING_SNAKE_CASE       :	str						    =							torch.Size((1, 2_1, 6_5, 6_5)							)
            self.assertEqual(logits.shape    ,						__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE       :	Tuple						    =							torch.tensor(
                [
                    [[17.5790, 17.7581, 18.3355], [18.3257, 18.4230, 18.8973], [18.6169, 18.8650, 19.2187]],
                    [[-2.1595, -2.0977, -2.3741], [-2.4226, -2.3028, -2.6835], [-2.7819, -2.5991, -2.7706]],
                    [[4.2058, 4.8317, 4.7638], [4.4136, 5.0361, 4.9383], [4.5028, 4.9644, 4.8734]],
                ]    ,						device=__lowerCamelCase    ,						)

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






def     lowerCamelCase__			(__lowerCamelCase,       __lowerCamelCase	):
     if a < 0 or b < 0:
          raise ValueError("the value of both inputs must be positive"	)
     _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							str(bin(__lowerCamelCase	)	)[2:]  # remove the leading "0b"
     _SCREAMING_SNAKE_CASE       :	List[str]						    =							str(bin(__lowerCamelCase	)	)[2:]
     _SCREAMING_SNAKE_CASE       :	Optional[Any]						    =							max(len(__lowerCamelCase	),       len(__lowerCamelCase	)	)
     return "0b" + "".join(
         str(int("1" in (char_a, char_b)	)	)
         for char_a, char_b in zip(a_binary.zfill(__lowerCamelCase	),       b_binary.zfill(__lowerCamelCase	)	)	)


if __name__ == "__main__":
       import doctest

       doctest.testmod()