






"""simple docstring"""






import inspect
import unittest

from transformers import DPTConfig
from transformers.file_utils import is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import MODEL_MAPPING, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTModel
  from transformers.models.dpt.modeling_dpt import DPT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import DPTImageProcessor




class 				lowerCAmelCase__							:






      '''simple docstring'''

      def __init__(		self	:    int		,      lowercase_	:    Union[str, Any]		,      lowercase_	:    str=2		,      lowercase_	:    Optional[Any]=32		,      lowercase_	:    List[str]=16		,      lowercase_	:    Tuple=3		,      lowercase_	:    str=True		,      lowercase_	:    Any=True		,      lowercase_	:    int=32		,      lowercase_	:    List[str]=4		,      lowercase_	:    List[Any]=[0, 1, 2, 3]		,      lowercase_	:    Any=4		,      lowercase_	:    List[str]=37		,      lowercase_	:    Optional[int]="gelu"		,      lowercase_	:    List[Any]=0.1		,      lowercase_	:    List[Any]=0.1		,      lowercase_	:    int=0.02		,      lowercase_	:    str=3		,      lowercase_	:    Any=[1, 384, 24, 24]		,      lowercase_	:    Optional[int]=True		,      lowercase_	:    Union[str, Any]=None		,      ):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Any       		=						parent
          SCREAMING_SNAKE_CASE_ :    Tuple       		=						batch_size
          SCREAMING_SNAKE_CASE_ :    Optional[int]       		=						image_size
          SCREAMING_SNAKE_CASE_ :    Tuple       		=						patch_size
          SCREAMING_SNAKE_CASE_ :    int       		=						num_channels
          SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						is_training
          SCREAMING_SNAKE_CASE_ :    Union[str, Any]       		=						use_labels
          SCREAMING_SNAKE_CASE_ :    List[Any]       		=						hidden_size
          SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						num_hidden_layers
          SCREAMING_SNAKE_CASE_ :    Any       		=						backbone_out_indices
          SCREAMING_SNAKE_CASE_ :    Union[str, Any]       		=						num_attention_heads
          SCREAMING_SNAKE_CASE_ :    Dict       		=						intermediate_size
          SCREAMING_SNAKE_CASE_ :    Dict       		=						hidden_act
          SCREAMING_SNAKE_CASE_ :    Dict       		=						hidden_dropout_prob
          SCREAMING_SNAKE_CASE_ :    List[Any]       		=						attention_probs_dropout_prob
          SCREAMING_SNAKE_CASE_ :    List[Any]       		=						initializer_range
          SCREAMING_SNAKE_CASE_ :    Union[str, Any]       		=						num_labels
          SCREAMING_SNAKE_CASE_ :    List[Any]       		=						backbone_featmap_shape
          SCREAMING_SNAKE_CASE_ :    Any       		=						scope
          SCREAMING_SNAKE_CASE_ :    Optional[int]       		=						is_hybrid
          # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
          SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						(image_size // patch_size) ** 2
          SCREAMING_SNAKE_CASE_ :    Any       		=						num_patches + 1
      def _SCREAMING_SNAKE_CASE					(		self	:    List[Any]):




          '''simple docstring'''


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

          SCREAMING_SNAKE_CASE_ :    List[str]       		=						None
          if self.use_labels:
              SCREAMING_SNAKE_CASE_ :    Dict       		=						ids_tensor([self.batch_size, self.image_size, self.image_size]		,      self.num_labels)

          SCREAMING_SNAKE_CASE_ :    Dict       		=						self.get_config()

          return config, pixel_values, labels
      def _SCREAMING_SNAKE_CASE					(		self	:    List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Dict       		=						{
              '''global_padding''': '''same''',
              '''layer_type''': '''bottleneck''',
              '''depths''': [3, 4, 9],
              '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
              '''embedding_dynamic_padding''': True,
              '''hidden_sizes''': [96, 192, 384, 768],
              '''num_groups''': 2,
          }

          return DPTConfig(
              image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      hidden_size=self.hidden_size		,      num_hidden_layers=self.num_hidden_layers		,      backbone_out_indices=self.backbone_out_indices		,      num_attention_heads=self.num_attention_heads		,      intermediate_size=self.intermediate_size		,      hidden_act=self.hidden_act		,      hidden_dropout_prob=self.hidden_dropout_prob		,      attention_probs_dropout_prob=self.attention_probs_dropout_prob		,      is_decoder=lowercase__		,      initializer_range=self.initializer_range		,      is_hybrid=self.is_hybrid		,      backbone_config=lowercase__		,      backbone_featmap_shape=self.backbone_featmap_shape		,      )
      def _SCREAMING_SNAKE_CASE					(		self	:    Union[str, Any]		,      lowercase_	:    str		,      lowercase_	:    Optional[Any]		,      lowercase_	:    List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    List[str]       		=						DPTModel(config=lowercase__)
          model.to(lowercase__)
          model.eval()
          SCREAMING_SNAKE_CASE_ :    Dict       		=						model(lowercase__)
          self.parent.assertEqual(result.last_hidden_state.shape		,      (self.batch_size, self.seq_length, self.hidden_size))
      def _SCREAMING_SNAKE_CASE					(		self	:    Dict		,      lowercase_	:    Optional[int]		,      lowercase_	:    Dict		,      lowercase_	:    Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    List[str]       		=						self.num_labels
          SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						DPTForDepthEstimation(lowercase__)
          model.to(lowercase__)
          model.eval()
          SCREAMING_SNAKE_CASE_ :    str       		=						model(lowercase__)
          self.parent.assertEqual(result.predicted_depth.shape		,      (self.batch_size, self.image_size, self.image_size))
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[int]		,      lowercase_	:    str		,      lowercase_	:    Tuple		,      lowercase_	:    str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Tuple       		=						self.num_labels
          SCREAMING_SNAKE_CASE_ :    Optional[int]       		=						DPTForSemanticSegmentation(lowercase__)
          model.to(lowercase__)
          model.eval()
          SCREAMING_SNAKE_CASE_ :    str       		=						model(lowercase__		,      labels=lowercase__)
          self.parent.assertEqual(
              result.logits.shape		,      (self.batch_size, self.num_labels, self.image_size, self.image_size))



      def _SCREAMING_SNAKE_CASE					(		self	:    Tuple):




          '''simple docstring'''


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




@require_torch
class 				lowerCAmelCase__							(     _UpperCamelCase							,						_UpperCamelCase							,						unittest.TestCase					):






      '''simple docstring'''

      __UpperCamelCase      					=    (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
      __UpperCamelCase      					=    (
          {
              '''depth-estimation''': DPTForDepthEstimation,
              '''feature-extraction''': DPTModel,
              '''image-segmentation''': DPTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      __UpperCamelCase      					=    False
      __UpperCamelCase      					=    False
      __UpperCamelCase      					=    False
      def _SCREAMING_SNAKE_CASE					(		self	:    Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Any       		=						DPTModelTester(self)
          SCREAMING_SNAKE_CASE_ :    str       		=						ConfigTester(self		,      config_class=lowercase__		,      has_text_modality=lowercase__		,      hidden_size=37)
      def _SCREAMING_SNAKE_CASE					(		self	:    Dict):




          '''simple docstring'''


          self.config_tester.run_common_tests()
      @unittest.skip(reason='''DPT does not use inputs_embeds''')
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[Any]):




          '''simple docstring'''


          pass
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[int]):




          '''simple docstring'''


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

          for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_ :    str       		=						model_class(lowercase__)
              self.assertIsInstance(model.get_input_embeddings()		,      (nn.Module))
              SCREAMING_SNAKE_CASE_ :    Tuple       		=						model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(lowercase__		,      nn.Linear))
      def _SCREAMING_SNAKE_CASE					(		self	:    Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Any       		=						self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_ :    str       		=						['''pixel_values''']
              self.assertListEqual(arg_names[:1]		,      lowercase__)
      def _SCREAMING_SNAKE_CASE					(		self	:    List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Tuple       		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowercase__)
      def _SCREAMING_SNAKE_CASE					(		self	:    List[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    List[str]       		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_depth_estimation(*lowercase__)
      def _SCREAMING_SNAKE_CASE					(		self	:    Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Dict       		=						self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*lowercase__)
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[Any]):




          '''simple docstring'''


          for model_class in self.all_model_classes:
              if model_class.__name__ == "DPTForDepthEstimation":
                  continue

              SCREAMING_SNAKE_CASE_ :    str       		=						self.model_tester.prepare_config_and_inputs_for_common()
              SCREAMING_SNAKE_CASE_ :    Any       		=						True

              if model_class in get_values(lowercase__):
                  continue

              SCREAMING_SNAKE_CASE_ :    List[Any]       		=						model_class(lowercase__)
              model.to(lowercase__)
              model.train()
              SCREAMING_SNAKE_CASE_ :    Any       		=						self._prepare_for_class(lowercase__		,      lowercase__		,      return_labels=lowercase__)
              SCREAMING_SNAKE_CASE_ :    Any       		=						model(**lowercase__).loss
              loss.backward()
      def _SCREAMING_SNAKE_CASE					(		self	:    List[str]):




          '''simple docstring'''


          for model_class in self.all_model_classes:
              if model_class.__name__ == "DPTForDepthEstimation":
                  continue

              SCREAMING_SNAKE_CASE_ :    int       		=						self.model_tester.prepare_config_and_inputs_for_common()
              SCREAMING_SNAKE_CASE_ :    Optional[int]       		=						False
              SCREAMING_SNAKE_CASE_ :    str       		=						True

              if model_class in get_values(lowercase__) or not model_class.supports_gradient_checkpointing:
                  continue
              SCREAMING_SNAKE_CASE_ :    Tuple       		=						model_class(lowercase__)
              model.to(lowercase__)
              model.gradient_checkpointing_enable()
              model.train()
              SCREAMING_SNAKE_CASE_ :    Tuple       		=						self._prepare_for_class(lowercase__		,      lowercase__		,      return_labels=lowercase__)
              SCREAMING_SNAKE_CASE_ :    Union[str, Any]       		=						model(**lowercase__).loss
              loss.backward()
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[int]):




          '''simple docstring'''


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

          SCREAMING_SNAKE_CASE_ :    List[Any]       		=						_config_zero_init(lowercase__)
          for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_ :    Tuple       		=						model_class(config=lowercase__)
              # Skip the check for the backbone
              SCREAMING_SNAKE_CASE_ :    List[Any]       		=						[]
              for name, module in model.named_modules():
                  if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                      SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						[F'{name}.{key}' for key in module.state_dict().keys()]
                      break

              for name, param in model.named_parameters():
                  if param.requires_grad:
                      if name in backbone_params:
                          continue
                      self.assertIn(
                          ((param.data.mean() * 1e9).round() / 1e9).item()		,      [0.0, 1.0]		,      msg=F'Parameter {name} of model {model_class} seems not properly initialized'		,      )
      @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
      def _SCREAMING_SNAKE_CASE					(		self	:    Optional[int]):




          '''simple docstring'''


          pass
      @slow
      def _SCREAMING_SNAKE_CASE					(		self	:    Union[str, Any]):




          '''simple docstring'''


          for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
              SCREAMING_SNAKE_CASE_ :    Optional[int]       		=						DPTModel.from_pretrained(lowercase__)
              self.assertIsNotNone(lowercase__)



      def _SCREAMING_SNAKE_CASE					(		self	:    Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    Tuple       		=						self.model_tester.prepare_config_and_inputs_for_common()
          SCREAMING_SNAKE_CASE_ :    List[str]       		=						'''add'''
          with self.assertRaises(lowercase__):
              SCREAMING_SNAKE_CASE_ :    Optional[Any]       		=						DPTForDepthEstimation(lowercase__)



def    _A     ()					->			Dict:
    """simple docstring"""






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





@require_torch
@require_vision
@slow
class 				lowerCAmelCase__							(     unittest.TestCase					):






      '''simple docstring'''

      def _SCREAMING_SNAKE_CASE					(		self	:    str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_ :    str       		=						DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''')
          SCREAMING_SNAKE_CASE_ :    str       		=						DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''').to(lowercase__)

          SCREAMING_SNAKE_CASE_ :    List[str]       		=						prepare_img()
          SCREAMING_SNAKE_CASE_ :    Tuple       		=						image_processor(images=lowercase__		,      return_tensors='''pt''').to(lowercase__)

          # forward pass
          with torch.no_grad():
              SCREAMING_SNAKE_CASE_ :    List[Any]       		=						model(**lowercase__)
              SCREAMING_SNAKE_CASE_ :    str       		=						outputs.predicted_depth

          # verify the predicted depth
          SCREAMING_SNAKE_CASE_ :    Union[str, Any]       		=						torch.Size((1, 384, 384))
          self.assertEqual(predicted_depth.shape		,      lowercase__)

          SCREAMING_SNAKE_CASE_ :    List[str]       		=						torch.tensor(
              [[[5.64_37, 5.61_46, 5.65_11], [5.43_71, 5.56_49, 5.59_58], [5.52_15, 5.51_84, 5.52_93]]]).to(lowercase__)

          self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100		,      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


lowerCAmelCase       		=    logging.get_logger(__name__)

lowerCAmelCase       		=    {
    """google/mobilenet_v2_1.4_224""": """https://huggingface.co/google/mobilenet_v2_1.4_224/resolve/main/config.json""",
    """google/mobilenet_v2_1.0_224""": """https://huggingface.co/google/mobilenet_v2_1.0_224/resolve/main/config.json""",
    """google/mobilenet_v2_0.75_160""": """https://huggingface.co/google/mobilenet_v2_0.75_160/resolve/main/config.json""",
    """google/mobilenet_v2_0.35_96""": """https://huggingface.co/google/mobilenet_v2_0.35_96/resolve/main/config.json""",
    # See all MobileNetV2 models at https://huggingface.co/models?filter=mobilenet_v2
}




class 							lowerCamelCase   (  _UpperCamelCase ):
	_lowerCAmelCase     :		Optional[Any]										=						'''mobilenet_v2'''


	def __init__(    self				,     lowercase__=3				,     lowercase__=2_2_4				,     lowercase__=1.0				,     lowercase__=8				,     lowercase__=8				,     lowercase__=6				,     lowercase__=3_2				,     lowercase__=True				,     lowercase__=True				,     lowercase__="relu6"				,     lowercase__=True				,     lowercase__=0.8				,     lowercase__=0.0_2				,     lowercase__=0.0_0_1				,     lowercase__=2_5_5				,     **lowercase__				,     ):
							super().__init__(**lowercase__)

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

							__UpperCAmelCase			:							Optional[int]	    =	num_channels
							__UpperCAmelCase			:							Optional[Any]	    =	image_size
							__UpperCAmelCase			:							Dict	    =	depth_multiplier
							__UpperCAmelCase			:							Optional[Any]	    =	depth_divisible_by
							__UpperCAmelCase			:							Union[str, Any]	    =	min_depth
							__UpperCAmelCase			:							Dict	    =	expand_ratio
							__UpperCAmelCase			:							int	    =	output_stride
							__UpperCAmelCase			:							Tuple	    =	first_layer_is_expansion
							__UpperCAmelCase			:							Union[str, Any]	    =	finegrained_output
							__UpperCAmelCase			:							int	    =	hidden_act
							__UpperCAmelCase			:							Tuple	    =	tf_padding
							__UpperCAmelCase			:							List[str]	    =	classifier_dropout_prob
							__UpperCAmelCase			:							Optional[Any]	    =	initializer_range
							__UpperCAmelCase			:							List[str]	    =	layer_norm_eps
							__UpperCAmelCase			:							Optional[int]	    =	semantic_loss_ignore_index






class 							lowerCamelCase   (  _UpperCamelCase ):
	_lowerCAmelCase     :		Tuple										=						version.parse('''1.11''' )


	@property
	def  A(    self):
							return OrderedDict([('''pixel_values''', {0: '''batch'''})])


	@property
	def  A(    self):
							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):
							return 1e-4

