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 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






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


          """simple docstring"""


          _lowerCamelCase     :		str 						=						self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(lowercase_    ,  """tf_padding"""))
          self.parent.assertTrue(hasattr(lowercase_    ,  """depth_multiplier"""))





class 	__snake_case	:





      '''simple docstring'''






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


          """simple docstring"""


          _lowerCamelCase     :		Any 						=						parent
          _lowerCamelCase     :		Optional[Any] 						=						batch_size
          _lowerCamelCase     :		str 						=						num_channels
          _lowerCamelCase     :		Dict 						=						image_size
          _lowerCamelCase     :		int 						=						depth_multiplier
          _lowerCamelCase     :		Union[str, Any] 						=						depth_divisible_by
          _lowerCamelCase     :		List[str] 						=						min_depth
          _lowerCamelCase     :		str 						=						expand_ratio
          _lowerCamelCase     :		Dict 						=						tf_padding
          _lowerCamelCase     :		Union[str, Any] 						=						output_stride
          _lowerCamelCase     :		Tuple 						=						first_layer_is_expansion
          _lowerCamelCase     :		str 						=						finegrained_output
          _lowerCamelCase     :		Dict 						=						hidden_act
          _lowerCamelCase     :		Union[str, Any] 						=						last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier)
          _lowerCamelCase     :		List[Any] 						=						classifier_dropout_prob
          _lowerCamelCase     :		Any 						=						use_labels
          _lowerCamelCase     :		Union[str, Any] 						=						is_training
          _lowerCamelCase     :		Tuple 						=						num_labels
          _lowerCamelCase     :		int 						=						initializer_range
          _lowerCamelCase     :		Any 						=						scope



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


          """simple docstring"""


          _lowerCamelCase     :		int 						=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

          _lowerCamelCase     :		List[str] 						=						None
          _lowerCamelCase     :		List[Any] 						=						None
          if self.use_labels:
              _lowerCamelCase     :		int 						=						ids_tensor([self.batch_size]    ,  self.num_labels)
              _lowerCamelCase     :		Union[str, Any] 						=						ids_tensor([self.batch_size, self.image_size, self.image_size]    ,  self.num_labels)

          _lowerCamelCase     :		Optional[int] 						=						self.get_config()

          return config, pixel_values, labels, pixel_labels



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


          """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 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any]    ,  _UpperCamelCase     :				List[str]    ,  _UpperCamelCase     :				str    ,  _UpperCamelCase     :				int    ,  _UpperCamelCase     :				Union[str, Any])				->str:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						MobileNetVaModel(config=lowercase_)
          model.to(lowercase_)
          model.eval()
          _lowerCamelCase     :		Dict 						=						model(lowercase_)
          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 	_SCREAMING_SNAKE_CASE    (					self     :				List[Any]    ,  _UpperCamelCase     :				Optional[int]    ,  _UpperCamelCase     :				Dict    ,  _UpperCamelCase     :				int    ,  _UpperCamelCase     :				int)				->int:


          """simple docstring"""


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



      def 	_SCREAMING_SNAKE_CASE    (					self     :				str    ,  _UpperCamelCase     :				Optional[Any]    ,  _UpperCamelCase     :				Any    ,  _UpperCamelCase     :				str    ,  _UpperCamelCase     :				Any)				->Union[str, Any]:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						self.num_labels
          _lowerCamelCase     :		Any 						=						MobileNetVaForSemanticSegmentation(lowercase_)
          model.to(lowercase_)
          model.eval()
          _lowerCamelCase     :		Union[str, Any] 						=						model(lowercase_)
          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     :		str 						=						model(lowercase_    ,  labels=lowercase_)
          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 	_SCREAMING_SNAKE_CASE    (					self     :				Dict)				->Union[str, Any]:


          """simple docstring"""


          _lowerCamelCase     :		Union[str, Any] 						=						self.prepare_config_and_inputs()
          _lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase						,							_lowerCamelCase     :		Any 						=						config_and_inputs
          _lowerCamelCase     :		Optional[Any] 						=						{"""pixel_values""": pixel_values}
          return config, inputs_dict





@require_torch
class 	__snake_case	( __lowerCAmelCase ,  __lowerCAmelCase ,  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 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->List[str]:


          """simple docstring"""


          _lowerCamelCase     :		List[str] 						=						MobileNetVaModelTester(self)
          _lowerCamelCase     :		Optional[Any] 						=						MobileNetVaConfigTester(self    ,  config_class=lowercase_    ,  has_text_modality=lowercase_)



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


          """simple docstring"""


          self.config_tester.run_common_tests()



      @unittest.skip(reason="""MobileNetV2 does not use inputs_embeds""")
      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->Dict:


          """simple docstring"""


          pass



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


          """simple docstring"""


          pass



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


          """simple docstring"""


          pass



      def 	_SCREAMING_SNAKE_CASE    (					self     :				int)				->int:


          """simple docstring"""


          _lowerCamelCase						,							_lowerCamelCase     :		int 						=						self.model_tester.prepare_config_and_inputs_for_common()

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

              _lowerCamelCase     :		Optional[Any] 						=						["""pixel_values"""]
              self.assertListEqual(arg_names[:1]    ,  lowercase_)



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


          """simple docstring"""


          _lowerCamelCase     :		Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase_)



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


          """simple docstring"""


          def check_hidden_states_output(_UpperCamelCase     :				Optional[Any]    ,  _UpperCamelCase     :				Optional[Any]    ,  _UpperCamelCase     :				Union[str, Any]):
              _lowerCamelCase     :		Tuple 						=						model_class(lowercase_)
              model.to(lowercase_)
              model.eval()

              with torch.no_grad():
                  _lowerCamelCase     :		Tuple 						=						model(**self._prepare_for_class(lowercase_    ,  lowercase_))

              _lowerCamelCase     :		List[str] 						=						outputs.hidden_states

              _lowerCamelCase     :		Union[str, Any] 						=						16
              self.assertEqual(len(lowercase_)    ,  lowercase_)

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

          for model_class in self.all_model_classes:
              _lowerCamelCase     :		Dict 						=						True
              check_hidden_states_output(lowercase_    ,  lowercase_    ,  lowercase_)

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

              check_hidden_states_output(lowercase_    ,  lowercase_    ,  lowercase_)



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


          """simple docstring"""


          _lowerCamelCase     :		str 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowercase_)



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


          """simple docstring"""


          _lowerCamelCase     :		Optional[Any] 						=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_)




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Any)				->Dict:


          """simple docstring"""


          for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              _lowerCamelCase     :		str 						=						MobileNetVaModel.from_pretrained(lowercase_)
              self.assertIsNotNone(lowercase_)







def 						A__  (					):







    '''simple docstring'''
    _lowerCamelCase     :		Dict 						=						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
    return image




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





      '''simple docstring'''






      @cached_property
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Optional[Any])				->Optional[int]:


          """simple docstring"""


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



      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->Dict:


          """simple docstring"""


          _lowerCamelCase     :		Dict 						=						MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224""").to(lowercase_)

          _lowerCamelCase     :		Tuple 						=						self.default_image_processor
          _lowerCamelCase     :		List[str] 						=						prepare_img()
          _lowerCamelCase     :		List[str] 						=						image_processor(images=lowercase_    ,  return_tensors="""pt""").to(lowercase_)

          # forward pass
          with torch.no_grad():
              _lowerCamelCase     :		Any 						=						model(**lowercase_)

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

          _lowerCamelCase     :		int 						=						torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]).to(lowercase_)

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




      @slow
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Tuple)				->List[Any]:


          """simple docstring"""


          _lowerCamelCase     :		Tuple 						=						MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""")
          _lowerCamelCase     :		Any 						=						model.to(lowercase_)

          _lowerCamelCase     :		Dict 						=						MobileNetVaImageProcessor.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""")

          _lowerCamelCase     :		Tuple 						=						prepare_img()
          _lowerCamelCase     :		Union[str, Any] 						=						image_processor(images=lowercase_    ,  return_tensors="""pt""").to(lowercase_)

          # forward pass
          with torch.no_grad():
              _lowerCamelCase     :		List[str] 						=						model(**lowercase_)
          _lowerCamelCase     :		Any 						=						outputs.logits

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

          _lowerCamelCase     :		Optional[Any] 						=						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=lowercase_    ,  )

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





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
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


