import unittest

from transformers import LayoutLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

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


if is_torch_available():
     import torch

     from transformers import (
         LayoutLMForMaskedLM,
         LayoutLMForQuestionAnswering,
         LayoutLMForSequenceClassification,
         LayoutLMForTokenClassification,
         LayoutLMModel,
     )







class        UpperCAmelCase_					:




    def __init__(       self	: List[Any]   ,   lowerCAmelCase	: int   ,   lowerCAmelCase	: Dict=13   ,   lowerCAmelCase	: List[Any]=7   ,   lowerCAmelCase	: str=True   ,   lowerCAmelCase	: Any=True   ,   lowerCAmelCase	: List[str]=True   ,   lowerCAmelCase	: Optional[Any]=True   ,   lowerCAmelCase	: Optional[int]=99   ,   lowerCAmelCase	: List[Any]=32   ,   lowerCAmelCase	: Union[str, Any]=5   ,   lowerCAmelCase	: Dict=4   ,   lowerCAmelCase	: int=37   ,   lowerCAmelCase	: Optional[int]="gelu"   ,   lowerCAmelCase	: List[Any]=0.1   ,   lowerCAmelCase	: List[str]=0.1   ,   lowerCAmelCase	: Optional[int]=512   ,   lowerCAmelCase	: Tuple=16   ,   lowerCAmelCase	: List[Any]=2   ,   lowerCAmelCase	: str=0.02   ,   lowerCAmelCase	: int=3   ,   lowerCAmelCase	: Dict=4   ,   lowerCAmelCase	: List[Any]=None   ,   lowerCAmelCase	: Union[str, Any]=1000   ,   )						->			int:
      a__  		=  parent
      a__  		=  batch_size
      a__  		=  seq_length
      a__  		=  is_training
      a__  		=  use_input_mask
      a__  		=  use_token_type_ids
      a__  		=  use_labels
      a__  		=  vocab_size
      a__  		=  hidden_size
      a__  		=  num_hidden_layers
      a__  		=  num_attention_heads
      a__  		=  intermediate_size
      a__  		=  hidden_act
      a__  		=  hidden_dropout_prob
      a__  		=  attention_probs_dropout_prob
      a__  		=  max_position_embeddings
      a__  		=  type_vocab_size
      a__  		=  type_sequence_label_size
      a__  		=  initializer_range
      a__  		=  num_labels
      a__  		=  num_choices
      a__  		=  scope
      a__  		=  range_bbox




    def     __lowerCamelCase			(       self	: Dict )						->			Any:
      a__  		=  ids_tensor([self.batch_size, self.seq_length]   ,   self.vocab_size )

      a__  		=  ids_tensor([self.batch_size, self.seq_length, 4]   ,   self.range_bbox )
      # Ensure that bbox is legal
      for i in range(bbox.shape[0] ):
        for j in range(bbox.shape[1] ):
          if bbox[i, j, 3] < bbox[i, j, 1]:
            a__  		=  bbox[i, j, 3]
            a__  		=  bbox[i, j, 1]
            a__  		=  t
          if bbox[i, j, 2] < bbox[i, j, 0]:
            a__  		=  bbox[i, j, 2]
            a__  		=  bbox[i, j, 0]
            a__  		=  t

      a__  		=  None
      if self.use_input_mask:
        a__  		=  ids_tensor([self.batch_size, self.seq_length]   ,   vocab_size=2 )

      a__  		=  None
      if self.use_token_type_ids:
        a__  		=  ids_tensor([self.batch_size, self.seq_length]   ,   self.type_vocab_size )

      a__  		=  None
      a__  		=  None
      a__  		=  None
      if self.use_labels:
        a__  		=  ids_tensor([self.batch_size]   ,   self.type_sequence_label_size )
        a__  		=  ids_tensor([self.batch_size, self.seq_length]   ,   self.num_labels )
        a__  		=  ids_tensor([self.batch_size]   ,   self.num_choices )

      a__  		=  self.get_config()

      return config, input_ids, bbox, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels




    def     __lowerCamelCase			(       self	: Optional[int] )						->			Dict:
      return LayoutLMConfig(
          vocab_size=self.vocab_size   ,   hidden_size=self.hidden_size   ,   num_hidden_layers=self.num_hidden_layers   ,   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   ,   max_position_embeddings=self.max_position_embeddings   ,   type_vocab_size=self.type_vocab_size   ,   initializer_range=self.initializer_range   ,   )




    def     __lowerCamelCase			(       self	: Tuple   ,   lowerCAmelCase	: Optional[int]   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Tuple   ,   lowerCAmelCase	: Dict   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: Tuple   ,   lowerCAmelCase	: List[str]   ,   lowerCAmelCase	: int )						->			Tuple:
      a__  		=  LayoutLMModel(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase   ,   lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase )
      a__  		=  model(lowerCAmelCase   ,   lowerCAmelCase   ,   token_type_ids=lowerCAmelCase )
      a__  		=  model(lowerCAmelCase   ,   lowerCAmelCase )
      self.parent.assertEqual(result.last_hidden_state.shape   ,   (self.batch_size, self.seq_length, self.hidden_size) )
      self.parent.assertEqual(result.pooler_output.shape   ,   (self.batch_size, self.hidden_size) )




    def     __lowerCamelCase			(       self	: List[Any]   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: int   ,   lowerCAmelCase	: Tuple   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: str   ,   lowerCAmelCase	: str   ,   lowerCAmelCase	: str   ,   lowerCAmelCase	: List[Any] )						->			Tuple:
      a__  		=  LayoutLMForMaskedLM(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase   ,   lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   labels=lowerCAmelCase )
      self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.seq_length, self.vocab_size) )




    def     __lowerCamelCase			(       self	: List[Any]   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: List[str]   ,   lowerCAmelCase	: int   ,   lowerCAmelCase	: Optional[int]   ,   lowerCAmelCase	: Dict   ,   lowerCAmelCase	: Optional[Any] )						->			Union[str, Any]:
      a__  		=  self.num_labels
      a__  		=  LayoutLMForSequenceClassification(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(
          lowerCAmelCase   ,   lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   labels=lowerCAmelCase )
      self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.num_labels) )




    def     __lowerCamelCase			(       self	: List[Any]   ,   lowerCAmelCase	: int   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: str   ,   lowerCAmelCase	: Optional[int]   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: List[str]   ,   lowerCAmelCase	: Any )						->			List[str]:
      a__  		=  self.num_labels
      a__  		=  LayoutLMForTokenClassification(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase   ,   lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   labels=lowerCAmelCase )
      self.parent.assertEqual(result.logits.shape   ,   (self.batch_size, self.seq_length, self.num_labels) )




    def     __lowerCamelCase			(       self	: int   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Union[str, Any]   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: List[Any]   ,   lowerCAmelCase	: List[str]   ,   lowerCAmelCase	: int )						->			Dict:
      a__  		=  LayoutLMForQuestionAnswering(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(
          lowerCAmelCase   ,   bbox=lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   start_positions=lowerCAmelCase   ,   end_positions=lowerCAmelCase   ,   )
      self.parent.assertEqual(result.start_logits.shape   ,   (self.batch_size, self.seq_length) )
      self.parent.assertEqual(result.end_logits.shape   ,   (self.batch_size, self.seq_length) )




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			str:
      a__  		=  self.prepare_config_and_inputs()
      (
          (
          a__
      )		,(
          a__
      )		,(
          a__
      )		,(
          a__
      )		,(
          a__
      )		,(
          a__
      )		,(
          a__
      )		,(
          a__
      )		,
      )  		=  config_and_inputs
      a__  		=  {
          "input_ids": input_ids,
          "bbox": bbox,
          "token_type_ids": token_type_ids,
          "attention_mask": input_mask,
      }
      return config, inputs_dict







@require_torch
class        UpperCAmelCase_					(				_a  ,  _a  ,  unittest.TestCase     ):
    UpperCAmelCase_      :							List[Any]    			=				(
        (
            LayoutLMModel,
            LayoutLMForMaskedLM,
            LayoutLMForSequenceClassification,
            LayoutLMForTokenClassification,
            LayoutLMForQuestionAnswering,
        )
        if is_torch_available()
        else None
    )
    UpperCAmelCase_      :							Tuple    			=				(
        {
            'document-question-answering': LayoutLMForQuestionAnswering,
            'feature-extraction': LayoutLMModel,
            'fill-mask': LayoutLMForMaskedLM,
            'text-classification': LayoutLMForSequenceClassification,
            'token-classification': LayoutLMForTokenClassification,
            'zero-shot': LayoutLMForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    UpperCAmelCase_      :							Tuple    			=				True




    def     __lowerCamelCase			(       self	: List[Any] )						->			Any:
      a__  		=  LayoutLMModelTester(self )
      a__  		=  ConfigTester(self   ,   config_class=lowerCAmelCase   ,   hidden_size=37 )




    def     __lowerCamelCase			(       self	: Any )						->			Union[str, Any]:
      self.config_tester.run_common_tests()




    def     __lowerCamelCase			(       self	: str )						->			List[str]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			Optional[int]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
        a__  		=  type
        self.model_tester.create_and_check_model(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Optional[Any] )						->			Union[str, Any]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_lm(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: List[str] )						->			List[Any]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Tuple )						->			Tuple:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: List[str] )						->			Optional[Any]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*lowerCAmelCase )




    @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
    def     __lowerCamelCase			(       self	: int )						->			str:
      pass

