






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							:  List[Any],	__A							:  List[str],	__A							:  Any=2,	__A							:  Tuple=3_2,	__A							:  str=1_6,	__A							:  List[str]=3,	__A							:  Dict=True,	__A							:  Optional[int]=True,	__A							:  Optional[Any]=3_2,	__A							:  int=4,	__A							:  Union[str, Any]=[0, 1, 2, 3],	__A							:  Tuple=4,	__A							:  Any=3_7,	__A							:  Union[str, Any]="gelu",	__A							:  str=0.1,	__A							:  Any=0.1,	__A							:  Tuple=0.0_2,	__A							:  Dict=3,	__A							:  Union[str, Any]=False,	__A							:  Union[str, Any]=None,	):
     UpperCAmelCase :							List[str]								=				parent
     UpperCAmelCase :							List[str]								=				batch_size
     UpperCAmelCase :							Tuple								=				image_size
     UpperCAmelCase :							Optional[int]								=				patch_size
     UpperCAmelCase :							Tuple								=				num_channels
     UpperCAmelCase :							List[Any]								=				is_training
     UpperCAmelCase :							Any								=				use_labels
     UpperCAmelCase :							int								=				hidden_size
     UpperCAmelCase :							Tuple								=				num_hidden_layers
     UpperCAmelCase :							Tuple								=				backbone_out_indices
     UpperCAmelCase :							Any								=				num_attention_heads
     UpperCAmelCase :							Union[str, Any]								=				intermediate_size
     UpperCAmelCase :							str								=				hidden_act
     UpperCAmelCase :							Optional[Any]								=				hidden_dropout_prob
     UpperCAmelCase :							Any								=				attention_probs_dropout_prob
     UpperCAmelCase :							Union[str, Any]								=				initializer_range
     UpperCAmelCase :							Optional[Any]								=				num_labels
     UpperCAmelCase :							str								=				scope
     UpperCAmelCase :							Union[str, Any]								=				is_hybrid
     # sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
     UpperCAmelCase :							Dict								=				(image_size // patch_size) ** 2
     UpperCAmelCase :							Dict								=				num_patches + 1



   def  __magic_name__					(							self							:  List[Any]		):
     UpperCAmelCase :							int								=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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

     return config, pixel_values, labels



   def  __magic_name__					(							self							:  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=lowerCAmelCase_,	initializer_range=self.initializer_range,	is_hybrid=self.is_hybrid,	)



   def  __magic_name__					(							self							:  List[str],	__A							:  Optional[int],	__A							:  Tuple,	__A							:  str		):
     UpperCAmelCase :							Union[str, Any]								=				DPTModel(config=lowerCAmelCase_		)
     model.to(lowerCAmelCase_		)
     model.eval()
     UpperCAmelCase :							str								=				model(lowerCAmelCase_		)
     self.parent.assertEqual(result.last_hidden_state.shape,	(self.batch_size, self.seq_length, self.hidden_size)		)



   def  __magic_name__					(							self							:  Tuple,	__A							:  Union[str, Any],	__A							:  Optional[int],	__A							:  Optional[Any]		):
     UpperCAmelCase :							List[Any]								=				self.num_labels
     UpperCAmelCase :							str								=				DPTForDepthEstimation(lowerCAmelCase_		)
     model.to(lowerCAmelCase_		)
     model.eval()
     UpperCAmelCase :							Optional[Any]								=				model(lowerCAmelCase_		)
     self.parent.assertEqual(result.predicted_depth.shape,	(self.batch_size, self.image_size, self.image_size)		)



   def  __magic_name__					(							self							:  Tuple,	__A							:  str,	__A							:  Any,	__A							:  Union[str, Any]		):
     UpperCAmelCase :							Union[str, Any]								=				self.num_labels
     UpperCAmelCase :							int								=				DPTForSemanticSegmentation(lowerCAmelCase_		)
     model.to(lowerCAmelCase_		)
     model.eval()
     UpperCAmelCase :							int								=				model(lowerCAmelCase_,	labels=lowerCAmelCase_		)
     self.parent.assertEqual(
         result.logits.shape,	(self.batch_size, self.num_labels, self.image_size, self.image_size)		)





   def  __magic_name__					(							self							:  int		):
     UpperCAmelCase :							Tuple								=				self.prepare_config_and_inputs()
     UpperCAmelCase				,		UpperCAmelCase				,		UpperCAmelCase :							Any								=				config_and_inputs
     UpperCAmelCase :							str								=				{'''pixel_values''': pixel_values}
     return config, inputs_dict






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

   UpperCamelCase       =  False
   UpperCamelCase       =  False
   UpperCamelCase       =  False



   def  __magic_name__					(							self							:  str		):
     UpperCAmelCase :							Any								=				DPTModelTester(self		)
     UpperCAmelCase :							Tuple								=				ConfigTester(self,	config_class=lowerCAmelCase_,	has_text_modality=lowerCAmelCase_,	hidden_size=3_7		)



   def  __magic_name__					(							self							:  int		):
     self.config_tester.run_common_tests()



   @unittest.skip(reason='''DPT does not use inputs_embeds'''		)
   def  __magic_name__					(							self							:  Dict		):
     pass



   def  __magic_name__					(							self							:  str		):
     UpperCAmelCase				,		UpperCAmelCase :							Optional[int]								=				self.model_tester.prepare_config_and_inputs_for_common()

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



   def  __magic_name__					(							self							:  Union[str, Any]		):
     UpperCAmelCase				,		UpperCAmelCase :							Tuple								=				self.model_tester.prepare_config_and_inputs_for_common()

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

       UpperCAmelCase :							Tuple								=				['''pixel_values''']
       self.assertListEqual(arg_names[:1],	lowerCAmelCase_		)



   def  __magic_name__					(							self							:  Dict		):
     UpperCAmelCase :							Union[str, Any]								=				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_		)



   def  __magic_name__					(							self							:  Optional[int]		):
     UpperCAmelCase :							Any								=				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_depth_estimation(*lowerCAmelCase_		)



   def  __magic_name__					(							self							:  Any		):
     UpperCAmelCase :							int								=				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*lowerCAmelCase_		)



   def  __magic_name__					(							self							:  Optional[int]		):






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

       UpperCAmelCase				,		UpperCAmelCase :							int								=				self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase :							Optional[Any]								=				True

       if model_class in get_values(lowerCAmelCase_		):
         continue

       UpperCAmelCase :							int								=				model_class(lowerCAmelCase_		)
       model.to(lowerCAmelCase_		)
       model.train()
       UpperCAmelCase :							int								=				self._prepare_for_class(lowerCAmelCase_,	lowerCAmelCase_,	return_labels=lowerCAmelCase_		)
       UpperCAmelCase :							Dict								=				model(**lowerCAmelCase_		).loss
       loss.backward()



   def  __magic_name__					(							self							:  str		):






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

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

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



   def  __magic_name__					(							self							:  Dict		):
     UpperCAmelCase				,		UpperCAmelCase :							int								=				self.model_tester.prepare_config_and_inputs_for_common()

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





   @slow
   def  __magic_name__					(							self							:  Union[str, Any]		):






     for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase :							Union[str, Any]								=				DPTModel.from_pretrained(lowerCAmelCase_		)
       self.assertIsNotNone(lowerCAmelCase_		)






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






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



   def  __magic_name__					(							self							:  Union[str, Any]		):
     UpperCAmelCase :							Union[str, Any]								=				DPTImageProcessor.from_pretrained('''Intel/dpt-large'''		)
     UpperCAmelCase :							Union[str, Any]								=				DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''		).to(lowerCAmelCase_		)

     UpperCAmelCase :							List[Any]								=				prepare_img()
     UpperCAmelCase :							List[str]								=				image_processor(images=lowerCAmelCase_,	return_tensors='''pt'''		).to(lowerCAmelCase_		)

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

     # verify the predicted depth
     UpperCAmelCase :							Dict								=				torch.Size((1, 3_8_4, 3_8_4)		)
     self.assertEqual(predicted_depth.shape,	lowerCAmelCase_		)

     UpperCAmelCase :							List[Any]								=				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(lowerCAmelCase_		)

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



   def  __magic_name__					(							self							:  List[str]		):
     UpperCAmelCase :							List[str]								=				DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''		)
     UpperCAmelCase :							Dict								=				DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''		).to(lowerCAmelCase_		)

     UpperCAmelCase :							List[Any]								=				prepare_img()
     UpperCAmelCase :							Dict								=				image_processor(images=lowerCAmelCase_,	return_tensors='''pt'''		).to(lowerCAmelCase_		)

     # forward pass
     with torch.no_grad():
       UpperCAmelCase :							Any								=				model(**lowerCAmelCase_		)

     # verify the logits
     UpperCAmelCase :							Union[str, Any]								=				torch.Size((1, 1_5_0, 4_8_0, 4_8_0)		)
     self.assertEqual(outputs.logits.shape,	lowerCAmelCase_		)

     UpperCAmelCase :							Optional[Any]								=				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(lowerCAmelCase_		)

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





   def  __magic_name__					(							self							:  List[str]		):
     UpperCAmelCase :							int								=				DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''		)
     UpperCAmelCase :							Any								=				DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''		).to(lowerCAmelCase_		)

     UpperCAmelCase :							Optional[int]								=				prepare_img()
     UpperCAmelCase :							Union[str, Any]								=				image_processor(images=lowerCAmelCase_,	return_tensors='''pt'''		).to(lowerCAmelCase_		)

     # forward pass
     with torch.no_grad():
       UpperCAmelCase :							Union[str, Any]								=				model(**lowerCAmelCase_		)

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

     UpperCAmelCase :							Any								=				image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase_,	target_sizes=[(5_0_0, 3_0_0)]		)
     UpperCAmelCase :							Any								=				torch.Size((5_0_0, 3_0_0)		)
     self.assertEqual(segmentation[0].shape,	lowerCAmelCase_		)

     UpperCAmelCase :							Any								=				image_processor.post_process_semantic_segmentation(outputs=lowerCAmelCase_		)
     UpperCAmelCase :							int								=				torch.Size((4_8_0, 4_8_0)		)
     self.assertEqual(segmentation[0].shape,	lowerCAmelCase_		)








