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__    ):
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     SCREAMING_SNAKE_CASE__:   List[Any]=      self.config_class(**self.inputs_dict   )
     self.parent.assertTrue(hasattr(UpperCAmelCase__ , '''tf_padding'''   )   )
     self.parent.assertTrue(hasattr(UpperCAmelCase__ , '''depth_multiplier'''   )   )






class 		_lowerCamelCase		:
    def __init__(  self , lowerCAmelCase , lowerCAmelCase=13 , lowerCAmelCase=3 , lowerCAmelCase=32 , lowerCAmelCase=0.25 , lowerCAmelCase=8 , lowerCAmelCase=8 , lowerCAmelCase=6 , lowerCAmelCase=32 , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase="relu6" , lowerCAmelCase=1280 , lowerCAmelCase=0.1 , lowerCAmelCase=0.02 , lowerCAmelCase=True , lowerCAmelCase=True , lowerCAmelCase=10 , lowerCAmelCase=None , )       ->					Dict:
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      parent
     SCREAMING_SNAKE_CASE__:   int=      batch_size
     SCREAMING_SNAKE_CASE__:   Any=      num_channels
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      image_size
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      depth_multiplier
     SCREAMING_SNAKE_CASE__:   int=      depth_divisible_by
     SCREAMING_SNAKE_CASE__:   str=      min_depth
     SCREAMING_SNAKE_CASE__:   List[str]=      expand_ratio
     SCREAMING_SNAKE_CASE__:   Dict=      tf_padding
     SCREAMING_SNAKE_CASE__:   Any=      output_stride
     SCREAMING_SNAKE_CASE__:   Any=      first_layer_is_expansion
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      finegrained_output
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      hidden_act
     SCREAMING_SNAKE_CASE__:   Union[str, Any]=      last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier   )
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      classifier_dropout_prob
     SCREAMING_SNAKE_CASE__:   Optional[int]=      use_labels
     SCREAMING_SNAKE_CASE__:   List[str]=      is_training
     SCREAMING_SNAKE_CASE__:   Tuple=      num_labels
     SCREAMING_SNAKE_CASE__:   List[Any]=      initializer_range
     SCREAMING_SNAKE_CASE__:   Optional[int]=      scope
    def 						UpperCamelCase_				(  self   )       ->					Union[str, Any]:
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

     SCREAMING_SNAKE_CASE__:   int=      None
     SCREAMING_SNAKE_CASE__:   Any=      None
     if self.use_labels:
      SCREAMING_SNAKE_CASE__:   str=      ids_tensor([self.batch_size] , self.num_labels   )
      SCREAMING_SNAKE_CASE__:   Optional[int]=      ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels   )

     SCREAMING_SNAKE_CASE__:   Any=      self.get_config()

     return config, pixel_values, labels, pixel_labels
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     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   )       ->					Any:
     SCREAMING_SNAKE_CASE__:   Dict=      MobileNetVaModel(config=UpperCAmelCase__   )
     model.to(UpperCAmelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__:   List[str]=      model(UpperCAmelCase__   )
     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   )       ->					Optional[int]:
     SCREAMING_SNAKE_CASE__:   List[str]=      self.num_labels
     SCREAMING_SNAKE_CASE__:   str=      MobileNetVaForImageClassification(UpperCAmelCase__   )
     model.to(UpperCAmelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__:   str=      model(UpperCAmelCase__ , labels=UpperCAmelCase__   )
     self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels)   )
    def 						UpperCamelCase_				(  self , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase   )       ->					Union[str, Any]:
     SCREAMING_SNAKE_CASE__:   Optional[int]=      self.num_labels
     SCREAMING_SNAKE_CASE__:   Any=      MobileNetVaForSemanticSegmentation(UpperCAmelCase__   )
     model.to(UpperCAmelCase__   )
     model.eval()
     SCREAMING_SNAKE_CASE__:   Any=      model(UpperCAmelCase__   )
     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__:   Optional[Any]=      model(UpperCAmelCase__ , labels=UpperCAmelCase__   )
     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   )       ->					Any:
     SCREAMING_SNAKE_CASE__:   str=      self.prepare_config_and_inputs()
     SCREAMING_SNAKE_CASE__:   Any=      config_and_inputs
     SCREAMING_SNAKE_CASE__:   str=      {'''pixel_values''': pixel_values}
     return config, inputs_dict