def 					__lowercase						(    )					->Tuple:

  '''simple docstring'''




  a__  		=  torch.tensor([[1_01,10_19,10_14,10_16,10_37,1_28_49,47_47,10_04,1_42_46,22_78,54_39,45_24,50_02,29_30,21_93,29_30,43_41,32_08,10_05,10_55,21_71,28_48,1_13_00,35_31,1_02],[1_01,40_70,40_34,70_20,10_24,30_58,10_15,10_13,28_61,10_13,60_70,1_92_74,27_72,62_05,2_78_14,1_61_47,1_61_47,43_43,20_47,1_02_83,1_09_69,1_43_89,10_12,23_38,1_02]]			,					device=lowerCamelCase__       )  # noqa: E231
  a__  		=  torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],]			,					device=lowerCamelCase__       )  # noqa: E231
  a__  		=  torch.tensor([[[0,0,0,0],[4_23,2_37,4_40,2_51],[4_27,2_72,4_41,2_87],[4_19,1_15,4_37,1_29],[9_61,8_85,9_92,9_12],[2_56,38,3_30,58],[2_56,38,3_30,58],[3_36,42,3_53,57],[3_60,39,4_01,56],[3_60,39,4_01,56],[4_11,39,4_71,59],[4_79,41,5_28,59],[5_33,39,6_30,60],[67,1_13,1_34,1_31],[1_41,1_15,2_09,1_32],[68,1_49,1_33,1_66],[1_41,1_49,1_87,1_64],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[1_95,1_48,2_87,1_65],[2_95,1_48,3_49,1_65],[4_41,1_49,4_92,1_66],[4_97,1_49,5_46,1_64],[64,2_01,1_25,2_18],[10_00,10_00,10_00,10_00]],[[0,0,0,0],[6_62,1_50,7_54,1_66],[6_65,1_99,7_42,2_11],[5_19,2_13,5_54,2_28],[5_19,2_13,5_54,2_28],[1_34,4_33,1_87,4_54],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[1_30,4_67,2_04,4_80],[3_14,4_69,3_76,4_82],[5_04,6_84,5_82,7_06],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[9_41,8_25,9_73,9_00],[6_10,7_49,6_52,7_65],[1_30,6_59,1_68,6_72],[1_76,6_57,2_37,6_72],[2_38,6_57,3_12,6_72],[4_43,6_53,6_28,6_72],[4_43,6_53,6_28,6_72],[7_16,3_01,8_25,3_17],[10_00,10_00,10_00,10_00]]]			,					device=lowerCamelCase__       )  # noqa: E231
  a__  		=  torch.tensor([[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]			,					device=lowerCamelCase__       )  # noqa: E231
  # these are sequence labels (i.e. at the token level)
  a__  		=  torch.tensor([[-1_00,10,10,10,9,1,-1_00,7,7,-1_00,7,7,4,2,5,2,8,8,-1_00,-1_00,5,0,3,2,-1_00],[-1_00,12,12,12,-1_00,12,10,-1_00,-1_00,-1_00,-1_00,10,12,9,-1_00,-1_00,-1_00,10,10,10,9,12,-1_00,10,-1_00]]			,					device=lowerCamelCase__       )  # noqa: E231
  # fmt: on

  return input_ids, attention_mask, bbox, token_type_ids, labels







@require_torch
class        UpperCAmelCase_					(				unittest.TestCase     ):




    @slow
    def     __lowerCamelCase			(       self	: str )						->			Any:
      a__  		=  LayoutLMModel.from_pretrained("microsoft/layoutlm-base-uncased" ).to(lowerCAmelCase )

      a__		,a__		,a__		,a__		,a__  		=  prepare_layoutlm_batch_inputs()

      # forward pass
      a__  		=  model(input_ids=lowerCAmelCase   ,   bbox=lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase )

      # test the sequence output on [0, :3, :3]
      a__  		=  torch.tensor(
          [[0.1_785, -0.1_947, -0.0_425], [-0.3_254, -0.2_807, 0.2_553], [-0.5_391, -0.3_322, 0.3_364]]   ,   device=lowerCAmelCase   ,   )

      self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]   ,   lowerCAmelCase   ,   atol=1e-3 ) )

      # test the pooled output on [1, :3]
      a__  		=  torch.tensor([-0.6_580, -0.0_214, 0.8_552]   ,   device=lowerCAmelCase )

      self.assertTrue(torch.allclose(outputs.pooler_output[1, :3]   ,   lowerCAmelCase   ,   atol=1e-3 ) )




    @slow
    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			Dict:
      # initialize model with randomly initialized sequence classification head
      a__  		=  LayoutLMForSequenceClassification.from_pretrained("microsoft/layoutlm-base-uncased"   ,   num_labels=2 ).to(
          lowerCAmelCase )

      a__		,a__		,a__		,a__		,a__  		=  prepare_layoutlm_batch_inputs()

      # forward pass
      a__  		=  model(
          input_ids=lowerCAmelCase   ,   bbox=lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   labels=torch.tensor([1, 1]   ,   device=lowerCAmelCase )   ,   )

      # test whether we get a loss as a scalar
      a__  		=  outputs.loss
      a__  		=  torch.Size([] )
      self.assertEqual(loss.shape   ,   lowerCAmelCase )

      # test the shape of the logits
      a__  		=  outputs.logits
      a__  		=  torch.Size((2, 2) )
      self.assertEqual(logits.shape   ,   lowerCAmelCase )




    @slow
    def     __lowerCamelCase			(       self	: Any )						->			Optional[int]:
      # initialize model with randomly initialized token classification head
      a__  		=  LayoutLMForTokenClassification.from_pretrained("microsoft/layoutlm-base-uncased"   ,   num_labels=13 ).to(
          lowerCAmelCase )

      a__		,a__		,a__		,a__		,a__  		=  prepare_layoutlm_batch_inputs()

      # forward pass
      a__  		=  model(
          input_ids=lowerCAmelCase   ,   bbox=lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase   ,   labels=lowerCAmelCase )

      # test the loss calculation to be around 2.65
      # expected_loss = torch.tensor(2.65, device=torch_device)

      # The loss is currently somewhat random and can vary between 0.1-0.3 atol.
      # self.assertTrue(torch.allclose(outputs.loss, expected_loss, atol=0.1))

      # test the shape of the logits
      a__  		=  outputs.logits
      a__  		=  torch.Size((2, 25, 13) )
      self.assertEqual(logits.shape   ,   lowerCAmelCase )




    @slow
    def     __lowerCamelCase			(       self	: Optional[int] )						->			Any:
      # initialize model with randomly initialized token classification head
      a__  		=  LayoutLMForQuestionAnswering.from_pretrained("microsoft/layoutlm-base-uncased" ).to(lowerCAmelCase )

      a__		,a__		,a__		,a__		,a__  		=  prepare_layoutlm_batch_inputs()

      # forward pass
      a__  		=  model(input_ids=lowerCAmelCase   ,   bbox=lowerCAmelCase   ,   attention_mask=lowerCAmelCase   ,   token_type_ids=lowerCAmelCase )

      # test the shape of the logits
      a__  		=  torch.Size((2, 25) )
      self.assertEqual(outputs.start_logits.shape   ,   lowerCAmelCase )
      self.assertEqual(outputs.end_logits.shape   ,   lowerCAmelCase )


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




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




    def     __lowerCamelCase			(       self	: List[Any] )						->			str:
      a__  		=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

      a__  		=  self.get_config()

      return config, pixel_values, labels




    def     __lowerCamelCase			(       self	: List[Any] )						->			Union[str, 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=lowerCAmelCase   ,   initializer_range=self.initializer_range   ,   is_hybrid=self.is_hybrid   ,   )




    def     __lowerCamelCase			(       self	: Optional[int]   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Optional[Any]   ,   lowerCAmelCase	: Optional[Any] )						->			Optional[Any]:
      a__  		=  DPTModel(config=lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase )
      self.parent.assertEqual(result.last_hidden_state.shape   ,   (self.batch_size, self.seq_length, self.hidden_size) )




    def     __lowerCamelCase			(       self	: Union[str, Any]   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Dict   ,   lowerCAmelCase	: str )						->			Optional[Any]:
      a__  		=  self.num_labels
      a__  		=  DPTForDepthEstimation(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase )
      self.parent.assertEqual(result.predicted_depth.shape   ,   (self.batch_size, self.image_size, self.image_size) )




    def     __lowerCamelCase			(       self	: str   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Any   ,   lowerCAmelCase	: Optional[int] )						->			List[str]:
      a__  		=  self.num_labels
      a__  		=  DPTForSemanticSegmentation(lowerCAmelCase )
      model.to(lowerCAmelCase )
      model.eval()
      a__  		=  model(lowerCAmelCase   ,   labels=lowerCAmelCase )
      self.parent.assertEqual(
          result.logits.shape   ,   (self.batch_size, self.num_labels, self.image_size, self.image_size) )




    def     __lowerCamelCase			(       self	: int )						->			Any:
      a__  		=  self.prepare_config_and_inputs()
      a__		,a__		,a__  		=  config_and_inputs
      a__  		=  {"pixel_values": pixel_values}
      return config, inputs_dict







