





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




   """simple docstring"""



   def __init__(   self   ,    lowercase   ,    lowercase=2   ,    lowercase=32   ,    lowercase=16   ,    lowercase=3   ,    lowercase=True   ,    lowercase=True   ,    lowercase=32   ,    lowercase=4   ,    lowercase=[0, 1, 2, 3]   ,    lowercase=4   ,    lowercase=37   ,    lowercase="gelu"   ,    lowercase=0.1   ,    lowercase=0.1   ,    lowercase=0.02   ,    lowercase=3   ,    lowercase=[1, 384, 24, 24]   ,    lowercase=True   ,    lowercase=None   ,    )     ->		Tuple:







          '''simple docstring'''

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

   def 				__lowercase						(   self)     ->		Tuple:







          '''simple docstring'''

          a__		:      List[str]					=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          a__		:      List[Any]					=							self.get_config()

          return config, pixel_values, labels

   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

          a__		:      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 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase)     ->		Union[str, Any]:







          '''simple docstring'''

          a__		:      Optional[int]					=							DPTModel(config=__a)
          model.to(__a)
          model.eval()
          a__		:      Tuple					=							model(__a)
          self.parent.assertEqual(result.last_hidden_state.shape   ,    (self.batch_size, self.seq_length, self.hidden_size))

   def 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase)     ->		Optional[int]:







          '''simple docstring'''

          a__		:      int					=							self.num_labels
          a__		:      int					=							DPTForDepthEstimation(__a)
          model.to(__a)
          model.eval()
          a__		:      Optional[int]					=							model(__a)
          self.parent.assertEqual(result.predicted_depth.shape   ,    (self.batch_size, self.image_size, self.image_size))

   def 				__lowercase						(   self   ,    lowercase   ,    lowercase   ,    lowercase)     ->		int:







          '''simple docstring'''

          a__		:      List[Any]					=							self.num_labels
          a__		:      Dict					=							DPTForSemanticSegmentation(__a)
          model.to(__a)
          model.eval()
          a__		:      str					=							model(__a   ,    labels=__a)
          self.parent.assertEqual(
              result.logits.shape   ,    (self.batch_size, self.num_labels, self.image_size, self.image_size))

   def 				__lowercase						(   self)     ->		List[str]:







          '''simple docstring'''

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





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




   """simple docstring"""



   __A  :							Union[str, Any]			    =    (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
   __A  :							str			    =    (
       {
           "depth-estimation": DPTForDepthEstimation,
           "feature-extraction": DPTModel,
           "image-segmentation": DPTForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A  :							List[str]			    =    False
   __A  :							Any			    =    False
   __A  :							int			    =    False

   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

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

   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

          self.config_tester.run_common_tests()

   @unittest.skip(reason='DPT does not use inputs_embeds')
   def 				__lowercase						(   self)     ->		Any:







          '''simple docstring'''

          pass

   def 				__lowercase						(   self)     ->		str:







          '''simple docstring'''

          a__		:      int					=							self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 a__		:      List[str]					=							model_class(__a)
                 self.assertIsInstance(model.get_input_embeddings()   ,    (nn.Module))
                 a__		:      Any					=							model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(__a   ,    nn.Linear))

   def 				__lowercase						(   self)     ->		List[str]:







          '''simple docstring'''

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

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

                 a__		:      int					=							["pixel_values"]
                 self.assertListEqual(arg_names[:1]   ,    __a)

   def 				__lowercase						(   self)     ->		List[str]:







          '''simple docstring'''

          a__		:      List[Any]					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__a)

   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

          a__		:      Dict					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_depth_estimation(*__a)

   def 				__lowercase						(   self)     ->		Dict:







          '''simple docstring'''

          a__		:      Dict					=							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*__a)

   def 				__lowercase						(   self)     ->		Optional[Any]:







          '''simple docstring'''

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

                 a__		:      str					=							self.model_tester.prepare_config_and_inputs_for_common()
                 a__		:      int					=							True

                 if model_class in get_values(__a):
                        continue

                 a__		:      Union[str, Any]					=							model_class(__a)
                 model.to(__a)
                 model.train()
                 a__		:      int					=							self._prepare_for_class(__a   ,    __a   ,    return_labels=__a)
                 a__		:      Optional[int]					=							model(**__a).loss
                 loss.backward()

   def 				__lowercase						(   self)     ->		List[str]:







          '''simple docstring'''

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

                 a__		:      Optional[int]					=							self.model_tester.prepare_config_and_inputs_for_common()
                 a__		:      Dict					=							False
                 a__		:      Dict					=							True

                 if model_class in get_values(__a) or not model_class.supports_gradient_checkpointing:
                        continue
                 a__		:      Optional[int]					=							model_class(__a)
                 model.to(__a)
                 model.gradient_checkpointing_enable()
                 model.train()
                 a__		:      Tuple					=							self._prepare_for_class(__a   ,    __a   ,    return_labels=__a)
                 a__		:      Optional[Any]					=							model(**__a).loss
                 loss.backward()

   def 				__lowercase						(   self)     ->		Optional[int]:







          '''simple docstring'''

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

          a__		:      Tuple					=							_config_zero_init(__a)
          for model_class in self.all_model_classes:
                 a__		:      int					=							model_class(config=__a)
                 # Skip the check for the backbone
                 a__		:      int					=							[]
                 for name, module in model.named_modules():
                        if module.__class__.__name__ == "DPTViTHybridEmbeddings":
                               a__		:      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 				__lowercase						(   self)     ->		Optional[Any]:







          '''simple docstring'''

          pass

   @slow
   def 				__lowercase						(   self)     ->		List[str]:







          '''simple docstring'''

          for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
                 a__		:      Optional[Any]					=							DPTModel.from_pretrained(__a)
                 self.assertIsNotNone(__a)

   def 				__lowercase						(   self)     ->		str:







          '''simple docstring'''

          a__		:      int					=							self.model_tester.prepare_config_and_inputs_for_common()
          a__		:      Optional[Any]					=							"add"
          with self.assertRaises(__a):
                 a__		:      str					=							DPTForDepthEstimation(__a)



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





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




   """simple docstring"""



   def 				__lowercase						(   self)     ->		Tuple:







          '''simple docstring'''

          a__		:      List[Any]					=							DPTImageProcessor.from_pretrained('Intel/dpt-hybrid-midas')
          a__		:      Optional[int]					=							DPTForDepthEstimation.from_pretrained('Intel/dpt-hybrid-midas').to(__a)

          a__		:      List[Any]					=							prepare_img()
          a__		:      Dict					=							image_processor(images=__a   ,    return_tensors='pt').to(__a)

          # forward pass
          with torch.no_grad():
                 a__		:      Optional[Any]					=							model(**__a)
                 a__		:      int					=							outputs.predicted_depth

          # verify the predicted depth
          a__		:      Tuple					=							torch.Size((1, 384, 384))
          self.assertEqual(predicted_depth.shape   ,    __a)

          a__		:      Optional[int]					=							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))









"""simple docstring"""


from collections.abc import Callable

import numpy as np




def        lowercase__     (       lowercase_		,lowercase_		,lowercase_		,lowercase_		,lowercase_      )       ->		np.ndarray:




      """simple docstring"""

      _UpperCamelCase   :						List[str]    =							int(np.ceil((x_end - xa) / step_size      )      )
      _UpperCamelCase   :						Tuple    =							np.zeros((n + 1,)      )
      _UpperCamelCase   :						List[str]    =							ya
      _UpperCamelCase   :						List[Any]    =							xa

      for k in range(lowercase_      ):
            _UpperCamelCase   :						List[str]    =							y[k] + step_size * ode_func(lowercase_		,y[k]      )
            x += step_size

      return y


if __name__ == "__main__":
  import doctest

  doctest.testmod()
