





'''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 							__SCREAMING_SNAKE_CASE			:
      '''simple docstring'''



      def __init__(							self    : str   ,UpperCamelCase    : List[Any]   ,UpperCamelCase    : Any=2   ,UpperCamelCase    : Union[str, Any]=32   ,UpperCamelCase    : Tuple=16   ,UpperCamelCase    : str=3   ,UpperCamelCase    : Optional[int]=True   ,UpperCamelCase    : Optional[Any]=True   ,UpperCamelCase    : Optional[int]=32   ,UpperCamelCase    : str=4   ,UpperCamelCase    : List[str]=[0, 1, 2, 3]   ,UpperCamelCase    : Optional[int]=4   ,UpperCamelCase    : Optional[Any]=37   ,UpperCamelCase    : Optional[int]="gelu"   ,UpperCamelCase    : Union[str, Any]=0.1   ,UpperCamelCase    : List[str]=0.1   ,UpperCamelCase    : Union[str, Any]=0.0_2   ,UpperCamelCase    : Tuple=3   ,UpperCamelCase    : Any=False   ,UpperCamelCase    : List[str]=None   ,)		->  List[Any]:
           _lowercase							:      Union[str, Any]  						=							parent
           _lowercase							:      Any  						=							batch_size
           _lowercase							:      List[Any]  						=							image_size
           _lowercase							:      Optional[Any]  						=							patch_size
           _lowercase							:      List[str]  						=							num_channels
           _lowercase							:      Any  						=							is_training
           _lowercase							:      Optional[int]  						=							use_labels
           _lowercase							:      Union[str, Any]  						=							hidden_size
           _lowercase							:      Any  						=							num_hidden_layers
           _lowercase							:      Tuple  						=							backbone_out_indices
           _lowercase							:      Dict  						=							num_attention_heads
           _lowercase							:      Dict  						=							intermediate_size
           _lowercase							:      List[Any]  						=							hidden_act
           _lowercase							:      Optional[int]  						=							hidden_dropout_prob
           _lowercase							:      Union[str, Any]  						=							attention_probs_dropout_prob
           _lowercase							:      str  						=							initializer_range
           _lowercase							:      Tuple  						=							num_labels
           _lowercase							:      Tuple  						=							scope
           _lowercase							:      Dict  						=							is_hybrid
           # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
           _lowercase							:      Dict  						=							(image_size // patch_size) ** 2
           _lowercase							:      Tuple  						=							num_patches + 1

      def   _lowerCamelCase		(							self    : List[Any]  )		->  Optional[int]:
           _lowercase							:      List[str]  						=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

           _lowercase							:      List[str]  						=							self.get_config()

           return config, pixel_values, labels

      def   _lowerCamelCase		(							self    : Dict  )		->  List[Any]:
           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=UpperCamelCase   ,initializer_range=self.initializer_range   ,is_hybrid=self.is_hybrid   ,)

      def   _lowerCamelCase		(							self    : Optional[Any]   ,UpperCamelCase    : List[str]   ,UpperCamelCase    : str   ,UpperCamelCase    : Tuple  )		->  Optional[int]:
           _lowercase							:      Any  						=							DPTModel(config=UpperCamelCase  )
           model.to(UpperCamelCase  )
           model.eval()
           _lowercase							:      Any  						=							model(UpperCamelCase  )
           self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, self.seq_length, self.hidden_size)  )

      def   _lowerCamelCase		(							self    : List[str]   ,UpperCamelCase    : Dict   ,UpperCamelCase    : Union[str, Any]   ,UpperCamelCase    : Tuple  )		->  Any:
           _lowercase							:      Dict  						=							self.num_labels
           _lowercase							:      List[str]  						=							DPTForDepthEstimation(UpperCamelCase  )
           model.to(UpperCamelCase  )
           model.eval()
           _lowercase							:      Any  						=							model(UpperCamelCase  )
           self.parent.assertEqual(result.predicted_depth.shape   ,(self.batch_size, self.image_size, self.image_size)  )

      def   _lowerCamelCase		(							self    : Tuple   ,UpperCamelCase    : Union[str, Any]   ,UpperCamelCase    : Optional[Any]   ,UpperCamelCase    : List[str]  )		->  int:
           _lowercase							:      Optional[Any]  						=							self.num_labels
           _lowercase							:      Dict  						=							DPTForSemanticSegmentation(UpperCamelCase  )
           model.to(UpperCamelCase  )
           model.eval()
           _lowercase							:      List[str]  						=							model(UpperCamelCase   ,labels=UpperCamelCase  )
           self.parent.assertEqual(
               result.logits.shape   ,(self.batch_size, self.num_labels, self.image_size, self.image_size)  )



      def   _lowerCamelCase		(							self    : List[str]  )		->  Dict:
           _lowercase							:      str  						=							self.prepare_config_and_inputs()
           _lowercase							:      Dict  						=							config_and_inputs
           _lowercase							:      Union[str, Any]  						=							{'pixel_values': pixel_values}
           return config, inputs_dict




@require_torch
class 							__SCREAMING_SNAKE_CASE			(       lowerCAmelCase__							,   lowerCAmelCase__							,   unittest.TestCase      ):
      '''simple docstring'''



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

      lowerCAmelCase__       :      Optional[int] 		=		False
      lowerCAmelCase__       :      Tuple 		=		False
      lowerCAmelCase__       :      Tuple 		=		False

      def   _lowerCamelCase		(							self    : Any  )		->  Optional[Any]:
           _lowercase							:      Dict  						=							DPTModelTester(self  )
           _lowercase							:      List[Any]  						=							ConfigTester(self   ,config_class=UpperCamelCase   ,has_text_modality=UpperCamelCase   ,hidden_size=37  )

      def   _lowerCamelCase		(							self    : int  )		->  Optional[int]:
           self.config_tester.run_common_tests()

      @unittest.skip(reason='DPT does not use inputs_embeds'  )
      def   _lowerCamelCase		(							self    : List[Any]  )		->  List[Any]:
           pass

      def   _lowerCamelCase		(							self    : int  )		->  Tuple:
           _lowercase							:      List[str]  						=							self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                _lowercase							:      Dict  						=							model_class(UpperCamelCase  )
                self.assertIsInstance(model.get_input_embeddings()   ,(nn.Module)  )
                _lowercase							:      Dict  						=							model.get_output_embeddings()
                self.assertTrue(x is None or isinstance(UpperCamelCase   ,nn.Linear  )  )

      def   _lowerCamelCase		(							self    : List[str]  )		->  List[str]:
           _lowercase							:      Union[str, Any]  						=							self.model_tester.prepare_config_and_inputs_for_common()

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

                _lowercase							:      Union[str, Any]  						=							['pixel_values']
                self.assertListEqual(arg_names[:1]   ,UpperCamelCase  )

      def   _lowerCamelCase		(							self    : Dict  )		->  str:
           _lowercase							:      str  						=							self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCamelCase  )

      def   _lowerCamelCase		(							self    : Union[str, Any]  )		->  Dict:
           _lowercase							:      List[str]  						=							self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_depth_estimation(*UpperCamelCase  )

      def   _lowerCamelCase		(							self    : List[Any]  )		->  Dict:
           _lowercase							:      Any  						=							self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*UpperCamelCase  )

      def   _lowerCamelCase		(							self    : Tuple  )		->  Tuple:
           for model_class in self.all_model_classes:
                if model_class.__name__ == "DPTForDepthEstimation":
                     continue

                _lowercase							:      str  						=							self.model_tester.prepare_config_and_inputs_for_common()
                _lowercase							:      str  						=							True

                if model_class in get_values(UpperCamelCase  ):
                     continue

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

      def   _lowerCamelCase		(							self    : int  )		->  Optional[int]:
           for model_class in self.all_model_classes:
                if model_class.__name__ == "DPTForDepthEstimation":
                     continue

                _lowercase							:      Tuple  						=							self.model_tester.prepare_config_and_inputs_for_common()
                _lowercase							:      Optional[Any]  						=							False
                _lowercase							:      List[str]  						=							True

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

      def   _lowerCamelCase		(							self    : str  )		->  List[str]:
           _lowercase							:      Tuple  						=							self.model_tester.prepare_config_and_inputs_for_common()

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



      @slow
      def   _lowerCamelCase		(							self    : Dict  )		->  Optional[int]:
           for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                _lowercase							:      Optional[int]  						=							DPTModel.from_pretrained(UpperCamelCase  )
                self.assertIsNotNone(UpperCamelCase  )

def 		SCREAMING_SNAKE_CASE      (					)			->						Optional[int]:

     '''simple docstring'''




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




@require_torch
@require_vision
@slow
class 							__SCREAMING_SNAKE_CASE			(       unittest.TestCase      ):
      '''simple docstring'''



      def   _lowerCamelCase		(							self    : List[Any]  )		->  Any:
           _lowercase							:      Any  						=							DPTImageProcessor.from_pretrained('Intel/dpt-large'  )
           _lowercase							:      Tuple  						=							DPTForDepthEstimation.from_pretrained('Intel/dpt-large'  ).to(UpperCamelCase  )

           _lowercase							:      Tuple  						=							prepare_img()
           _lowercase							:      Dict  						=							image_processor(images=UpperCamelCase   ,return_tensors='pt'  ).to(UpperCamelCase  )

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

           # verify the predicted depth
           _lowercase							:      Optional[int]  						=							torch.Size((1, 384, 384)  )
           self.assertEqual(predicted_depth.shape   ,UpperCamelCase  )

           _lowercase							:      Dict  						=							torch.tensor(
               [[6.3_1_9_9, 6.3_6_2_9, 6.4_1_4_8], [6.3_8_5_0, 6.3_6_1_5, 6.4_1_6_6], [6.3_5_1_9, 6.3_1_7_6, 6.3_5_7_5]]  ).to(UpperCamelCase  )

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

      def   _lowerCamelCase		(							self    : int  )		->  List[str]:
           _lowercase							:      List[str]  						=							DPTImageProcessor.from_pretrained('Intel/dpt-large-ade'  )
           _lowercase							:      Any  						=							DPTForSemanticSegmentation.from_pretrained('Intel/dpt-large-ade'  ).to(UpperCamelCase  )

           _lowercase							:      Union[str, Any]  						=							prepare_img()
           _lowercase							:      int  						=							image_processor(images=UpperCamelCase   ,return_tensors='pt'  ).to(UpperCamelCase  )

           # forward pass
           with torch.no_grad():
                _lowercase							:      List[str]  						=							model(**UpperCamelCase  )

           # verify the logits
           _lowercase							:      int  						=							torch.Size((1, 150, 480, 480)  )
           self.assertEqual(outputs.logits.shape   ,UpperCamelCase  )

           _lowercase							:      str  						=							torch.tensor(
               [[4.0_4_8_0, 4.2_4_2_0, 4.4_3_6_0], [4.3_1_2_4, 4.5_6_9_3, 4.8_2_6_1], [4.5_7_6_8, 4.8_9_6_5, 5.2_1_6_3]]  ).to(UpperCamelCase  )

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



      def   _lowerCamelCase		(							self    : Any  )		->  Dict:
           _lowercase							:      List[Any]  						=							DPTImageProcessor.from_pretrained('Intel/dpt-large-ade'  )
           _lowercase							:      Optional[Any]  						=							DPTForSemanticSegmentation.from_pretrained('Intel/dpt-large-ade'  ).to(UpperCamelCase  )

           _lowercase							:      Optional[Any]  						=							prepare_img()
           _lowercase							:      Dict  						=							image_processor(images=UpperCamelCase   ,return_tensors='pt'  ).to(UpperCamelCase  )

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

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

           _lowercase							:      int  						=							image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase   ,target_sizes=[(500, 300)]  )
           _lowercase							:      Dict  						=							torch.Size((500, 300)  )
           self.assertEqual(segmentation[0].shape   ,UpperCamelCase  )

           _lowercase							:      int  						=							image_processor.post_process_semantic_segmentation(outputs=UpperCamelCase  )
           _lowercase							:      Union[str, Any]  						=							torch.Size((480, 480)  )
           self.assertEqual(segmentation[0].shape   ,UpperCamelCase  )






'''simple docstring'''







import warnings

from ...utils import logging
from .image_processing_mobilenet_va import MobileNetVaImageProcessor


A						    =							logging.get_logger(__name__)



class 							__SCREAMING_SNAKE_CASE			(       lowerCAmelCase__      ):
      '''simple docstring'''



      def __init__(							self    : Tuple   ,*UpperCamelCase    : str   ,**UpperCamelCase    : List[Any]  )		->  None:
           warnings.warn(
               'The class MobileNetV2FeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
               ' Please use MobileNetV2ImageProcessor instead.'   ,UpperCamelCase   ,)
           super().__init__(*UpperCamelCase   ,**UpperCamelCase  )