@require_torch
class        UpperCAmelCase_					(				_a  ,  _a  ,  unittest.TestCase     ):
    UpperCAmelCase_      :							int    			=				(DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
    UpperCAmelCase_      :							str    			=				(
        {
            'depth-estimation': DPTForDepthEstimation,
            'feature-extraction': DPTModel,
            'image-segmentation': DPTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    UpperCAmelCase_      :							List[str]    			=				False
    UpperCAmelCase_      :							int    			=				False
    UpperCAmelCase_      :							Optional[Any]    			=				False




    def     __lowerCamelCase			(       self	: List[Any] )						->			Any:
      a__  		=  DPTModelTester(self )
      a__  		=  ConfigTester(self   ,   config_class=lowerCAmelCase   ,   has_text_modality=lowerCAmelCase   ,   hidden_size=37 )




    def     __lowerCamelCase			(       self	: int )						->			List[Any]:
      self.config_tester.run_common_tests()




    @unittest.skip(reason="DPT does not use inputs_embeds" )
    def     __lowerCamelCase			(       self	: str )						->			Dict:
      pass




    def     __lowerCamelCase			(       self	: List[str] )						->			int:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

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




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			Any:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

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

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




    def     __lowerCamelCase			(       self	: Optional[int] )						->			Optional[Any]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: Tuple )						->			List[str]:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase )




    def     __lowerCamelCase			(       self	: List[Any] )						->			Any:
      a__  		=  self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase )




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

        a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()
        a__  		=  True

        if model_class in get_values(lowerCAmelCase ):
          continue

        a__  		=  model_class(lowerCAmelCase )
        model.to(lowerCAmelCase )
        model.train()
        a__  		=  self._prepare_for_class(lowerCAmelCase   ,   lowerCAmelCase   ,   return_labels=lowerCAmelCase )
        a__  		=  model(**lowerCAmelCase ).loss
        loss.backward()




    def     __lowerCamelCase			(       self	: Any )						->			Dict:
      for model_class in self.all_model_classes:
        if model_class.__name__ == "DPTForDepthEstimation":
          continue

        a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()
        a__  		=  False
        a__  		=  True

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




    def     __lowerCamelCase			(       self	: List[str] )						->			int:
      a__		,a__  		=  self.model_tester.prepare_config_and_inputs_for_common()

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




    @slow
    def     __lowerCamelCase			(       self	: List[str] )						->			Dict:
      for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a__  		=  DPTModel.from_pretrained(lowerCAmelCase )
        self.assertIsNotNone(lowerCAmelCase )

