


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


     def __init__(   self				:  Dict				,						lowerCamelCase__				:  int				,						lowerCamelCase__				:  Union[str, Any]=2				,						lowerCamelCase__				:  Any=32				,						lowerCamelCase__				:  int=16				,						lowerCamelCase__				:  List[str]=3				,						lowerCamelCase__				:  Tuple=True				,						lowerCamelCase__				:  List[str]=True				,						lowerCamelCase__				:  List[Any]=32				,						lowerCamelCase__				:  Dict=4				,						lowerCamelCase__				:  Any=[0, 1, 2, 3]				,						lowerCamelCase__				:  int=4				,						lowerCamelCase__				:  Dict=37				,						lowerCamelCase__				:  Any="gelu"				,						lowerCamelCase__				:  List[str]=0.1				,						lowerCamelCase__				:  Optional[Any]=0.1				,						lowerCamelCase__				:  Tuple=0.02				,						lowerCamelCase__				:  List[Any]=3				,						lowerCamelCase__				:  Optional[Any]=False				,						lowerCamelCase__				:  int=None				,						)	->   Optional[int]:





      '''simple docstring'''






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


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     List[Any] 							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

      UpperCamelCase__       :     Any 							= None
      if self.use_labels:
       UpperCamelCase__       :     int 							= 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				:  Optional[Any]      )	->   Dict:





      '''simple docstring'''






      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=lowerCamelCase__				,						initializer_range=self.initializer_range				,						is_hybrid=self.is_hybrid				,						)


     def   UpperCAmelCase__						(   self				:  Optional[Any]				,						lowerCamelCase__				:  Union[str, Any]				,						lowerCamelCase__				:  str				,						lowerCamelCase__				:  Optional[int]      )	->   Dict:





      '''simple docstring'''






      UpperCamelCase__       :     Dict 							= DPTModel(config=lowerCamelCase__      )
      model.to(lowerCamelCase__      )
      model.eval()
      UpperCamelCase__       :     Tuple 							= model(lowerCamelCase__      )
      self.parent.assertEqual(result.last_hidden_state.shape				,						(self.batch_size, self.seq_length, self.hidden_size)      )


     def   UpperCAmelCase__						(   self				:  Optional[Any]				,						lowerCamelCase__				:  Any				,						lowerCamelCase__				:  Union[str, Any]				,						lowerCamelCase__				:  Any      )	->   str:





      '''simple docstring'''






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


     def   UpperCAmelCase__						(   self				:  Tuple				,						lowerCamelCase__				:  List[Any]				,						lowerCamelCase__				:  List[str]				,						lowerCamelCase__				:  Dict      )	->   str:





      '''simple docstring'''






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


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





      '''simple docstring'''






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



