

'''simple docstring'''






import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, 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 EfficientNetForImageClassification, EfficientNetModel
      from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor
class 	SCREAMING_SNAKE_CASE__			:




    def __init__(					self				,     lowercase__				,     lowercase__=13				,     lowercase__=32				,     lowercase__=3				,     lowercase__=[3, 3, 5]				,     lowercase__=[32, 16, 24]				,     lowercase__=[16, 24, 40]				,     lowercase__=[1, 1, 2]				,     lowercase__=[1, 1, 2]				,     lowercase__=[1, 6, 6]				,     lowercase__=True				,     lowercase__=True				,     lowercase__=37				,     lowercase__="gelu"				,     lowercase__=10				,     ):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       parent
          SCREAMING_SNAKE_CASE_      :			Dict     =       batch_size
          SCREAMING_SNAKE_CASE_      :			Tuple     =       image_size
          SCREAMING_SNAKE_CASE_      :			Any     =       num_channels
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       kernel_sizes
          SCREAMING_SNAKE_CASE_      :			int     =       in_channels
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       out_channels
          SCREAMING_SNAKE_CASE_      :			Dict     =       strides
          SCREAMING_SNAKE_CASE_      :			Dict     =       num_block_repeats
          SCREAMING_SNAKE_CASE_      :			List[str]     =       expand_ratios
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       is_training
          SCREAMING_SNAKE_CASE_      :			str     =       hidden_act
          SCREAMING_SNAKE_CASE_      :			List[str]     =       num_labels
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       use_labels




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

          SCREAMING_SNAKE_CASE_      :			Any     =       None
          if self.use_labels:
                SCREAMING_SNAKE_CASE_      :			Tuple     =       ids_tensor([self.batch_size]				,     self.num_labels			)

          SCREAMING_SNAKE_CASE_      :			Any     =       self.get_config()
          return config, pixel_values, labels




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return EfficientNetConfig(
              num_channels=self.num_channels				,     kernel_sizes=self.kernel_sizes				,     in_channels=self.in_channels				,     out_channels=self.out_channels				,     strides=self.strides				,     num_block_repeats=self.num_block_repeats				,     expand_ratios=self.expand_ratios				,     hidden_act=self.hidden_act				,     num_labels=self.num_labels				,     )




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[Any]     =       EfficientNetModel(config=lowercase__			)
          model.to(lowercase__			)
          model.eval()
          SCREAMING_SNAKE_CASE_      :			Dict     =       model(lowercase__			)
          # expected last hidden states: B, C, H // 4, W // 4
          self.parent.assertEqual(
              result.last_hidden_state.shape				,     (self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)				,     )




    def   __lowerCamelCase      (					self				,     lowercase__				,     lowercase__				,     lowercase__			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Dict     =       EfficientNetForImageClassification(lowercase__			)
          model.to(lowercase__			)
          model.eval()
          SCREAMING_SNAKE_CASE_      :			int     =       model(lowercase__				,     labels=lowercase__			)
          self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_labels)			)







    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Tuple     =       self.prepare_config_and_inputs()
          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Dict     =       config_and_inputs
          SCREAMING_SNAKE_CASE_      :			Any     =       {"pixel_values": pixel_values}
          return config, inputs_dict