def 					__lowercase						(    )					->int:

  '''simple docstring'''




  a__  		=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
  return image







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




    def     __lowerCamelCase			(       self	: Any )						->			Union[str, Any]:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large" )
      a__  		=  DPTForDepthEstimation.from_pretrained("Intel/dpt-large" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )
        a__  		=  outputs.predicted_depth

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

      a__  		=  torch.tensor(
          [[6.3_199, 6.3_629, 6.4_148], [6.3_850, 6.3_615, 6.4_166], [6.3_519, 6.3_176, 6.3_575]] ).to(lowerCAmelCase )

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




    def     __lowerCamelCase			(       self	: Union[str, Any] )						->			str:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade" )
      a__  		=  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )

      # verify the logits
      a__  		=  torch.Size((1, 150, 480, 480) )
      self.assertEqual(outputs.logits.shape   ,   lowerCAmelCase )

      a__  		=  torch.tensor(
          [[4.0_480, 4.2_420, 4.4_360], [4.3_124, 4.5_693, 4.8_261], [4.5_768, 4.8_965, 5.2_163]] ).to(lowerCAmelCase )

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




    def     __lowerCamelCase			(       self	: str )						->			Optional[int]:
      a__  		=  DPTImageProcessor.from_pretrained("Intel/dpt-large-ade" )
      a__  		=  DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade" ).to(lowerCAmelCase )

      a__  		=  prepare_img()
      a__  		=  image_processor(images=lowerCAmelCase   ,   return_tensors="pt" ).to(lowerCAmelCase )

      # forward pass
      with torch.no_grad():
        a__  		=  model(**lowerCAmelCase )

      a__  		=  outputs.logits.detach().cpu()

      a__  		=  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase   ,   target_sizes=[(500, 300)] )
      a__  		=  torch.Size((500, 300) )
      self.assertEqual(segmentation[0].shape   ,   lowerCAmelCase )

      a__  		=  image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase )
      a__  		=  torch.Size((480, 480) )
      self.assertEqual(segmentation[0].shape   ,   lowerCAmelCase )