@require_torch
class    __magic_name__						(  __lowerCAmelCase       ,					__lowerCAmelCase       ,					unittest.TestCase):
     A:		int								=   (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
     A:		Union[str, Any]								=   (
         {
             "depth-estimation": DPTForDepthEstimation,
             "feature-extraction": DPTModel,
             "image-segmentation": DPTForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     A:		str								=   False
     A:		Tuple								=   False
     A:		int								=   False


     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Union[str, Any]:





      '''simple docstring'''






      UpperCamelCase__       :     int 							= DPTModelTester(self      )
      UpperCamelCase__       :     Optional[Any] 							= ConfigTester(self				,						config_class=lowerCamelCase__				,						has_text_modality=lowerCamelCase__				,						hidden_size=37      )


     def   UpperCAmelCase__						(   self				:  Any      )	->   List[Any]:





      '''simple docstring'''






      self.config_tester.run_common_tests()


     @unittest.skip(reason='''DPT does not use inputs_embeds'''      )
     def   UpperCAmelCase__						(   self				:  Union[str, Any]      )	->   List[str]:





      '''simple docstring'''






      pass


     def   UpperCAmelCase__						(   self				:  List[str]      )	->   Union[str, Any]:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     Union[str, Any] 							= self.model_tester.prepare_config_and_inputs_for_common()

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


     def   UpperCAmelCase__						(   self				:  int      )	->   int:





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     List[str] 							= self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       UpperCamelCase__       :     Dict 							= model_class(lowerCamelCase__      )
       UpperCamelCase__       :     Dict 							= inspect.signature(model.forward      )
       # signature.parameters is an OrderedDict => so arg_names order is deterministic
       UpperCamelCase__       :     Dict 							= [*signature.parameters.keys()]

       UpperCamelCase__       :     List[str] 							= ['''pixel_values''']
       self.assertListEqual(arg_names[:1]				,						lowerCamelCase__      )


     def   UpperCAmelCase__						(   self				:  Tuple      )	->   Optional[int]:





      '''simple docstring'''






      UpperCamelCase__       :     Optional[int] 							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase__      )


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     Union[str, Any] 							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_depth_estimation(*lowerCamelCase__      )


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





      '''simple docstring'''






      UpperCamelCase__       :     List[str] 							= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase__      )


     def   UpperCAmelCase__						(   self				:  List[str]      )	->   Optional[Any]:





      '''simple docstring'''






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

       UpperCamelCase__							,					UpperCamelCase__       :     List[Any] 							= self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__       :     int 							= True

       if model_class in get_values(lowerCamelCase__      ):
        continue

       UpperCamelCase__       :     str 							= model_class(lowerCamelCase__      )
       model.to(lowerCamelCase__      )
       model.train()
       UpperCamelCase__       :     str 							= self._prepare_for_class(lowerCamelCase__				,						lowerCamelCase__				,						return_labels=lowerCamelCase__      )
       UpperCamelCase__       :     Dict 							= model(**lowerCamelCase__      ).loss
       loss.backward()


     def   UpperCAmelCase__						(   self				:  Dict      )	->   Dict:





      '''simple docstring'''






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

       UpperCamelCase__							,					UpperCamelCase__       :     Tuple 							= self.model_tester.prepare_config_and_inputs_for_common()
       UpperCamelCase__       :     Union[str, Any] 							= False
       UpperCamelCase__       :     List[Any] 							= True

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


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





      '''simple docstring'''






      UpperCamelCase__							,					UpperCamelCase__       :     int 							= self.model_tester.prepare_config_and_inputs_for_common()

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





      '''simple docstring'''






      pass


     @slow
     def   UpperCAmelCase__						(   self				:  Optional[Any]      )	->   Tuple:





      '''simple docstring'''






      for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCamelCase__       :     str 							= DPTModel.from_pretrained(lowerCamelCase__      )
       self.assertIsNotNone(lowerCamelCase__      )



def       _a	(					):







 """simple docstring"""



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






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


     def   UpperCAmelCase__						(   self				:  Tuple      )	->   List[Any]:





      '''simple docstring'''






      UpperCamelCase__       :     Optional[Any] 							= DPTImageProcessor.from_pretrained('''Intel/dpt-large'''      )
      UpperCamelCase__       :     Union[str, Any] 							= DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''      ).to(lowerCamelCase__      )

      UpperCamelCase__       :     Optional[int] 							= prepare_img()
      UpperCamelCase__       :     Union[str, Any] 							= image_processor(images=lowerCamelCase__				,						return_tensors='''pt'''      ).to(lowerCamelCase__      )

      # forward pass
      with torch.no_grad():
       UpperCamelCase__       :     Dict 							= model(**lowerCamelCase__      )
       UpperCamelCase__       :     Tuple 							= outputs.predicted_depth

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

      UpperCamelCase__       :     List[Any] 							= torch.tensor(
          [[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]]      ).to(lowerCamelCase__      )

      self.assertTrue(torch.allclose(outputs.predicted_depth[0, :3, :3]				,						lowerCamelCase__				,						atol=1E-4      )      )


     def   UpperCAmelCase__						(   self				:  List[Any]      )	->   Optional[int]:





      '''simple docstring'''






      UpperCamelCase__       :     Tuple 							= DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
      UpperCamelCase__       :     str 							= DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(lowerCamelCase__      )

      UpperCamelCase__       :     str 							= prepare_img()
      UpperCamelCase__       :     Union[str, Any] 							= image_processor(images=lowerCamelCase__				,						return_tensors='''pt'''      ).to(lowerCamelCase__      )

      # forward pass
      with torch.no_grad():
       UpperCamelCase__       :     Optional[Any] 							= model(**lowerCamelCase__      )

      # verify the logits
      UpperCamelCase__       :     Optional[Any] 							= torch.Size((1, 150, 480, 480)      )
      self.assertEqual(outputs.logits.shape				,						lowerCamelCase__      )

      UpperCamelCase__       :     Optional[int] 							= torch.tensor(
          [[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]]      ).to(lowerCamelCase__      )

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


     def   UpperCAmelCase__						(   self				:  Dict      )	->   List[str]:





      '''simple docstring'''






      UpperCamelCase__       :     Any 							= DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
      UpperCamelCase__       :     Optional[Any] 							= DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(lowerCamelCase__      )

      UpperCamelCase__       :     Tuple 							= prepare_img()
      UpperCamelCase__       :     Union[str, Any] 							= image_processor(images=lowerCamelCase__				,						return_tensors='''pt'''      ).to(lowerCamelCase__      )

      # forward pass
      with torch.no_grad():
       UpperCamelCase__       :     List[Any] 							= model(**lowerCamelCase__      )

      UpperCamelCase__       :     Optional[int] 							= outputs.logits.detach().cpu()

      UpperCamelCase__       :     Optional[int] 							= image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__				,						target_sizes=[(500, 300)]      )
      UpperCamelCase__       :     List[str] 							= torch.Size((500, 300)      )
      self.assertEqual(segmentation[0].shape				,						lowerCamelCase__      )

      UpperCamelCase__       :     List[Any] 							= image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase__      )
      UpperCamelCase__       :     List[str] 							= torch.Size((480, 480)      )
      self.assertEqual(segmentation[0].shape				,						lowerCamelCase__      )






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