@require_torch
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase,_UpperCAmelCase,unittest.TestCase      ):
    _A			    =							(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
    _A			    =							(
        {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
        if is_torch_available()
        else {}
    )

    _A			    =							False
    _A			    =							False
    _A			    =							False
    _A			    =							False
    _A			    =							False




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       EfficientNetModelTester(self			)
          SCREAMING_SNAKE_CASE_      :			List[str]     =       ConfigTester(
              self				,     config_class=lowercase__				,     has_text_modality=lowercase__				,     hidden_size=37			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return




    @unittest.skip(reason="EfficientNet does not use inputs_embeds"			)
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    @unittest.skip(reason="EfficientNet does not support input and output embeddings"			)
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    @unittest.skip(reason="EfficientNet does not use feedforward chunking"			)
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






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

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

                SCREAMING_SNAKE_CASE_      :			int     =       ["pixel_values"]
                self.assertListEqual(arg_names[:1]				,     lowercase__			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			str     =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase__			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          def check_hidden_states_output(lowercase__				,     lowercase__				,     lowercase__			):
                SCREAMING_SNAKE_CASE_      :			int     =       model_class(lowercase__			)
                model.to(lowercase__			)
                model.eval()

                with torch.no_grad():
                      SCREAMING_SNAKE_CASE_      :			Optional[int]     =       model(**self._prepare_for_class(lowercase__				,     lowercase__			)			)

                SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                SCREAMING_SNAKE_CASE_      :			Any     =       sum(config.num_block_repeats			) * 4
                self.assertEqual(len(lowercase__			)				,     lowercase__			)

                # EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
                self.assertListEqual(
                    list(hidden_states[0].shape[-2:]			)				,     [self.model_tester.image_size // 2, self.model_tester.image_size // 2]				,     )

          SCREAMING_SNAKE_CASE_,						SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                SCREAMING_SNAKE_CASE_      :			str     =       True
                check_hidden_states_output(lowercase__				,     lowercase__				,     lowercase__			)

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

                check_hidden_states_output(lowercase__				,     lowercase__				,     lowercase__			)




    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase__			)




    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."			)
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          pass




    @slow
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                SCREAMING_SNAKE_CASE_      :			Tuple     =       EfficientNetModel.from_pretrained(lowercase__			)
                self.assertIsNotNone(lowercase__			)







    @is_pipeline_test
    @require_vision
    @slow
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          super().test_pipeline_image_classification()






def 					__lowerCamelCase			(      )							->   List[Any]:
      """simple docstring"""

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





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




    @cached_property
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return AutoImageProcessor.from_pretrained("google/efficientnet-b7"			) if is_vision_available() else None







    @slow
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          SCREAMING_SNAKE_CASE_      :			List[str]     =       EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"			).to(lowercase__			)

          SCREAMING_SNAKE_CASE_      :			Any     =       self.default_image_processor
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       prepare_img()
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       image_processor(images=lowercase__				,     return_tensors="pt"			).to(lowercase__			)

          # forward pass
          with torch.no_grad():
                SCREAMING_SNAKE_CASE_      :			Dict     =       model(**lowercase__			)

          # verify the logits
          SCREAMING_SNAKE_CASE_      :			Tuple     =       torch.Size((1, 1000)			)
          self.assertEqual(outputs.logits.shape				,     lowercase__			)

          SCREAMING_SNAKE_CASE_      :			Tuple     =       torch.tensor([0.0001, 0.0002, 0.0002]			).to(lowercase__			)
          self.assertTrue(torch.allclose(outputs.logits[0, :3]				,     lowercase__				,     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


snake_case_       =       logging.get_logger(__name__)

snake_case_       =       {
    'apple/mobilevit-small': 'https://huggingface.co/apple/mobilevit-small/resolve/main/config.json',
    'apple/mobilevit-x-small': 'https://huggingface.co/apple/mobilevit-x-small/resolve/main/config.json',
    'apple/mobilevit-xx-small': 'https://huggingface.co/apple/mobilevit-xx-small/resolve/main/config.json',
    'apple/deeplabv3-mobilevit-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-small/resolve/main/config.json'
    ),
    'apple/deeplabv3-mobilevit-x-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-x-small/resolve/main/config.json'
    ),
    'apple/deeplabv3-mobilevit-xx-small': (
        'https://huggingface.co/apple/deeplabv3-mobilevit-xx-small/resolve/main/config.json'
    ),
    # See all MobileViT models at https://huggingface.co/models?filter=mobilevit
}
class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase      ):
    _A			    =							"mobilevit"




    def __init__(					self				,     lowercase__=3				,     lowercase__=256				,     lowercase__=2				,     lowercase__=[144, 192, 240]				,     lowercase__=[16, 32, 64, 96, 128, 160, 640]				,     lowercase__=4				,     lowercase__=2.0				,     lowercase__=4.0				,     lowercase__="silu"				,     lowercase__=3				,     lowercase__=32				,     lowercase__=0.1				,     lowercase__=0.0				,     lowercase__=0.1				,     lowercase__=0.02				,     lowercase__=1e-5				,     lowercase__=True				,     lowercase__=256				,     lowercase__=[6, 12, 18]				,     lowercase__=0.1				,     lowercase__=255				,     **lowercase__				,     ):






          """simple docstring"""






          super().__init__(**lowercase__			)

          SCREAMING_SNAKE_CASE_      :			int     =       num_channels
          SCREAMING_SNAKE_CASE_      :			List[str]     =       image_size
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       patch_size
          SCREAMING_SNAKE_CASE_      :			List[str]     =       hidden_sizes
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       neck_hidden_sizes
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       num_attention_heads
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       mlp_ratio
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       expand_ratio
          SCREAMING_SNAKE_CASE_      :			str     =       hidden_act
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       conv_kernel_size
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       output_stride
          SCREAMING_SNAKE_CASE_      :			Tuple     =       hidden_dropout_prob
          SCREAMING_SNAKE_CASE_      :			int     =       attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_      :			Tuple     =       classifier_dropout_prob
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       initializer_range
          SCREAMING_SNAKE_CASE_      :			Union[str, Any]     =       layer_norm_eps
          SCREAMING_SNAKE_CASE_      :			str     =       qkv_bias

          # decode head attributes for semantic segmentation
          SCREAMING_SNAKE_CASE_      :			Optional[int]     =       aspp_out_channels
          SCREAMING_SNAKE_CASE_      :			Optional[Any]     =       atrous_rates
          SCREAMING_SNAKE_CASE_      :			List[Any]     =       aspp_dropout_prob
          SCREAMING_SNAKE_CASE_      :			Any     =       semantic_loss_ignore_index






class 	SCREAMING_SNAKE_CASE__			(				_UpperCAmelCase      ):
    _A			    =							version.parse("1.11"      )




    @property
    def   __lowerCamelCase      (					self			):






          """simple docstring"""






          return OrderedDict([("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"})]			)




    @property
    def   __lowerCamelCase      (					self			):






          """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   __lowerCamelCase      (					self			):






          """simple docstring"""






          return 1e-4

