






'''simple docstring'''





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 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Union[str, Any]     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     self.config_class(**self.inputs_dict     )
     self.parent.assertTrue(hasattr(__lowerCamelCase				,     "tf_padding"     )     )
     self.parent.assertTrue(hasattr(__lowerCamelCase				,     "depth_multiplier"     )     )
class 				lowercase       :


    '''simple docstring'''

    def __init__(					self     :     Dict				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     str=13				,     __lowerCamelCase     :     Union[str, Any]=3				,     __lowerCamelCase     :     str=32				,     __lowerCamelCase     :     Any=0.2_5				,     __lowerCamelCase     :     Optional[int]=8				,     __lowerCamelCase     :     str=8				,     __lowerCamelCase     :     str=6				,     __lowerCamelCase     :     List[Any]=32				,     __lowerCamelCase     :     Union[str, Any]=True				,     __lowerCamelCase     :     List[Any]=True				,     __lowerCamelCase     :     List[str]=True				,     __lowerCamelCase     :     int="relu6"				,     __lowerCamelCase     :     Tuple=1280				,     __lowerCamelCase     :     Any=0.1				,     __lowerCamelCase     :     List[str]=0.0_2				,     __lowerCamelCase     :     List[Any]=True				,     __lowerCamelCase     :     int=True				,     __lowerCamelCase     :     Dict=10				,     __lowerCamelCase     :     Optional[Any]=None				,     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     parent
     lowerCamelCase__  =     batch_size
     lowerCamelCase__  =     num_channels
     lowerCamelCase__  =     image_size
     lowerCamelCase__  =     depth_multiplier
     lowerCamelCase__  =     depth_divisible_by
     lowerCamelCase__  =     min_depth
     lowerCamelCase__  =     expand_ratio
     lowerCamelCase__  =     tf_padding
     lowerCamelCase__  =     output_stride
     lowerCamelCase__  =     first_layer_is_expansion
     lowerCamelCase__  =     finegrained_output
     lowerCamelCase__  =     hidden_act
     lowerCamelCase__  =     last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier     )
     lowerCamelCase__  =     classifier_dropout_prob
     lowerCamelCase__  =     use_labels
     lowerCamelCase__  =     is_training
     lowerCamelCase__  =     num_labels
     lowerCamelCase__  =     initializer_range
     lowerCamelCase__  =     scope

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

     '''simple docstring'''




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

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

     lowerCamelCase__  =     self.get_config()

     return config, pixel_values, labels, pixel_labels

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

     '''simple docstring'''




     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    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Union[str, Any]     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     MobileNetVaModel(config=__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     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    a__				(					self     :     int				,     __lowerCamelCase     :     Any				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Any     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_labels
     lowerCamelCase__  =     MobileNetVaForImageClassification(__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     model(__lowerCamelCase				,     labels=__lowerCamelCase     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_labels)     )

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[str]     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_labels
     lowerCamelCase__  =     MobileNetVaForSemanticSegmentation(__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     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,
         )				,     )
     lowerCamelCase__  =     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    a__				(					self     :     str     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.prepare_config_and_inputs()
     lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     config_and_inputs
     lowerCamelCase__  =     {"pixel_values": pixel_values}
     return config, inputs_dict
@require_torch
class 				lowercase       (							_lowerCamelCase ,       _lowerCamelCase ,       unittest.TestCase      ):


    '''simple docstring'''

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

    lowerCAmelCase__      				=							False
    lowerCAmelCase__      				=							False
    lowerCAmelCase__      				=							False
    lowerCAmelCase__      				=							False

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

     '''simple docstring'''




     lowerCamelCase__  =     MobileNetVaModelTester(self     )
     lowerCamelCase__  =     MobileNetVaConfigTester(self				,     config_class=__lowerCamelCase				,     has_text_modality=__lowerCamelCase     )

    def    a__				(					self     :     str     )							->							int:

     '''simple docstring'''




     self.config_tester.run_common_tests()

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

     '''simple docstring'''




     pass

    @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"     )
    def    a__				(					self     :     Optional[int]     )							->							Union[str, Any]:

     '''simple docstring'''




     pass

    @unittest.skip(reason="MobileNetV2 does not output attentions"     )
    def    a__				(					self     :     Optional[Any]     )							->							List[str]:

     '''simple docstring'''




     pass

    def    a__				(					self     :     int     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs_for_common()

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

      lowerCamelCase__  =     ["pixel_values"]
      self.assertListEqual(arg_names[:1]				,     __lowerCamelCase     )

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

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase     )

    def    a__				(					self     :     Tuple     )							->							int:

     '''simple docstring'''




     def check_hidden_states_output(__lowerCamelCase     :     Dict				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     int     ):
      lowerCamelCase__  =     model_class(__lowerCamelCase     )
      model.to(__lowerCamelCase     )
      model.eval()

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

      lowerCamelCase__  =     outputs.hidden_states

      lowerCamelCase__  =     16
      self.assertEqual(len(__lowerCamelCase     )				,     __lowerCamelCase     )

     lowerCamelCase__  ,	lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs_for_common()

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

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

      check_hidden_states_output(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )

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

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase     )

    def    a__				(					self     :     int     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase     )




    @slow
    def    a__				(					self     :     Optional[Any]     )							->							Dict:

     '''simple docstring'''




     for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      lowerCamelCase__  =     MobileNetVaModel.from_pretrained(__lowerCamelCase     )
      self.assertIsNotNone(__lowerCamelCase     )






def    lowerCamelCase_     (    ):
 lowerCamelCase__  =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
 return image
@require_torch
@require_vision
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    @cached_property
    def    a__				(					self     :     List[Any]     )							->							str:

     '''simple docstring'''




     return (
         MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"     ) if is_vision_available() else None
     )

    @slow
    def    a__				(					self     :     Optional[Any]     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"     ).to(__lowerCamelCase     )

     lowerCamelCase__  =     self.default_image_processor
     lowerCamelCase__  =     prepare_img()
     lowerCamelCase__  =     image_processor(images=__lowerCamelCase				,     return_tensors="pt"     ).to(__lowerCamelCase     )

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

     # verify the logits
     lowerCamelCase__  =     torch.Size((1, 1001)     )
     self.assertEqual(outputs.logits.shape				,     __lowerCamelCase     )

     lowerCamelCase__  =     torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]     ).to(__lowerCamelCase     )

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




    @slow
    def    a__				(					self     :     str     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )
     lowerCamelCase__  =     model.to(__lowerCamelCase     )

     lowerCamelCase__  =     MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"     )

     lowerCamelCase__  =     prepare_img()
     lowerCamelCase__  =     image_processor(images=__lowerCamelCase				,     return_tensors="pt"     ).to(__lowerCamelCase     )

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

     # verify the logits
     lowerCamelCase__  =     torch.Size((1, 21, 65, 65)     )
     self.assertEqual(logits.shape				,     __lowerCamelCase     )

     lowerCamelCase__  =     torch.tensor(
         [
             [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
             [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
             [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
         ]				,     device=__lowerCamelCase				,     )

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









'''simple docstring'''





from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__A							:							Optional[int]  							=		logging.get_logger(__name__)

__A							:							Tuple  							=		{
    """google/mobilenet_v1_1.0_224""": """https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v1_0.75_192""": """https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json""",
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							"mobilenet_v1"

    def __init__(					self     :     Union[str, Any]				,     __lowerCamelCase     :     Tuple=3				,     __lowerCamelCase     :     Any=224				,     __lowerCamelCase     :     Tuple=1.0				,     __lowerCamelCase     :     Optional[int]=8				,     __lowerCamelCase     :     str="relu6"				,     __lowerCamelCase     :     Any=True				,     __lowerCamelCase     :     Union[str, Any]=0.9_9_9				,     __lowerCamelCase     :     List[Any]=0.0_2				,     __lowerCamelCase     :     str=0.0_0_1				,     **__lowerCamelCase     :     str				,     )							->							Dict:

     '''simple docstring'''




     super().__init__(**__lowerCamelCase     )

     if depth_multiplier <= 0:
      raise ValueError("depth_multiplier must be greater than zero."     )

     lowerCamelCase__  =     num_channels
     lowerCamelCase__  =     image_size
     lowerCamelCase__  =     depth_multiplier
     lowerCamelCase__  =     min_depth
     lowerCamelCase__  =     hidden_act
     lowerCamelCase__  =     tf_padding
     lowerCamelCase__  =     classifier_dropout_prob
     lowerCamelCase__  =     initializer_range
     lowerCamelCase__  =     layer_norm_eps
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							version.parse("1.11"      )

    @property
    def    a__				(					self     :     List[str]     )							->							Mapping[str, Mapping[int, str]]:

     '''simple docstring'''




     return OrderedDict([("pixel_values", {0: "batch"})]     )

    @property
    def    a__				(					self     :     str     )							->							Mapping[str, Mapping[int, str]]:

     '''simple docstring'''




     if self.task == "image-classification":
      return OrderedDict([("logits", {0: "batch"})]     )
     else:
      return OrderedDict([("last_hidden_state", {0: "batch"}), ("pooler_output", {0: "batch"})]     )




    @property
    def    a__				(					self     :     List[Any]     )							->							float:

     '''simple docstring'''




     return 1E-4

