





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




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=32		,SCREAMING_SNAKE_CASE__=16		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=32		,SCREAMING_SNAKE_CASE__=4		,SCREAMING_SNAKE_CASE__=[0, 1, 2, 3]		,SCREAMING_SNAKE_CASE__=4		,SCREAMING_SNAKE_CASE__=37		,SCREAMING_SNAKE_CASE__="gelu"		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=0.0_2		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=[1, 3_84, 24, 24]		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=None		,)      ->				Union[str, Any]:





             """simple docstring"""






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




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  self.get_config()

             return config, pixel_values, labels




       def    _UpperCamelCase					(						self							)      ->				Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  {
                 '''global_padding''': '''same''',
                 '''layer_type''': '''bottleneck''',
                 '''depths''': [3, 4, 9],
                 '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
                 '''embedding_dynamic_padding''': True,
                 '''hidden_sizes''': [96, 1_92, 3_84, 7_68],
                 '''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=SCREAMING_SNAKE_CASE__		,initializer_range=self.initializer_range		,is_hybrid=self.is_hybrid		,backbone_config=SCREAMING_SNAKE_CASE__		,backbone_featmap_shape=self.backbone_featmap_shape		,)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[Any]		    =  DPTModel(config=SCREAMING_SNAKE_CASE__							)
             model.to(SCREAMING_SNAKE_CASE__							)
             model.eval()
             __SCREAMING_SNAKE_CASE       :int		    =  model(SCREAMING_SNAKE_CASE__							)
             self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size)							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  self.num_labels
             __SCREAMING_SNAKE_CASE       :Dict		    =  DPTForDepthEstimation(SCREAMING_SNAKE_CASE__							)
             model.to(SCREAMING_SNAKE_CASE__							)
             model.eval()
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  model(SCREAMING_SNAKE_CASE__							)
             self.parent.assertEqual(result.predicted_depth.shape		,(self.batch_size, self.image_size, self.image_size)							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				int:





             """simple docstring"""






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




       def    _UpperCamelCase					(						self							)      ->				Any:





             """simple docstring"""






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






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

       SCREAMING_SNAKE_CASE_       :				Union[str, Any]     						=  False
       SCREAMING_SNAKE_CASE_       :				Tuple     						=  False
       SCREAMING_SNAKE_CASE_       :				Union[str, Any]     						=  False




       def    _UpperCamelCase					(						self							)      ->				str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  DPTModelTester(self							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  ConfigTester(self		,config_class=SCREAMING_SNAKE_CASE__		,has_text_modality=SCREAMING_SNAKE_CASE__		,hidden_size=37							)




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






             self.config_tester.run_common_tests()




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





             """simple docstring"""






             pass




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Tuple		    =  self.model_tester.prepare_config_and_inputs_for_common()

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




       def    _UpperCamelCase					(						self							)      ->				str:





             """simple docstring"""






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

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

                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  ['''pixel_values''']
                   self.assertListEqual(arg_names[:1]		,SCREAMING_SNAKE_CASE__							)




       def    _UpperCamelCase					(						self							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Any		    =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_depth_estimation(*SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__							)




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





             """simple docstring"""






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

                   __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Any		    =  self.model_tester.prepare_config_and_inputs_for_common()
                   __SCREAMING_SNAKE_CASE       :Dict		    =  True

                   if model_class in get_values(SCREAMING_SNAKE_CASE__							):
                         continue

                   __SCREAMING_SNAKE_CASE       :Dict		    =  model_class(SCREAMING_SNAKE_CASE__							)
                   model.to(SCREAMING_SNAKE_CASE__							)
                   model.train()
                   __SCREAMING_SNAKE_CASE       :str		    =  self._prepare_for_class(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,return_labels=SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  model(**SCREAMING_SNAKE_CASE__							).loss
                   loss.backward()




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





             """simple docstring"""






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

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

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




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





             """simple docstring"""






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

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





             """simple docstring"""






             pass




       @slow
       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






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




       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE    ,__SCREAMING_SNAKE_CASE       :Any		    =  self.model_tester.prepare_config_and_inputs_for_common()
             __SCREAMING_SNAKE_CASE       :Tuple		    =  '''add'''
             with self.assertRaises(SCREAMING_SNAKE_CASE__							):
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  DPTForDepthEstimation(SCREAMING_SNAKE_CASE__							)




def 					__lowerCamelCase       (							)      ->				List[str]:
      __SCREAMING_SNAKE_CASE       :Any		    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
      return image







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




       def    _UpperCamelCase					(						self							)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :str		    =  DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas'''							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas'''							).to(SCREAMING_SNAKE_CASE__							)

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

             # forward pass
             with torch.no_grad():
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  model(**SCREAMING_SNAKE_CASE__							)
                   __SCREAMING_SNAKE_CASE       :str		    =  outputs.predicted_depth

             # verify the predicted depth
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  torch.Size((1, 3_84, 3_84)							)
             self.assertEqual(predicted_depth.shape		,SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE       :str		    =  torch.tensor(
                 [[[5.6_4_3_7, 5.6_1_4_6, 5.6_5_1_1], [5.4_3_7_1, 5.5_6_4_9, 5.5_9_5_8], [5.5_2_1_5, 5.5_1_8_4, 5.5_2_9_3]]]							).to(SCREAMING_SNAKE_CASE__							)

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






"""simple docstring"""
from itertools import product



def 					__lowerCamelCase       (							a_					:		int			,       a_					:		int							)      ->				list[int]:
      __SCREAMING_SNAKE_CASE       :Tuple		    =  sides_number
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  max_face_number * dice_number
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  [0] * (max_total + 1)

      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  1
      __SCREAMING_SNAKE_CASE       :Tuple		    =  range(a_			,       max_face_number + 1							)
      for dice_numbers in product(a_			,       repeat=a_							):
            __SCREAMING_SNAKE_CASE       :Any		    =  sum(a_							)
            totals_frequencies[total] += 1

      return totals_frequencies



def 					__lowerCamelCase       (							)      ->				float:
      __SCREAMING_SNAKE_CASE       :Dict		    =  total_frequency_distribution(
          sides_number=4			,       dice_number=9							)
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  total_frequency_distribution(
          sides_number=6			,       dice_number=6							)

      __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  0
      __SCREAMING_SNAKE_CASE       :Any		    =  9
      __SCREAMING_SNAKE_CASE       :List[str]		    =  4 * 9
      __SCREAMING_SNAKE_CASE       :Dict		    =  6
      for peter_total in range(a_			,       max_peter_total + 1							):
            peter_wins_count += peter_totals_frequencies[peter_total] * sum(
                colin_totals_frequencies[min_colin_total:peter_total]							)

      __SCREAMING_SNAKE_CASE       :List[str]		    =  (4**9) * (6**6)
      __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  peter_wins_count / total_games_number

      __SCREAMING_SNAKE_CASE       :str		    =  round(a_			,       ndigits=7							)

      return rounded_peter_win_probability


if __name__ == "__main__":
  print(f'{solution() = }')