





'''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 					__a      :

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







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

							def     UpperCAmelCase__	(							self							:     Any   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

													UpperCAmelCase_			:      Optional[Any]     						=  self.get_config()

													return config, pixel_values, labels

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







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[Any]     						=  {
													    '''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=__magic_name__       ,     initializer_range=self.initializer_range       ,     is_hybrid=self.is_hybrid       ,     backbone_config=__magic_name__       ,     backbone_featmap_shape=self.backbone_featmap_shape       ,     )

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







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  DPTModel(config=__magic_name__   )
													model.to(__magic_name__   )
													model.eval()
													UpperCAmelCase_			:      Tuple     						=  model(__magic_name__   )
													self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)   )

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







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  self.num_labels
													UpperCAmelCase_			:      Optional[int]     						=  DPTForDepthEstimation(__magic_name__   )
													model.to(__magic_name__   )
													model.eval()
													UpperCAmelCase_			:      Optional[Any]     						=  model(__magic_name__   )
													self.parent.assertEqual(result.predicted_depth.shape       ,     (self.batch_size, self.image_size, self.image_size)   )

							def     UpperCAmelCase__	(							self							:     int       ,     __magic_name__							:     str       ,     __magic_name__							:     Dict       ,     __magic_name__							:     int   )					->       List[Any]:







													"""simple docstring"""
													UpperCAmelCase_			:      List[Any]     						=  self.num_labels
													UpperCAmelCase_			:      Optional[Any]     						=  DPTForSemanticSegmentation(__magic_name__   )
													model.to(__magic_name__   )
													model.eval()
													UpperCAmelCase_			:      Tuple     						=  model(__magic_name__       ,     labels=__magic_name__   )
													self.parent.assertEqual(
													    result.logits.shape       ,     (self.batch_size, self.num_labels, self.image_size, self.image_size)   )



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







													"""simple docstring"""
													UpperCAmelCase_			:      Optional[int]     						=  self.prepare_config_and_inputs()
													UpperCAmelCase_						,       UpperCAmelCase_						,       UpperCAmelCase_			:      Dict     						=  config_and_inputs
													UpperCAmelCase_			:      Optional[int]     						=  {'''pixel_values''': pixel_values}
													return config, inputs_dict





@require_torch
class 					__a      (lowerCamelCase       ,		lowerCamelCase       ,		unittest.TestCase     ):
							__a					:   int									=       (DPTModel, DPTForDepthEstimation, DPTForSemanticSegmentation) if is_torch_available() else ()
							__a					:   Tuple									=       (
							    {
							        "depth-estimation": DPTForDepthEstimation,
							        "feature-extraction": DPTModel,
							        "image-segmentation": DPTForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							__a					:   List[str]									=       False
							__a					:   List[str]									=       False
							__a					:   Union[str, Any]									=       False

							def     UpperCAmelCase__	(							self							:     Any   )					->       Any:







													"""simple docstring"""
													UpperCAmelCase_			:      Dict     						=  DPTModelTester(self   )
													UpperCAmelCase_			:      List[str]     						=  ConfigTester(self       ,     config_class=__magic_name__       ,     has_text_modality=__magic_name__       ,     hidden_size=37   )

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







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

							@unittest.skip(reason='''DPT does not use inputs_embeds'''   )
							def     UpperCAmelCase__	(							self							:     Optional[int]   )					->       str:







													"""simple docstring"""
													pass

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







													"""simple docstring"""
													UpperCAmelCase_						,       UpperCAmelCase_			:      List[str]     						=  self.model_tester.prepare_config_and_inputs_for_common()

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

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







													"""simple docstring"""
													UpperCAmelCase_						,       UpperCAmelCase_			:      Tuple     						=  self.model_tester.prepare_config_and_inputs_for_common()

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

																			UpperCAmelCase_			:      Dict     						=  ['''pixel_values''']
																			self.assertListEqual(arg_names[:1]       ,     __magic_name__   )

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







													"""simple docstring"""
													UpperCAmelCase_			:      int     						=  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__magic_name__   )

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







													"""simple docstring"""
													UpperCAmelCase_			:      str     						=  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_depth_estimation(*__magic_name__   )

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







													"""simple docstring"""
													UpperCAmelCase_			:      Union[str, Any]     						=  self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_semantic_segmentation(*__magic_name__   )

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







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

																			UpperCAmelCase_						,       UpperCAmelCase_			:      Any     						=  self.model_tester.prepare_config_and_inputs_for_common()
																			UpperCAmelCase_			:      List[str]     						=  True

																			if model_class in get_values(__magic_name__   ):
																									continue

																			UpperCAmelCase_			:      List[Any]     						=  model_class(__magic_name__   )
																			model.to(__magic_name__   )
																			model.train()
																			UpperCAmelCase_			:      Tuple     						=  self._prepare_for_class(__magic_name__       ,     __magic_name__       ,     return_labels=__magic_name__   )
																			UpperCAmelCase_			:      Dict     						=  model(**__magic_name__   ).loss
																			loss.backward()

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







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

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

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

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







													"""simple docstring"""
													UpperCAmelCase_						,       UpperCAmelCase_			:      int     						=  self.model_tester.prepare_config_and_inputs_for_common()

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







													"""simple docstring"""
													pass

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







													"""simple docstring"""
													for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																			UpperCAmelCase_			:      Tuple     						=  DPTModel.from_pretrained(__magic_name__   )
																			self.assertIsNotNone(__magic_name__   )



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







													"""simple docstring"""
													# We do this test only for DPTForDepthEstimation since it is the only model that uses readout_type
													UpperCAmelCase_						,       UpperCAmelCase_			:      Tuple     						=  self.model_tester.prepare_config_and_inputs_for_common()
													UpperCAmelCase_			:      Optional[int]     						=  '''add'''
													with self.assertRaises(__magic_name__   ):
																			UpperCAmelCase_			:      Union[str, Any]     						=  DPTForDepthEstimation(__magic_name__   )





def        lowerCamelCase_      (  ) ->	Any:
						UpperCAmelCase_			:      Union[str, Any]     						=  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
						return image


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

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







													"""simple docstring"""
													UpperCAmelCase_			:      Dict     						=  DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas'''   )
													UpperCAmelCase_			:      Any     						=  DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas'''   ).to(__magic_name__   )

													UpperCAmelCase_			:      List[Any]     						=  prepare_img()
													UpperCAmelCase_			:      Tuple     						=  image_processor(images=__magic_name__       ,     return_tensors='''pt'''   ).to(__magic_name__   )

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

													# verify the predicted depth
													UpperCAmelCase_			:      Optional[int]     						=  torch.Size((1, 3_84, 3_84)   )
													self.assertEqual(predicted_depth.shape       ,     __magic_name__   )

													UpperCAmelCase_			:      List[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(__magic_name__   )

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












'''simple docstring'''







def        lowerCamelCase_      (  SCREAMING_SNAKE_CASE__      :			int = 10,			SCREAMING_SNAKE_CASE__      :			int = 22   ) ->	int:
						UpperCAmelCase_			:      Optional[int]     						=  range(1,			SCREAMING_SNAKE_CASE__   )
						UpperCAmelCase_			:      List[Any]     						=  range(1,			SCREAMING_SNAKE_CASE__   )
						return sum(
						    1 for power in powers for base in bases if len(str(base**power   )   ) == power   )


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