@require_torch
class 		_lowerCamelCase		(   lowercase__    ,     lowercase__    ,     unittest.TestCase    ):
    __a  =      (
        (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    __a  =      (
        {
            "feature-extraction": MobileNetVaModel,
            "image-classification": MobileNetVaForImageClassification,
            "image-segmentation": MobileNetVaForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    __a  =      False
    __a  =      False
    __a  =      False
    __a  =      False
    def 						UpperCamelCase_				(  self   )       ->					Optional[Any]:
     SCREAMING_SNAKE_CASE__:   List[Any]=      MobileNetVaModelTester(self   )
     SCREAMING_SNAKE_CASE__:   Any=      MobileNetVaConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__   )
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     self.config_tester.run_common_tests()
    @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds'''   )
    def 						UpperCamelCase_				(  self   )       ->					Dict:
     pass
    @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings'''   )
    def 						UpperCamelCase_				(  self   )       ->					Union[str, Any]:
     pass
    @unittest.skip(reason='''MobileNetV2 does not output attentions'''   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     pass
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     SCREAMING_SNAKE_CASE__:   Any=      self.model_tester.prepare_config_and_inputs_for_common()

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

      SCREAMING_SNAKE_CASE__:   str=      ['''pixel_values''']
      self.assertListEqual(arg_names[:1] , UpperCAmelCase__   )
    def 						UpperCamelCase_				(  self   )       ->					List[str]:
     SCREAMING_SNAKE_CASE__:   List[str]=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase__   )
    def 						UpperCamelCase_				(  self   )       ->					Union[str, Any]:
     def check_hidden_states_output(lowerCAmelCase , lowerCAmelCase , lowerCAmelCase   ):
      SCREAMING_SNAKE_CASE__:   Tuple=      model_class(UpperCAmelCase__   )
      model.to(UpperCAmelCase__   )
      model.eval()

      with torch.no_grad():
       SCREAMING_SNAKE_CASE__:   str=      model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__   )   )

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

      SCREAMING_SNAKE_CASE__:   int=      16
      self.assertEqual(len(UpperCAmelCase__   ) , UpperCAmelCase__   )

     SCREAMING_SNAKE_CASE__:   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(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__   )

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

      check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__   )
    def 						UpperCamelCase_				(  self   )       ->					Optional[int]:
     SCREAMING_SNAKE_CASE__:   Dict=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__   )
    def 						UpperCamelCase_				(  self   )       ->					Tuple:
     SCREAMING_SNAKE_CASE__:   Optional[int]=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase__   )



    @slow
    def 						UpperCamelCase_				(  self   )       ->					Any:
     for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      SCREAMING_SNAKE_CASE__:   List[str]=      MobileNetVaModel.from_pretrained(UpperCAmelCase__   )
      self.assertIsNotNone(UpperCAmelCase__   )







def 			A__      (	):

 '''simple docstring'''





 SCREAMING_SNAKE_CASE__:   str=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''      )
 return image






@require_torch
@require_vision
class 		_lowerCamelCase		(   unittest.TestCase    ):
    @cached_property
    def 						UpperCamelCase_				(  self   )       ->					List[Any]:
     return (
         MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224'''   ) if is_vision_available() else None
     )
    @slow
    def 						UpperCamelCase_				(  self   )       ->					str:
     SCREAMING_SNAKE_CASE__:   Optional[Any]=      MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224'''   ).to(UpperCAmelCase__   )

     SCREAMING_SNAKE_CASE__:   Optional[int]=      self.default_image_processor
     SCREAMING_SNAKE_CASE__:   Optional[int]=      prepare_img()
     SCREAMING_SNAKE_CASE__:   List[str]=      image_processor(images=UpperCAmelCase__ , return_tensors='''pt'''   ).to(UpperCAmelCase__   )

     # forward pass
     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   Dict=      model(**UpperCAmelCase__   )

     # verify the logits
     SCREAMING_SNAKE_CASE__:   str=      torch.Size((1, 1001)   )
     self.assertEqual(outputs.logits.shape , UpperCAmelCase__   )

     SCREAMING_SNAKE_CASE__:   Any=      torch.tensor([0.2445, -1.1993, 0.1905]   ).to(UpperCAmelCase__   )

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



    @slow
    def 						UpperCamelCase_				(  self   )       ->					Dict:
     SCREAMING_SNAKE_CASE__:   Optional[int]=      MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''   )
     SCREAMING_SNAKE_CASE__:   List[str]=      model.to(UpperCAmelCase__   )

     SCREAMING_SNAKE_CASE__:   List[Any]=      MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513'''   )

     SCREAMING_SNAKE_CASE__:   List[Any]=      prepare_img()
     SCREAMING_SNAKE_CASE__:   Any=      image_processor(images=UpperCAmelCase__ , return_tensors='''pt'''   ).to(UpperCAmelCase__   )

     # forward pass
     with torch.no_grad():
      SCREAMING_SNAKE_CASE__:   Optional[Any]=      model(**UpperCAmelCase__   )
     SCREAMING_SNAKE_CASE__:   Any=      outputs.logits

     # verify the logits
     SCREAMING_SNAKE_CASE__:   Dict=      torch.Size((1, 21, 65, 65)   )
     self.assertEqual(logits.shape , UpperCAmelCase__   )

     SCREAMING_SNAKE_CASE__:   List[str]=      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=UpperCAmelCase__ , )

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


from typing import TYPE_CHECKING

# rely on isort to merge the imports
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowercase_     :   Dict 				=				{
    'configuration_autoformer': [
        'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'AutoformerConfig',
    ],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase_     :   str 				=				[
          'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
          'AutoformerForPrediction',
          'AutoformerModel',
          'AutoformerPreTrainedModel',
      ]


if TYPE_CHECKING:
      from .configuration_autoformer import (
          AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
          AutoformerConfig,
      )

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_autoformer import (
                AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
                AutoformerForPrediction,
                AutoformerModel,
                AutoformerPreTrainedModel,
            )

else:
      import sys

      lowercase_     :   Tuple 				=				_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

