

"""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        __lowercase     :

  def __init__(					self						:     Optional[int]   ,A						:     Dict   ,A						:     str=2   ,A						:     str=32   ,A						:     List[str]=16   ,A						:     Optional[Any]=3   ,A						:     Tuple=True   ,A						:     Any=True   ,A						:     str=32   ,A						:     Any=4   ,A						:     Tuple=[0, 1, 2, 3]   ,A						:     List[str]=4   ,A						:     str=37   ,A						:     List[Any]="gelu"   ,A						:     Dict=0.1   ,A						:     str=0.1   ,A						:     str=0.0_2   ,A						:     int=3   ,A						:     Optional[int]=False   ,A						:     List[str]=None   ,):






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

  def 				__lowercase    (					self						:     Dict      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[Any]   				=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

   UpperCAmelCase__   :					Any   				=   self.get_config()

   return config, pixel_values, labels

  def 				__lowercase    (					self						:     Tuple      ):






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

  def 				__lowercase    (					self						:     Optional[Any]   ,A						:     Union[str, Any]   ,A						:     int   ,A						:     int      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[Any]   				=   DPTModel(config=A      )
   model.to(A      )
   model.eval()
   UpperCAmelCase__   :					Tuple   				=   model(A      )
   self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, self.seq_length, self.hidden_size)      )

  def 				__lowercase    (					self						:     Dict   ,A						:     List[Any]   ,A						:     Dict   ,A						:     List[Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					str   				=   self.num_labels
   UpperCAmelCase__   :					List[Any]   				=   DPTForDepthEstimation(A      )
   model.to(A      )
   model.eval()
   UpperCAmelCase__   :					Any   				=   model(A      )
   self.parent.assertEqual(result.predicted_depth.shape   ,(self.batch_size, self.image_size, self.image_size)      )

  def 				__lowercase    (					self						:     Tuple   ,A						:     str   ,A						:     Tuple   ,A						:     Any      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Dict   				=   self.num_labels
   UpperCAmelCase__   :					int   				=   DPTForSemanticSegmentation(A      )
   model.to(A      )
   model.eval()
   UpperCAmelCase__   :					int   				=   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						:     str      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Any   				=   self.prepare_config_and_inputs()
   UpperCAmelCase__   :					int   				=   config_and_inputs
   UpperCAmelCase__   :					Union[str, Any]   				=   {"""pixel_values""": pixel_values}
   return config, inputs_dict







@require_torch
class        __lowercase     (      __lowerCamelCase		,     __lowerCamelCase		,     unittest.TestCase   ):
  snake_case_			    =    (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
  snake_case_			    =    (
      {
          """depth-estimation""": DPTForDepthEstimation,
          """feature-extraction""": DPTModel,
          """image-segmentation""": DPTForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  snake_case_			    =    False
  snake_case_			    =    False
  snake_case_			    =    False

  def 				__lowercase    (					self						:     Optional[int]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Tuple   				=   DPTModelTester(self      )
   UpperCAmelCase__   :					Optional[Any]   				=   ConfigTester(self   ,config_class=A   ,has_text_modality=A   ,hidden_size=37      )

  def 				__lowercase    (					self						:     str      ):






   '''simple docstring'''
   self.config_tester.run_common_tests()

  @unittest.skip(reason="""DPT does not use inputs_embeds"""      )
  def 				__lowercase    (					self						:     List[Any]      ):






   '''simple docstring'''
   pass

  def 				__lowercase    (					self						:     Tuple      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   self.model_tester.prepare_config_and_inputs_for_common()

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

  def 				__lowercase    (					self						:     Dict      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[int]   				=   self.model_tester.prepare_config_and_inputs_for_common()

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

    UpperCAmelCase__   :					List[str]   				=   ["""pixel_values"""]
    self.assertListEqual(arg_names[:1]   ,A      )

  def 				__lowercase    (					self						:     Union[str, Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[int]   				=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*A      )

  def 				__lowercase    (					self						:     List[str]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Any   				=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_depth_estimation(*A      )

  def 				__lowercase    (					self						:     Any      ):






   '''simple docstring'''
   UpperCAmelCase__   :					str   				=   self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*A      )

  def 				__lowercase    (					self						:     Optional[int]      ):






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

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

    if model_class in get_values(A      ):
     continue

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

  def 				__lowercase    (					self						:     int      ):






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

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

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

  def 				__lowercase    (					self						:     Optional[Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Dict   				=   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__   :					int   				=   model_class(config=A      )
    # Skip the check for the backbone
    UpperCAmelCase__   :					str   				=   []
    for name, module in model.named_modules():
     if module.__class__.__name__ == "DPTViTHybridEmbeddings":
      UpperCAmelCase__   :					Optional[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 				__lowercase    (					self						:     Optional[int]      ):






   '''simple docstring'''
   pass




  @slow
  def 				__lowercase    (					self						:     Dict      ):






   '''simple docstring'''
   for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    UpperCAmelCase__   :					Dict   				=   DPTModel.from_pretrained(A      )
    self.assertIsNotNone(A      )







def 					lowerCAmelCase  (   ):
 '''simple docstring'''





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







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

  def 				__lowercase    (					self						:     Optional[Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Dict   				=   DPTImageProcessor.from_pretrained("""Intel/dpt-large"""      )
   UpperCAmelCase__   :					Tuple   				=   DPTForDepthEstimation.from_pretrained("""Intel/dpt-large"""      ).to(A      )

   UpperCAmelCase__   :					Any   				=   prepare_img()
   UpperCAmelCase__   :					Any   				=   image_processor(images=A   ,return_tensors="""pt"""      ).to(A      )

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__   :					Optional[int]   				=   model(**A      )
    UpperCAmelCase__   :					Optional[int]   				=   outputs.predicted_depth

   # verify the predicted depth
   UpperCAmelCase__   :					List[str]   				=   torch.Size((1, 384, 384)      )
   self.assertEqual(predicted_depth.shape   ,A      )

   UpperCAmelCase__   :					Optional[int]   				=   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(A      )

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

  def 				__lowercase    (					self						:     List[str]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""      )
   UpperCAmelCase__   :					Tuple   				=   DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""      ).to(A      )

   UpperCAmelCase__   :					List[str]   				=   prepare_img()
   UpperCAmelCase__   :					Tuple   				=   image_processor(images=A   ,return_tensors="""pt"""      ).to(A      )

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

   # verify the logits
   UpperCAmelCase__   :					Tuple   				=   torch.Size((1, 150, 480, 480)      )
   self.assertEqual(outputs.logits.shape   ,A      )

   UpperCAmelCase__   :					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(A      )

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




  def 				__lowercase    (					self						:     List[Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   DPTImageProcessor.from_pretrained("""Intel/dpt-large-ade"""      )
   UpperCAmelCase__   :					Tuple   				=   DPTForSemanticSegmentation.from_pretrained("""Intel/dpt-large-ade"""      ).to(A      )

   UpperCAmelCase__   :					Any   				=   prepare_img()
   UpperCAmelCase__   :					List[Any]   				=   image_processor(images=A   ,return_tensors="""pt"""      ).to(A      )

   # forward pass
   with torch.no_grad():
    UpperCAmelCase__   :					Any   				=   model(**A      )

   UpperCAmelCase__   :					str   				=   outputs.logits.detach().cpu()

   UpperCAmelCase__   :					int   				=   image_processor.post_process_semantic_segmentation(outputs=A   ,target_sizes=[(500, 300)]      )
   UpperCAmelCase__   :					Any   				=   torch.Size((500, 300)      )
   self.assertEqual(segmentation[0].shape   ,A      )

   UpperCAmelCase__   :					Any   				=   image_processor.post_process_semantic_segmentation(outputs=A      )
   UpperCAmelCase__   :					Tuple   				=   torch.Size((480, 480)      )
   self.assertEqual(segmentation[0].shape   ,A      )








"""simple docstring"""




from math import factorial
def 					lowerCAmelCase  (   __UpperCamelCase							,      __UpperCamelCase ):
 '''simple docstring'''





 return factorial(__UpperCamelCase ) / (factorial(__UpperCamelCase ) * factorial(n - r ))
def 					lowerCAmelCase  (   ):
 '''simple docstring'''





 UpperCAmelCase__   :					Any   				=   0

 for i in range(1							,      101 ):
  for j in range(1							,      i + 1 ):
   if combinations(__UpperCamelCase							,      __UpperCamelCase ) > 1e6:
    total += 1
 return total


if __name__ == "__main__":
      print(solution())





