


"""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__				(					A_				):





   def 		UpperCamelCase_  (							self)  ->  Optional[int]:
      _lowerCamelCase	:					Dict   =		self.config_class(**self.inputs_dict)
      self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,   """tf_padding"""))
      self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,   """depth_multiplier"""))







class 	lowercase__				:





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





   def 		UpperCamelCase_  (							self)  ->  Union[str, Any]:
      _lowerCamelCase	:					Any   =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

      _lowerCamelCase	:					List[Any]   =		None
      _lowerCamelCase	:					str   =		None
      if self.use_labels:
         _lowerCamelCase	:					List[Any]   =		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	:					Dict   =		self.get_config()

      return config, pixel_values, labels, pixel_labels





   def 		UpperCamelCase_  (							self)  ->  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      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  str:
      _lowerCamelCase	:					Tuple   =		MobileNetVaModel(config=SCREAMING_SNAKE_CASE)
      model.to(SCREAMING_SNAKE_CASE)
      model.eval()
      _lowerCamelCase	:					str   =		model(SCREAMING_SNAKE_CASE)
      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      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  Tuple:
      _lowerCamelCase	:					Tuple   =		self.num_labels
      _lowerCamelCase	:					Union[str, Any]   =		MobileNetVaForImageClassification(SCREAMING_SNAKE_CASE)
      model.to(SCREAMING_SNAKE_CASE)
      model.eval()
      _lowerCamelCase	:					Optional[int]   =		model(SCREAMING_SNAKE_CASE      ,   labels=SCREAMING_SNAKE_CASE)
      self.parent.assertEqual(result.logits.shape      ,   (self.batch_size, self.num_labels))





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)  ->  int:
      _lowerCamelCase	:					Tuple   =		self.num_labels
      _lowerCamelCase	:					List[str]   =		MobileNetVaForSemanticSegmentation(SCREAMING_SNAKE_CASE)
      model.to(SCREAMING_SNAKE_CASE)
      model.eval()
      _lowerCamelCase	:					int   =		model(SCREAMING_SNAKE_CASE)
      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	:					Tuple   =		model(SCREAMING_SNAKE_CASE      ,   labels=SCREAMING_SNAKE_CASE)
      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)  ->  Optional[Any]:
      _lowerCamelCase	:					Tuple   =		self.prepare_config_and_inputs()
      _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase	:					Tuple   =		config_and_inputs
      _lowerCamelCase	:					Optional[Any]   =		{"""pixel_values""": pixel_values}
      return config, inputs_dict







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

   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False
   __UpperCAmelCase							       =					False





   def 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					int   =		MobileNetVaModelTester(self)
      _lowerCamelCase	:					Dict   =		MobileNetVaConfigTester(self      ,   config_class=SCREAMING_SNAKE_CASE      ,   has_text_modality=SCREAMING_SNAKE_CASE)





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





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





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





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





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      _lowerCamelCase   ,    _lowerCamelCase	:					Dict   =		self.model_tester.prepare_config_and_inputs_for_common()

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

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





   def 		UpperCamelCase_  (							self)  ->  int:
      _lowerCamelCase	:					str   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      def check_hidden_states_output(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE):
         _lowerCamelCase	:					List[str]   =		model_class(SCREAMING_SNAKE_CASE)
         model.to(SCREAMING_SNAKE_CASE)
         model.eval()

         with torch.no_grad():
            _lowerCamelCase	:					List[Any]   =		model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE))

         _lowerCamelCase	:					Optional[Any]   =		outputs.hidden_states

         _lowerCamelCase	:					Tuple   =		16
         self.assertEqual(len(SCREAMING_SNAKE_CASE)      ,   SCREAMING_SNAKE_CASE)

      _lowerCamelCase   ,    _lowerCamelCase	:					List[Any]   =		self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         _lowerCamelCase	:					List[str]   =		True
         check_hidden_states_output(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)

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

         check_hidden_states_output(SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  Tuple:
      _lowerCamelCase	:					str   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE)





   def 		UpperCamelCase_  (							self)  ->  Dict:
      _lowerCamelCase	:					Optional[int]   =		self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE)





   @slow
   def 		UpperCamelCase_  (							self)  ->  Tuple:
      for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowerCamelCase	:					str   =		MobileNetVaModel.from_pretrained(SCREAMING_SNAKE_CASE)
         self.assertIsNotNone(SCREAMING_SNAKE_CASE)







def 				_snake_case      (   ):




   """simple docstring"""







   _lowerCamelCase	:					Tuple   =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
   return image





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





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





   @slow
   def 		UpperCamelCase_  (							self)  ->  Dict:
      _lowerCamelCase	:					List[str]   =		MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v2_1.0_224""").to(SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Union[str, Any]   =		self.default_image_processor
      _lowerCamelCase	:					int   =		prepare_img()
      _lowerCamelCase	:					Optional[Any]   =		image_processor(images=SCREAMING_SNAKE_CASE      ,   return_tensors="""pt""").to(SCREAMING_SNAKE_CASE)

      # forward pass
      with torch.no_grad():
         _lowerCamelCase	:					str   =		model(**SCREAMING_SNAKE_CASE)

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

      _lowerCamelCase	:					Tuple   =		torch.tensor([0.24_45, -1.19_93, 0.19_05]).to(SCREAMING_SNAKE_CASE)

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





   @slow
   def 		UpperCamelCase_  (							self)  ->  List[str]:
      _lowerCamelCase	:					Optional[int]   =		MobileNetVaForSemanticSegmentation.from_pretrained("""google/deeplabv3_mobilenet_v2_1.0_513""")
      _lowerCamelCase	:					str   =		model.to(SCREAMING_SNAKE_CASE)

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

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

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

      # verify the logits
      _lowerCamelCase	:					Union[str, Any]   =		torch.Size((1, 21, 65, 65))
      self.assertEqual(logits.shape      ,   SCREAMING_SNAKE_CASE)

      _lowerCamelCase	:					Optional[Any]   =		torch.tensor(
          [
              [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
              [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
              [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
          ]      ,   device=SCREAMING_SNAKE_CASE      ,   )

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


"""simple docstring"""


import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..bit import BitConfig


UpperCAmelCase__			=    logging.get_logger(__name__)

UpperCAmelCase__			=    {
    """Intel/dpt-large""": """https://huggingface.co/Intel/dpt-large/resolve/main/config.json""",
    # See all DPT models at https://huggingface.co/models?filter=dpt
}


class 							a					(		lowerCAmelCase_ ):
    _snake_case  :	int  				=				'dpt'


    def __init__(       self						:	Any ,					__lowerCAmelCase						:	Optional[Any]=768 ,					__lowerCAmelCase						:	str=12 ,					__lowerCAmelCase						:	Optional[int]=12 ,					__lowerCAmelCase						:	Dict=3072 ,					__lowerCAmelCase						:	List[Any]="gelu" ,					__lowerCAmelCase						:	Tuple=0.0 ,					__lowerCAmelCase						:	str=0.0 ,					__lowerCAmelCase						:	List[Any]=0.02 ,					__lowerCAmelCase						:	Optional[Any]=1e-1_2 ,					__lowerCAmelCase						:	List[str]=384 ,					__lowerCAmelCase						:	Tuple=16 ,					__lowerCAmelCase						:	List[str]=3 ,					__lowerCAmelCase						:	Optional[Any]=False ,					__lowerCAmelCase						:	Optional[Any]=True ,					__lowerCAmelCase						:	Optional[Any]=[2, 5, 8, 11] ,					__lowerCAmelCase						:	Any="project" ,					__lowerCAmelCase						:	Dict=[4, 2, 1, 0.5] ,					__lowerCAmelCase						:	int=[96, 192, 384, 768] ,					__lowerCAmelCase						:	Dict=256 ,					__lowerCAmelCase						:	Optional[Any]=-1 ,					__lowerCAmelCase						:	Optional[Any]=False ,					__lowerCAmelCase						:	Union[str, Any]=True ,					__lowerCAmelCase						:	List[Any]=0.4 ,					__lowerCAmelCase						:	List[str]=255 ,					__lowerCAmelCase						:	List[Any]=0.1 ,					__lowerCAmelCase						:	Optional[int]=[1, 1024, 24, 24] ,					__lowerCAmelCase						:	List[Any]=[0, 1] ,					__lowerCAmelCase						:	Dict=None ,					**__lowerCAmelCase						:	str ,					):
      super().__init__(**__lowerCAmelCase       )

      _UpperCAmelCase    			=   hidden_size
      _UpperCAmelCase    			=   is_hybrid

      if self.is_hybrid:
        if backbone_config is None:
          logger.info("""Initializing the config with a `BiT` backbone."""       )
          _UpperCAmelCase    			=   {
              """global_padding""": """same""",
              """layer_type""": """bottleneck""",
              """depths""": [3, 4, 9],
              """out_features""": ["""stage1""", """stage2""", """stage3"""],
              """embedding_dynamic_padding""": True,
          }
          _UpperCAmelCase    			=   BitConfig(**__lowerCAmelCase       )
        elif isinstance(__lowerCAmelCase ,					__lowerCAmelCase       ):
          logger.info("""Initializing the config with a `BiT` backbone."""       )
          _UpperCAmelCase    			=   BitConfig(**__lowerCAmelCase       )
        elif isinstance(__lowerCAmelCase ,					__lowerCAmelCase       ):
          _UpperCAmelCase    			=   backbone_config
        else:
          raise ValueError(
              f'''backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}.'''       )

        _UpperCAmelCase    			=   backbone_featmap_shape
        _UpperCAmelCase    			=   neck_ignore_stages

        if readout_type != "project":
          raise ValueError("""Readout type must be 'project' when using `DPT-hybrid` mode."""       )
      else:
        _UpperCAmelCase    			=   None
        _UpperCAmelCase    			=   None
        _UpperCAmelCase    			=   []

      _UpperCAmelCase    			=   num_hidden_layers
      _UpperCAmelCase    			=   num_attention_heads
      _UpperCAmelCase    			=   intermediate_size
      _UpperCAmelCase    			=   hidden_act
      _UpperCAmelCase    			=   hidden_dropout_prob
      _UpperCAmelCase    			=   attention_probs_dropout_prob
      _UpperCAmelCase    			=   initializer_range
      _UpperCAmelCase    			=   layer_norm_eps
      _UpperCAmelCase    			=   image_size
      _UpperCAmelCase    			=   patch_size
      _UpperCAmelCase    			=   num_channels
      _UpperCAmelCase    			=   qkv_bias
      _UpperCAmelCase    			=   backbone_out_indices
      if readout_type not in ["ignore", "add", "project"]:
        raise ValueError("""Readout_type must be one of ['ignore', 'add', 'project']"""       )
      _UpperCAmelCase    			=   readout_type
      _UpperCAmelCase    			=   reassemble_factors
      _UpperCAmelCase    			=   neck_hidden_sizes
      _UpperCAmelCase    			=   fusion_hidden_size
      _UpperCAmelCase    			=   head_in_index
      _UpperCAmelCase    			=   use_batch_norm_in_fusion_residual
      # auxiliary head attributes (semantic segmentation)
      _UpperCAmelCase    			=   use_auxiliary_head
      _UpperCAmelCase    			=   auxiliary_loss_weight
      _UpperCAmelCase    			=   semantic_loss_ignore_index
      _UpperCAmelCase    			=   semantic_classifier_dropout


    def   lowerCAmelCase_	(       self						:	List[str]       ):
      _UpperCAmelCase    			=   copy.deepcopy(self.__dict__       )

      if output["backbone_config"] is not None:
        _UpperCAmelCase    			=   self.backbone_config.to_dict()

      _UpperCAmelCase    			=   self.__class__.model_type
      return output
