



"""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			,  UpperCAmelCase			,  UpperCAmelCase=2			,  UpperCAmelCase=32			,  UpperCAmelCase=16			,  UpperCAmelCase=3			,  UpperCAmelCase=True			,  UpperCAmelCase=True			,  UpperCAmelCase=32			,  UpperCAmelCase=4			,  UpperCAmelCase=[0, 1, 2, 3]			,  UpperCAmelCase=4			,  UpperCAmelCase=37			,  UpperCAmelCase="gelu"			,  UpperCAmelCase=0.1			,  UpperCAmelCase=0.1			,  UpperCAmelCase=0.0_2			,  UpperCAmelCase=3			,  UpperCAmelCase=False			,  UpperCAmelCase=None			,  ):

					'''simple docstring'''






					lowerCAmelCase_			       = parent
					lowerCAmelCase_			       = batch_size
					lowerCAmelCase_			       = image_size
					lowerCAmelCase_			       = patch_size
					lowerCAmelCase_			       = num_channels
					lowerCAmelCase_			       = is_training
					lowerCAmelCase_			       = use_labels
					lowerCAmelCase_			       = hidden_size
					lowerCAmelCase_			       = num_hidden_layers
					lowerCAmelCase_			       = backbone_out_indices
					lowerCAmelCase_			       = num_attention_heads
					lowerCAmelCase_			       = intermediate_size
					lowerCAmelCase_			       = hidden_act
					lowerCAmelCase_			       = hidden_dropout_prob
					lowerCAmelCase_			       = attention_probs_dropout_prob
					lowerCAmelCase_			       = initializer_range
					lowerCAmelCase_			       = num_labels
					lowerCAmelCase_			       = scope
					lowerCAmelCase_			       = is_hybrid
					# sequence length of DPT = num_patches + 1 (we add 1 for the [CLS] token)
					lowerCAmelCase_			       = (image_size // patch_size) ** 2
					lowerCAmelCase_			       = num_patches + 1







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

					lowerCAmelCase_			       = self.get_config()

					return config, pixel_values, labels







				def     lowerCamelCase_    (   self      ):

					'''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     lowerCamelCase_    (   self			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = DPTModel(config=a_      )
					model.to(a_      )
					model.eval()
					lowerCAmelCase_			       = model(a_      )
					self.parent.assertEqual(result.last_hidden_state.shape			,  (self.batch_size, self.seq_length, self.hidden_size)      )







				def     lowerCamelCase_    (   self			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.num_labels
					lowerCAmelCase_			       = DPTForDepthEstimation(a_      )
					model.to(a_      )
					model.eval()
					lowerCAmelCase_			       = model(a_      )
					self.parent.assertEqual(result.predicted_depth.shape			,  (self.batch_size, self.image_size, self.image_size)      )







				def     lowerCamelCase_    (   self			,  UpperCAmelCase			,  UpperCAmelCase			,  UpperCAmelCase      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.num_labels
					lowerCAmelCase_			       = DPTForSemanticSegmentation(a_      )
					model.to(a_      )
					model.eval()
					lowerCAmelCase_			       = model(a_			,  labels=a_      )
					self.parent.assertEqual(
					    result.logits.shape			,  (self.batch_size, self.num_labels, self.image_size, self.image_size)      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.prepare_config_and_inputs()
					lowerCAmelCase_       ,  lowerCAmelCase_       ,  lowerCAmelCase_			       = config_and_inputs
					lowerCAmelCase_			       = {'''pixel_values''': pixel_values}
					return config, inputs_dict







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

				lowerCamelCase    :					Tuple 					=False
				lowerCamelCase    :					Any 					=False
				lowerCamelCase    :					Tuple 					=False







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = DPTModelTester(self      )
					lowerCAmelCase_			       = ConfigTester(self			,  config_class=a_			,  has_text_modality=a_			,  hidden_size=37      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					self.config_tester.run_common_tests()







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

					'''simple docstring'''






					pass







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_       ,  lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs_for_common()

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







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_       ,  lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs_for_common()

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

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







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*a_      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_depth_estimation(*a_      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*a_      )







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






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

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

						if model_class in get_values(a_      ):
							continue

						lowerCAmelCase_			       = model_class(a_      )
						model.to(a_      )
						model.train()
						lowerCAmelCase_			       = self._prepare_for_class(a_			,  a_			,  return_labels=a_      )
						lowerCAmelCase_			       = model(**a_      ).loss
						loss.backward()







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






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

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

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







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_       ,  lowerCAmelCase_			       = self.model_tester.prepare_config_and_inputs_for_common()

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

					'''simple docstring'''






					pass







				@slow
				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowerCAmelCase_			       = DPTModel.from_pretrained(a_      )
						self.assertIsNotNone(a_      )




def     UpperCAmelCase    (					)	->   Tuple:


	"""simple docstring"""




	lowerCAmelCase_			       = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
	return image







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







				def     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = DPTImageProcessor.from_pretrained('''Intel/dpt-large'''      )
					lowerCAmelCase_			       = DPTForDepthEstimation.from_pretrained('''Intel/dpt-large'''      ).to(a_      )

					lowerCAmelCase_			       = prepare_img()
					lowerCAmelCase_			       = image_processor(images=a_			,  return_tensors='''pt'''      ).to(a_      )

					# forward pass
					with torch.no_grad():
						lowerCAmelCase_			       = model(**a_      )
						lowerCAmelCase_			       = outputs.predicted_depth

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

					lowerCAmelCase_			       = 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     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
					lowerCAmelCase_			       = DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(a_      )

					lowerCAmelCase_			       = prepare_img()
					lowerCAmelCase_			       = image_processor(images=a_			,  return_tensors='''pt'''      ).to(a_      )

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

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

					lowerCAmelCase_			       = 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     lowerCamelCase_    (   self      ):

					'''simple docstring'''






					lowerCAmelCase_			       = DPTImageProcessor.from_pretrained('''Intel/dpt-large-ade'''      )
					lowerCAmelCase_			       = DPTForSemanticSegmentation.from_pretrained('''Intel/dpt-large-ade'''      ).to(a_      )

					lowerCAmelCase_			       = prepare_img()
					lowerCAmelCase_			       = image_processor(images=a_			,  return_tensors='''pt'''      ).to(a_      )

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

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

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

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



"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_sentencepiece_available,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


lowercase_							 =       {'configuration_pegasus': ['PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP', 'PegasusConfig']}

try:
		if not is_sentencepiece_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_							 =       ['PegasusTokenizer']

try:
		if not is_tokenizers_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_							 =       ['PegasusTokenizerFast']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_							 =       [
		    'PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST',
		    'PegasusForCausalLM',
		    'PegasusForConditionalGeneration',
		    'PegasusModel',
		    'PegasusPreTrainedModel',
		]

try:
		if not is_tf_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_							 =       [
		    'TFPegasusForConditionalGeneration',
		    'TFPegasusModel',
		    'TFPegasusPreTrainedModel',
		]

try:
		if not is_flax_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_							 =       [
		    'FlaxPegasusForConditionalGeneration',
		    'FlaxPegasusModel',
		    'FlaxPegasusPreTrainedModel',
		]


if TYPE_CHECKING:
		from .configuration_pegasus import PEGASUS_PRETRAINED_CONFIG_ARCHIVE_MAP, PegasusConfig

		try:
				if not is_sentencepiece_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_pegasus import PegasusTokenizer

		try:
				if not is_tokenizers_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .tokenization_pegasus_fast import PegasusTokenizerFast

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_pegasus import (
				    PEGASUS_PRETRAINED_MODEL_ARCHIVE_LIST,
				    PegasusForCausalLM,
				    PegasusForConditionalGeneration,
				    PegasusModel,
				    PegasusPreTrainedModel,
				)

		try:
				if not is_tf_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_tf_pegasus import TFPegasusForConditionalGeneration, TFPegasusModel, TFPegasusPreTrainedModel

		try:
				if not is_flax_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_flax_pegasus import (
				    FlaxPegasusForConditionalGeneration,
				    FlaxPegasusModel,
				    FlaxPegasusPreTrainedModel,
				)

else:
		import sys

		lowercase_							 =       _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)