lowerCAmelCase			:							Any     =logging.get_logger(__name__)

lowerCAmelCase			:							List[Any]     ={
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}




class 	__snake_case	( __lowerCAmelCase ,  __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       'swin'

      _snake_case    		=       {
          'num_attention_heads': 'num_heads',
          'num_hidden_layers': 'num_layers',
      }



      def __init__(					self     :				Optional[int]    ,  _UpperCamelCase     :				List[str]=224    ,  _UpperCamelCase     :				List[str]=4    ,  _UpperCamelCase     :				List[Any]=3    ,  _UpperCamelCase     :				Dict=96    ,  _UpperCamelCase     :				Any=[2, 2, 6, 2]    ,  _UpperCamelCase     :				Any=[3, 6, 12, 24]    ,  _UpperCamelCase     :				Tuple=7    ,  _UpperCamelCase     :				Tuple=4.0    ,  _UpperCamelCase     :				Dict=True    ,  _UpperCamelCase     :				Tuple=0.0    ,  _UpperCamelCase     :				Any=0.0    ,  _UpperCamelCase     :				Optional[int]=0.1    ,  _UpperCamelCase     :				Any="gelu"    ,  _UpperCamelCase     :				str=False    ,  _UpperCamelCase     :				str=0.0_2    ,  _UpperCamelCase     :				Dict=1E-5    ,  _UpperCamelCase     :				List[str]=32    ,  _UpperCamelCase     :				Optional[Any]=None    ,  _UpperCamelCase     :				List[Any]=None    ,  **_UpperCamelCase     :				List[Any]    ,  )				->Tuple:


          """simple docstring"""


          super().__init__(**_UpperCamelCase)

          _lowerCamelCase     :		List[str] 						=						image_size
          _lowerCamelCase     :		Tuple 						=						patch_size
          _lowerCamelCase     :		Dict 						=						num_channels
          _lowerCamelCase     :		Union[str, Any] 						=						embed_dim
          _lowerCamelCase     :		str 						=						depths
          _lowerCamelCase     :		str 						=						len(_UpperCamelCase)
          _lowerCamelCase     :		Optional[Any] 						=						num_heads
          _lowerCamelCase     :		Tuple 						=						window_size
          _lowerCamelCase     :		int 						=						mlp_ratio
          _lowerCamelCase     :		Optional[int] 						=						qkv_bias
          _lowerCamelCase     :		List[str] 						=						hidden_dropout_prob
          _lowerCamelCase     :		str 						=						attention_probs_dropout_prob
          _lowerCamelCase     :		Tuple 						=						drop_path_rate
          _lowerCamelCase     :		List[str] 						=						hidden_act
          _lowerCamelCase     :		Dict 						=						use_absolute_embeddings
          _lowerCamelCase     :		int 						=						layer_norm_eps
          _lowerCamelCase     :		str 						=						initializer_range
          _lowerCamelCase     :		Dict 						=						encoder_stride
          # we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
          # this indicates the channel dimension after the last stage of the model
          _lowerCamelCase     :		int 						=						int(embed_dim * 2 ** (len(_UpperCamelCase) - 1))
          _lowerCamelCase     :		Dict 						=						["""stem"""] + [F"""stage{idx}""" for idx in range(1    ,  len(_UpperCamelCase) + 1)]
          _lowerCamelCase						,							_lowerCamelCase     :		List[str] 						=						get_aligned_output_features_output_indices(
              out_features=_UpperCamelCase    ,  out_indices=_UpperCamelCase    ,  stage_names=self.stage_names)





class 	__snake_case	( __lowerCAmelCase		):





      '''simple docstring'''






      _snake_case    		=       version.parse('1.11'		)



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


          """simple docstring"""


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




      @property
      def 	_SCREAMING_SNAKE_CASE    (					self     :				Union[str, Any])				->float:


          """simple docstring"""


          return 1E-4




