





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       A__     :





      def __init__(				self ,							A_ ,							A_=2 ,							A_=32 ,							A_=16 ,							A_=3 ,							A_=True ,							A_=True ,							A_=32 ,							A_=4 ,							A_=[0, 1, 2, 3] ,							A_=4 ,							A_=37 ,							A_="gelu" ,							A_=0.1 ,							A_=0.1 ,							A_=0.02 ,							A_=3 ,							A_=[1, 384, 24, 24] ,							A_=True ,							A_=None ,							):
       '''simple docstring'''




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





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Dict 			=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

       UpperCamelCase			:      Tuple 			=     self.get_config()

       return config, pixel_values, labels





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      List[str] 			=     {
           "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=A_ ,							initializer_range=self.initializer_range ,							is_hybrid=self.is_hybrid ,							backbone_config=A_ ,							backbone_featmap_shape=self.backbone_featmap_shape ,							)





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     DPTModel(config=A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      List[Any] 			=     model(A_     )
       self.parent.assertEqual(result.last_hidden_state.shape ,							(self.batch_size, self.seq_length, self.hidden_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     self.num_labels
       UpperCamelCase			:      Dict 			=     DPTForDepthEstimation(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Dict 			=     model(A_     )
       self.parent.assertEqual(result.predicted_depth.shape ,							(self.batch_size, self.image_size, self.image_size)     )





      def  __UpperCamelCase(				self ,							A_ ,							A_ ,							A_     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.num_labels
       UpperCamelCase			:      int 			=     DPTForSemanticSegmentation(A_     )
       model.to(A_     )
       model.eval()
       UpperCamelCase			:      Dict 			=     model(A_ ,							labels=A_     )
       self.parent.assertEqual(
           result.logits.shape ,							(self.batch_size, self.num_labels, self.image_size, self.image_size)     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.prepare_config_and_inputs()
       UpperCamelCase			:      Optional[Any] 			=     config_and_inputs
       UpperCamelCase			:      List[Any] 			=     {"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class       A__     ( __snake_case ,     __snake_case ,     unittest.TestCase    ):
      _UpperCAmelCase			:Tuple							=     (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
      _UpperCAmelCase			:List[str]							=     (
          {
              'depth-estimation': DPTForDepthEstimation,
              'feature-extraction': DPTModel,
              'image-segmentation': DPTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _UpperCAmelCase			:Optional[Any]							=     False
      _UpperCAmelCase			:str							=     False
      _UpperCAmelCase			:Dict							=     False





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[int] 			=     DPTModelTester(self     )
       UpperCamelCase			:      str 			=     ConfigTester(self ,							config_class=A_ ,							has_text_modality=A_ ,							hidden_size=37     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       self.config_tester.run_common_tests()





      @unittest.skip(reason="DPT does not use inputs_embeds"     )
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




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

       for model_class in self.all_model_classes:
        UpperCamelCase			:      Tuple 			=     model_class(A_     )
        self.assertIsInstance(model.get_input_embeddings() ,							(nn.Module)     )
        UpperCamelCase			:      Optional[int] 			=     model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(A_ ,							nn.Linear     )     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Tuple 			=     self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCamelCase			:      Optional[int] 			=     ["pixel_values"]
        self.assertListEqual(arg_names[:1] ,							A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Optional[Any] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Any 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_depth_estimation(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      Union[str, Any] 			=     self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




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

        UpperCamelCase			:      Optional[int] 			=     self.model_tester.prepare_config_and_inputs_for_common()
        UpperCamelCase			:      List[Any] 			=     True

        if model_class in get_values(A_     ):
         continue

        UpperCamelCase			:      Optional[int] 			=     model_class(A_     )
        model.to(A_     )
        model.train()
        UpperCamelCase			:      Optional[int] 			=     self._prepare_for_class(A_ ,							A_ ,							return_labels=A_     )
        UpperCamelCase			:      Optional[int] 			=     model(**A_     ).loss
        loss.backward()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




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

        UpperCamelCase			:      Optional[Any] 			=     self.model_tester.prepare_config_and_inputs_for_common()
        UpperCamelCase			:      Any 			=     False
        UpperCamelCase			:      Optional[int] 			=     True

        if model_class in get_values(A_     ) or not model_class.supports_gradient_checkpointing:
         continue
        UpperCamelCase			:      str 			=     model_class(A_     )
        model.to(A_     )
        model.gradient_checkpointing_enable()
        model.train()
        UpperCamelCase			:      Any 			=     self._prepare_for_class(A_ ,							A_ ,							return_labels=A_     )
        UpperCamelCase			:      Any 			=     model(**A_     ).loss
        loss.backward()





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      str 			=     self.model_tester.prepare_config_and_inputs_for_common()

       UpperCamelCase			:      List[Any] 			=     _config_zero_init(A_     )
       for model_class in self.all_model_classes:
        UpperCamelCase			:      List[str] 			=     model_class(config=A_     )
        # Skip the check for the backbone
        UpperCamelCase			:      List[Any] 			=     []
        for name, module in model.named_modules():
         if module.__class__.__name__ == "DPTViTHybridEmbeddings":
          UpperCamelCase			:      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  __UpperCamelCase(				self     ):
       '''simple docstring'''




       pass





      @slow
      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
        UpperCamelCase			:      Dict 			=     DPTModel.from_pretrained(A_     )
        self.assertIsNotNone(A_     )





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase			:      Dict 			=     "add"
       with self.assertRaises(A_     ):
        UpperCamelCase			:      Optional[int] 			=     DPTForDepthEstimation(A_     )



def 	A_       (  )		->				Optional[Any]:
 UpperCamelCase			:      List[Any] 			=     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
 return image



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





      def  __UpperCamelCase(				self     ):
       '''simple docstring'''




       UpperCamelCase			:      int 			=     DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas"     )
       UpperCamelCase			:      Optional[Any] 			=     DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas"     ).to(A_     )

       UpperCamelCase			:      int 			=     prepare_img()
       UpperCamelCase			:      Tuple 			=     image_processor(images=A_ ,							return_tensors="pt"     ).to(A_     )

       # forward pass
       with torch.no_grad():
        UpperCamelCase			:      List[str] 			=     model(**A_     )
        UpperCamelCase			:      int 			=     outputs.predicted_depth

       # verify the predicted depth
       UpperCamelCase			:      str 			=     torch.Size((1, 384, 384)     )
       self.assertEqual(predicted_depth.shape ,							A_     )

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

       self.assertTrue(torch.allclose(outputs.predicted_depth[:3, :3, :3] / 100 ,							A_ ,							atol=1e-4     )     )







import math

import tensorflow as tf
from packaging import version



def 	A_       (  _lowerCAmelCase  )		->				Any:
 UpperCamelCase			:      List[Any] 			=     tf.convert_to_tensor(_lowerCAmelCase  )
 UpperCamelCase			:      Any 			=     0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0  )							,     x.dtype  )  ))

 return x * cdf



def 	A_       (  _lowerCAmelCase  )		->				Dict:
 UpperCamelCase			:      Union[str, Any] 			=     tf.convert_to_tensor(_lowerCAmelCase  )
 UpperCamelCase			:      List[Any] 			=     tf.cast(math.pi							,     x.dtype  )
 UpperCamelCase			:      Optional[Any] 			=     tf.cast(0.044_715							,     x.dtype  )
 UpperCamelCase			:      int 			=     0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi  ) * (x + coeff * tf.pow(_lowerCAmelCase							,     3  ))  ))

 return x * cdf



def 	A_       (  _lowerCAmelCase  )		->				List[Any]:
 UpperCamelCase			:      str 			=     tf.convert_to_tensor(_lowerCAmelCase  )

 return x * tf.tanh(tf.math.softplus(_lowerCAmelCase  )  )



def 	A_       (  _lowerCAmelCase  )		->				List[Any]:
 UpperCamelCase			:      Tuple 			=     tf.convert_to_tensor(_lowerCAmelCase  )
 UpperCamelCase			:      List[Any] 			=     tf.cast(0.044_715							,     x.dtype  )
 UpperCamelCase			:      Optional[Any] 			=     tf.cast(0.7_978_845_608							,     x.dtype  )

 return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x)  ))



def 	A_       (  _lowerCAmelCase  )		->				Optional[Any]:
 UpperCamelCase			:      Any 			=     tf.convert_to_tensor(_lowerCAmelCase  )
 UpperCamelCase			:      List[Any] 			=     tf.cast(1.702							,     x.dtype  )
 return x * tf.math.sigmoid(coeff * x  )



def 	A_       (  _lowerCAmelCase  )		->				List[Any]:
 return tf.clip_by_value(_gelu(_lowerCAmelCase  )							,     -10							,     10  )



def 	A_       (  _lowerCAmelCase							,     _lowerCAmelCase=-1  )		->				str:
 UpperCamelCase			,					UpperCamelCase			:      List[Any] 			=     tf.split(_lowerCAmelCase							,     2							,     axis=_lowerCAmelCase  )
 return a * tf.math.sigmoid(_lowerCAmelCase  )


if version.parse(tf.version.VERSION) >= version.parse("""2.4"""):



    def 	A_       (  _lowerCAmelCase  )		->				Any:
     return tf.keras.activations.gelu(_lowerCAmelCase							,     approximate=_lowerCAmelCase  )

    __lowerCamelCase :  Optional[int]										=  tf.keras.activations.gelu


    __lowerCamelCase :  int										=  approximate_gelu_wrap
else:
    __lowerCamelCase :  List[Any]										=  _gelu
    __lowerCamelCase :  Optional[Any]										=  _gelu_new


__lowerCamelCase :  Any										=  {
    """gelu""": gelu,
    """gelu_10""": gelu_aa,
    """gelu_fast""": gelu_fast,
    """gelu_new""": gelu_new,
    """glu""": glu,
    """mish""": mish,
    """quick_gelu""": quick_gelu,
    """relu""": tf.keras.activations.relu,
    """sigmoid""": tf.keras.activations.sigmoid,
    """silu""": tf.keras.activations.swish,
    """swish""": tf.keras.activations.swish,
    """tanh""": tf.keras.activations.tanh,
}



def 	A_       (  _lowerCAmelCase  )		->				Optional[Any]:
 if activation_string in ACTaFN:
  return ACTaFN[activation_string]
 else:
  raise KeyError(F"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()  )}"""  )