__UpperCamelCase							:							List[Any]    							=					{
    "configuration_mpnet": ["MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP", "MPNetConfig"],
    "tokenization_mpnet": ["MPNetTokenizer"],
}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							Union[str, Any]    							=					["MPNetTokenizerFast"]

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							Union[str, Any]    							=					[
           "MPNET_PRETRAINED_MODEL_ARCHIVE_LIST",
           "MPNetForMaskedLM",
           "MPNetForMultipleChoice",
           "MPNetForQuestionAnswering",
           "MPNetForSequenceClassification",
           "MPNetForTokenClassification",
           "MPNetLayer",
           "MPNetModel",
           "MPNetPreTrainedModel",
       ]

try:
       if not is_tf_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       __UpperCamelCase							:							List[Any]    							=					[
           "TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST",
           "TFMPNetEmbeddings",
           "TFMPNetForMaskedLM",
           "TFMPNetForMultipleChoice",
           "TFMPNetForQuestionAnswering",
           "TFMPNetForSequenceClassification",
           "TFMPNetForTokenClassification",
           "TFMPNetMainLayer",
           "TFMPNetModel",
           "TFMPNetPreTrainedModel",
       ]


if TYPE_CHECKING:
       from .configuration_mpnet import MPNET_PRETRAINED_CONFIG_ARCHIVE_MAP, MPNetConfig
       from .tokenization_mpnet import MPNetTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_mpnet_fast import MPNetTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mpnet import (
                  MPNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MPNetForMaskedLM,
                  MPNetForMultipleChoice,
                  MPNetForQuestionAnswering,
                  MPNetForSequenceClassification,
                  MPNetForTokenClassification,
                  MPNetLayer,
                  MPNetModel,
                  MPNetPreTrainedModel,
              )

       try:
              if not is_tf_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_tf_mpnet import (
                  TF_MPNET_PRETRAINED_MODEL_ARCHIVE_LIST,
                  TFMPNetEmbeddings,
                  TFMPNetForMaskedLM,
                  TFMPNetForMultipleChoice,
                  TFMPNetForQuestionAnswering,
                  TFMPNetForSequenceClassification,
                  TFMPNetForTokenClassification,
                  TFMPNetMainLayer,
                  TFMPNetModel,
                  TFMPNetPreTrainedModel,
              )

else:
       import sys

       __UpperCamelCase							:							Tuple    							=					_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