from functools import lru_cache

@lru_cache
def     a__  (	UpperCAmelCase							:    int    )						->		int:
  if not isinstance(UpperCAmelCase       ,				UpperCAmelCase    ):
    raise TypeError('''k must be an integer.'''    )
  if k < 0:
    raise ValueError('''k integer must be greater or equal to zero.'''    )
  if k == 0:
    return 0
  elif k == 1:
    return 1
  else:
    return fibonacci(k - 1    ) + fibonacci(k - 2    )

def     a__  (	UpperCAmelCase							:    list       ,				UpperCAmelCase							:    int    )						->		int:
  UpperCAmelCase :							List[str]								=				len(UpperCAmelCase    )
  # Find m such that F_m >= n where F_i is the i_th fibonacci number.
  UpperCAmelCase :							Any								=				0
  while True:
    if fibonacci(UpperCAmelCase    ) >= len_list:
      UpperCAmelCase :							Optional[Any]								=				i
      break
    i += 1
  UpperCAmelCase :							List[Any]								=				0
  while fibb_k > 0:
    UpperCAmelCase :							List[str]								=				min(
        offset + fibonacci(fibb_k - 1    )       ,				len_list - 1    )  # Prevent out of range
    UpperCAmelCase :							Optional[Any]								=				arr[index_k]
    if item_k_1 == val:
      return index_k
    elif val < item_k_1:
      fibb_k -= 1
    elif val > item_k_1:
      offset += fibonacci(fibb_k - 1    )
      fibb_k -= 2
  else:
    return -1


if __name__ == "__main__":
     import doctest

     doctest.testmod()





