




"""simple docstring"""






import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class   a__			(       UpperCamelCase_					,	UpperCamelCase_					,	unittest.TestCase  ):
						snake_case__             = StableDiffusionDiffEditPipeline
						snake_case__             = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''height''', '''width''', '''image'''} | {'''image_latents'''}
						snake_case__             = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'''image'''} | {'''image_latents'''}
						snake_case__             = frozenset(
						    []  )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
						snake_case__             = frozenset([]  )





						def       __UpperCamelCase     (							self      :	int)						->       int:




											"""simple docstring"""







											torch.manual_seed(0)
											_lowerCAmelCase:int									=  UNetaDConditionModel(
											    block_out_channels=(32, 64)     ,layers_per_block=2     ,sample_size=32     ,in_channels=4     ,out_channels=4     ,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')     ,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')     ,cross_attention_dim=32     ,attention_head_dim=(2, 4)     ,use_linear_projection=a__     ,)
											_lowerCAmelCase:Tuple									=  DDIMScheduler(
											    beta_start=0.00085     ,beta_end=0.012     ,beta_schedule='''scaled_linear'''     ,clip_sample=a__     ,set_alpha_to_one=a__     ,)
											_lowerCAmelCase:Any									=  DDIMInverseScheduler(
											    beta_start=0.00085     ,beta_end=0.012     ,beta_schedule='''scaled_linear'''     ,clip_sample=a__     ,set_alpha_to_zero=a__     ,)
											torch.manual_seed(0)
											_lowerCAmelCase:Dict									=  AutoencoderKL(
											    block_out_channels=[32, 64]     ,in_channels=3     ,out_channels=3     ,down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,latent_channels=4     ,sample_size=128     ,)
											torch.manual_seed(0)
											_lowerCAmelCase:Optional[int]									=  CLIPTextConfig(
											    bos_token_id=0     ,eos_token_id=2     ,hidden_size=32     ,intermediate_size=37     ,layer_norm_eps=1E-05     ,num_attention_heads=4     ,num_hidden_layers=5     ,pad_token_id=1     ,vocab_size=1000     ,hidden_act='''gelu'''     ,projection_dim=512     ,)
											_lowerCAmelCase:Union[str, Any]									=  CLIPTextModel(a__)
											_lowerCAmelCase:str									=  CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''')

											_lowerCAmelCase:int									=  {
											    '''unet''': unet,
											    '''scheduler''': scheduler,
											    '''inverse_scheduler''': inverse_scheduler,
											    '''vae''': vae,
											    '''text_encoder''': text_encoder,
											    '''tokenizer''': tokenizer,
											    '''safety_checker''': None,
											    '''feature_extractor''': None,
											}

											return components





						def       __UpperCamelCase     (							self      :	Any     ,a__      :	Dict     ,a__      :	int=0)						->       Any:




											"""simple docstring"""







											_lowerCAmelCase:List[Any]									=  floats_tensor((1, 16, 16)     ,rng=random.Random(a__)).to(a__)
											_lowerCAmelCase:List[Any]									=  floats_tensor((1, 2, 4, 16, 16)     ,rng=random.Random(a__)).to(a__)
											if str(a__).startswith('''mps'''):
																_lowerCAmelCase:List[str]									=  torch.manual_seed(a__)
											else:
																_lowerCAmelCase:Optional[Any]									=  torch.Generator(device=a__).manual_seed(a__)
											_lowerCAmelCase:str									=  {
											    '''prompt''': '''a dog and a newt''',
											    '''mask_image''': mask,
											    '''image_latents''': latents,
											    '''generator''': generator,
											    '''num_inference_steps''': 2,
											    '''inpaint_strength''': 1.0,
											    '''guidance_scale''': 6.0,
											    '''output_type''': '''numpy''',
											}

											return inputs





						def       __UpperCamelCase     (							self      :	Dict     ,a__      :	Union[str, Any]     ,a__      :	Any=0)						->       Union[str, Any]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  floats_tensor((1, 3, 32, 32)     ,rng=random.Random(a__)).to(a__)
											_lowerCAmelCase:List[str]									=  image.cpu().permute(0     ,2     ,3     ,1)[0]
											_lowerCAmelCase:Union[str, Any]									=  Image.fromarray(np.uinta(a__)).convert('''RGB''')
											if str(a__).startswith('''mps'''):
																_lowerCAmelCase:List[str]									=  torch.manual_seed(a__)
											else:
																_lowerCAmelCase:Union[str, Any]									=  torch.Generator(device=a__).manual_seed(a__)
											_lowerCAmelCase:Optional[int]									=  {
											    '''image''': image,
											    '''source_prompt''': '''a cat and a frog''',
											    '''target_prompt''': '''a dog and a newt''',
											    '''generator''': generator,
											    '''num_inference_steps''': 2,
											    '''num_maps_per_mask''': 2,
											    '''mask_encode_strength''': 1.0,
											    '''guidance_scale''': 6.0,
											    '''output_type''': '''numpy''',
											}

											return inputs





						def       __UpperCamelCase     (							self      :	List[str]     ,a__      :	Optional[int]     ,a__      :	str=0)						->       List[str]:




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  floats_tensor((1, 3, 32, 32)     ,rng=random.Random(a__)).to(a__)
											_lowerCAmelCase:List[str]									=  image.cpu().permute(0     ,2     ,3     ,1)[0]
											_lowerCAmelCase:int									=  Image.fromarray(np.uinta(a__)).convert('''RGB''')
											if str(a__).startswith('''mps'''):
																_lowerCAmelCase:List[str]									=  torch.manual_seed(a__)
											else:
																_lowerCAmelCase:Optional[Any]									=  torch.Generator(device=a__).manual_seed(a__)
											_lowerCAmelCase:Any									=  {
											    '''image''': image,
											    '''prompt''': '''a cat and a frog''',
											    '''generator''': generator,
											    '''num_inference_steps''': 2,
											    '''inpaint_strength''': 1.0,
											    '''guidance_scale''': 6.0,
											    '''decode_latents''': True,
											    '''output_type''': '''numpy''',
											}
											return inputs





						def       __UpperCamelCase     (							self      :	Tuple)						->       int:




											"""simple docstring"""







											if not hasattr(self.pipeline_class     ,'''_optional_components'''):
																return

											_lowerCAmelCase:Any									=  self.get_dummy_components()
											_lowerCAmelCase:str									=  self.pipeline_class(**a__)
											pipe.to(a__)
											pipe.set_progress_bar_config(disable=a__)

											# set all optional components to None and update pipeline config accordingly
											for optional_component in pipe._optional_components:
																setattr(a__     ,a__     ,a__)
											pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components})

											_lowerCAmelCase:List[str]									=  self.get_dummy_inputs(a__)
											_lowerCAmelCase:Dict									=  pipe(**a__)[0]

											with tempfile.TemporaryDirectory() as tmpdir:
																pipe.save_pretrained(a__)
																_lowerCAmelCase:int									=  self.pipeline_class.from_pretrained(a__)
																pipe_loaded.to(a__)
																pipe_loaded.set_progress_bar_config(disable=a__)

											for optional_component in pipe._optional_components:
																self.assertTrue(
																    getattr(a__     ,a__) is None     ,F'`{optional_component}` did not stay set to None after loading.'     ,)

											_lowerCAmelCase:Optional[Any]									=  self.get_dummy_inputs(a__)
											_lowerCAmelCase:str									=  pipe_loaded(**a__)[0]

											_lowerCAmelCase:Union[str, Any]									=  np.abs(output - output_loaded).max()
											self.assertLess(a__     ,1E-4)





						def       __UpperCamelCase     (							self      :	List[str])						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]									=  '''cpu'''

											_lowerCAmelCase:str									=  self.get_dummy_components()
											_lowerCAmelCase:Any									=  self.pipeline_class(**a__)
											pipe.to(a__)
											pipe.set_progress_bar_config(disable=a__)

											_lowerCAmelCase:str									=  self.get_dummy_mask_inputs(a__)
											_lowerCAmelCase:List[str]									=  pipe.generate_mask(**a__)
											_lowerCAmelCase:Union[str, Any]									=  mask[0, -3:, -3:]

											self.assertEqual(mask.shape     ,(1, 16, 16))
											_lowerCAmelCase:Optional[Any]									=  np.array([0] * 9)
											_lowerCAmelCase:Optional[Any]									=  np.abs(mask_slice.flatten() - expected_slice).max()
											self.assertLessEqual(a__     ,1E-3)
											self.assertEqual(mask[0, -3, -4]     ,0)





						def       __UpperCamelCase     (							self      :	Any)						->       str:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]									=  '''cpu'''

											_lowerCAmelCase:str									=  self.get_dummy_components()
											_lowerCAmelCase:int									=  self.pipeline_class(**a__)
											pipe.to(a__)
											pipe.set_progress_bar_config(disable=a__)

											_lowerCAmelCase:Dict									=  self.get_dummy_inversion_inputs(a__)
											_lowerCAmelCase:Optional[Any]									=  pipe.invert(**a__).images
											_lowerCAmelCase:List[str]									=  image[0, -1, -3:, -3:]

											self.assertEqual(image.shape     ,(2, 32, 32, 3))
											_lowerCAmelCase:Dict									=  np.array(
											    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]     ,)
											_lowerCAmelCase:str									=  np.abs(image_slice.flatten() - expected_slice).max()
											self.assertLessEqual(a__     ,1E-3)





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




											"""simple docstring"""







											super().test_inference_batch_single_identical(expected_max_diff=5E-3)







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




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  '''cpu'''

											_lowerCAmelCase:Union[str, Any]									=  self.get_dummy_components()

											_lowerCAmelCase:List[str]									=  {'''beta_start''': 0.00085, '''beta_end''': 0.012, '''beta_schedule''': '''scaled_linear'''}
											_lowerCAmelCase:Optional[int]									=  DPMSolverMultistepScheduler(**a__)
											_lowerCAmelCase:List[str]									=  DPMSolverMultistepInverseScheduler(**a__)

											_lowerCAmelCase:List[str]									=  self.pipeline_class(**a__)
											pipe.to(a__)
											pipe.set_progress_bar_config(disable=a__)

											_lowerCAmelCase:str									=  self.get_dummy_inversion_inputs(a__)
											_lowerCAmelCase:Tuple									=  pipe.invert(**a__).images
											_lowerCAmelCase:Optional[int]									=  image[0, -1, -3:, -3:]

											self.assertEqual(image.shape     ,(2, 32, 32, 3))
											_lowerCAmelCase:List[Any]									=  np.array(
											    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]     ,)
											_lowerCAmelCase:List[Any]									=  np.abs(image_slice.flatten() - expected_slice).max()
											self.assertLessEqual(a__     ,1E-3)




@require_torch_gpu
@slow
class   a__			(       unittest.TestCase  ):





						def       __UpperCamelCase     (							self      :	int)						->       List[str]:




											"""simple docstring"""







											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()





						@classmethod
						def       __UpperCamelCase     (							cls      :	Tuple)						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png''')

											_lowerCAmelCase:Optional[int]									=  raw_image.convert('''RGB''').resize((768, 768))

											_lowerCAmelCase:Dict									=  raw_image





						def       __UpperCamelCase     (							self      :	Dict)						->       List[Any]:




											"""simple docstring"""







											_lowerCAmelCase:str									=  torch.manual_seed(0)

											_lowerCAmelCase:List[Any]									=  StableDiffusionDiffEditPipeline.from_pretrained(
											    '''stabilityai/stable-diffusion-2-1'''     ,safety_checker=a__     ,torch_dtype=torch.floataa)
											_lowerCAmelCase:Union[str, Any]									=  DDIMScheduler.from_config(pipe.scheduler.config)
											_lowerCAmelCase:Tuple									=  DDIMInverseScheduler.from_config(pipe.scheduler.config)
											pipe.enable_model_cpu_offload()
											pipe.set_progress_bar_config(disable=a__)

											_lowerCAmelCase:Any									=  '''a bowl of fruit'''
											_lowerCAmelCase:List[str]									=  '''a bowl of pears'''

											_lowerCAmelCase:List[str]									=  pipe.generate_mask(
											    image=self.raw_image     ,source_prompt=a__     ,target_prompt=a__     ,generator=a__     ,)

											_lowerCAmelCase:str									=  pipe.invert(
											    prompt=a__     ,image=self.raw_image     ,inpaint_strength=0.7     ,generator=a__).latents

											_lowerCAmelCase:Optional[int]									=  pipe(
											    prompt=a__     ,mask_image=a__     ,image_latents=a__     ,generator=a__     ,negative_prompt=a__     ,inpaint_strength=0.7     ,output_type='''numpy'''     ,).images[0]

											_lowerCAmelCase:List[str]									=  (
											    np.array(
											        load_image(
											            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											            '''/diffedit/pears.png''').resize((768, 768)))
											    / 255
											)
											assert np.abs((expected_image - image).max()) < 5E-1







						def       __UpperCamelCase     (							self      :	Dict)						->       int:




											"""simple docstring"""







											_lowerCAmelCase:int									=  torch.manual_seed(0)

											_lowerCAmelCase:List[str]									=  StableDiffusionDiffEditPipeline.from_pretrained(
											    '''stabilityai/stable-diffusion-2-1'''     ,safety_checker=a__     ,torch_dtype=torch.floataa)
											_lowerCAmelCase:List[Any]									=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
											_lowerCAmelCase:Dict									=  DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config)
											pipe.enable_model_cpu_offload()
											pipe.set_progress_bar_config(disable=a__)

											_lowerCAmelCase:Any									=  '''a bowl of fruit'''
											_lowerCAmelCase:Union[str, Any]									=  '''a bowl of pears'''

											_lowerCAmelCase:Optional[int]									=  pipe.generate_mask(
											    image=self.raw_image     ,source_prompt=a__     ,target_prompt=a__     ,generator=a__     ,)

											_lowerCAmelCase:Dict									=  pipe.invert(
											    prompt=a__     ,image=self.raw_image     ,inpaint_strength=0.7     ,generator=a__     ,num_inference_steps=25     ,).latents

											_lowerCAmelCase:Optional[int]									=  pipe(
											    prompt=a__     ,mask_image=a__     ,image_latents=a__     ,generator=a__     ,negative_prompt=a__     ,inpaint_strength=0.7     ,num_inference_steps=25     ,output_type='''numpy'''     ,).images[0]

											_lowerCAmelCase:Optional[Any]									=  (
											    np.array(
											        load_image(
											            '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											            '''/diffedit/pears.png''').resize((768, 768)))
											    / 255
											)
											assert np.abs((expected_image - image).max()) < 5E-1












"""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      :	List[str]     ,a__      :	List[Any]     ,a__      :	List[str]=2     ,a__      :	Optional[Any]=32     ,a__      :	int=16     ,a__      :	Dict=3     ,a__      :	Optional[int]=True     ,a__      :	int=True     ,a__      :	Optional[Any]=32     ,a__      :	str=4     ,a__      :	Tuple=[0, 1, 2, 3]     ,a__      :	Any=4     ,a__      :	int=37     ,a__      :	int="gelu"     ,a__      :	Optional[int]=0.1     ,a__      :	List[Any]=0.1     ,a__      :	Optional[Any]=0.02     ,a__      :	str=3     ,a__      :	str=[1, 384, 24, 24]     ,a__      :	Optional[Any]=True     ,a__      :	Tuple=None     ,)						->       Optional[Any]:




											"""simple docstring"""







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





						def       __UpperCamelCase     (							self      :	Tuple)						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

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

											return config, pixel_values, labels





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




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]									=  {
											    '''global_padding''': '''same''',
											    '''layer_type''': '''bottleneck''',
											    '''depths''': [3, 4, 9],
											    '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
											    '''embedding_dynamic_padding''': True,
											    '''hidden_sizes''': [96, 192, 384, 768],
											    '''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=a__     ,initializer_range=self.initializer_range     ,is_hybrid=self.is_hybrid     ,backbone_config=a__     ,backbone_featmap_shape=self.backbone_featmap_shape     ,)





						def       __UpperCamelCase     (							self      :	int     ,a__      :	Tuple     ,a__      :	Tuple     ,a__      :	Tuple)						->       Dict:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  DPTModel(config=a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:Optional[Any]									=  model(a__)
											self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, self.seq_length, self.hidden_size))





						def       __UpperCamelCase     (							self      :	str     ,a__      :	Optional[int]     ,a__      :	Union[str, Any]     ,a__      :	int)						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Tuple									=  self.num_labels
											_lowerCAmelCase:List[Any]									=  DPTForDepthEstimation(a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:int									=  model(a__)
											self.parent.assertEqual(result.predicted_depth.shape     ,(self.batch_size, self.image_size, self.image_size))





						def       __UpperCamelCase     (							self      :	Union[str, Any]     ,a__      :	Dict     ,a__      :	List[Any]     ,a__      :	str)						->       Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  self.num_labels
											_lowerCAmelCase:str									=  DPTForSemanticSegmentation(a__)
											model.to(a__)
											model.eval()
											_lowerCAmelCase:int									=  model(a__     ,labels=a__)
											self.parent.assertEqual(
											    result.logits.shape     ,(self.batch_size, self.num_labels, self.image_size, self.image_size))







						def       __UpperCamelCase     (							self      :	Optional[int])						->       List[str]:




											"""simple docstring"""







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




@require_torch
class   a__			(       UpperCamelCase_					,	UpperCamelCase_					,	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       __UpperCamelCase     (							self      :	Optional[Any])						->       List[str]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  DPTModelTester(self)
											_lowerCAmelCase:List[str]									=  ConfigTester(self     ,config_class=a__     ,has_text_modality=a__     ,hidden_size=37)





						def       __UpperCamelCase     (							self      :	str)						->       Optional[int]:




											"""simple docstring"""







											self.config_tester.run_common_tests()





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




											"""simple docstring"""







											pass





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




											"""simple docstring"""







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

											for model_class in self.all_model_classes:
																_lowerCAmelCase:Union[str, Any]									=  model_class(a__)
																self.assertIsInstance(model.get_input_embeddings()     ,(nn.Module))
																_lowerCAmelCase:Optional[int]									=  model.get_output_embeddings()
																self.assertTrue(x is None or isinstance(a__     ,nn.Linear))





						def       __UpperCamelCase     (							self      :	Dict)						->       int:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:Any									=  self.model_tester.prepare_config_and_inputs_for_common()

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

																_lowerCAmelCase:Any									=  ['''pixel_values''']
																self.assertListEqual(arg_names[:1]     ,a__)





						def       __UpperCamelCase     (							self      :	Tuple)						->       int:




											"""simple docstring"""







											_lowerCAmelCase:Optional[Any]									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*a__)





						def       __UpperCamelCase     (							self      :	Dict)						->       int:




											"""simple docstring"""







											_lowerCAmelCase:Dict									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_depth_estimation(*a__)





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




											"""simple docstring"""







											_lowerCAmelCase:Union[str, Any]									=  self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*a__)





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




											"""simple docstring"""







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

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

																if model_class in get_values(a__):
																					continue

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





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




											"""simple docstring"""







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

																_lowerCAmelCase							,   _lowerCAmelCase:Optional[Any]									=  self.model_tester.prepare_config_and_inputs_for_common()
																_lowerCAmelCase:str									=  False
																_lowerCAmelCase:str									=  True

																if model_class in get_values(a__) or not model_class.supports_gradient_checkpointing:
																					continue
																_lowerCAmelCase:Dict									=  model_class(a__)
																model.to(a__)
																model.gradient_checkpointing_enable()
																model.train()
																_lowerCAmelCase:Any									=  self._prepare_for_class(a__     ,a__     ,return_labels=a__)
																_lowerCAmelCase:Tuple									=  model(**a__).loss
																loss.backward()





						def       __UpperCamelCase     (							self      :	Any)						->       int:




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:Optional[Any]									=  self.model_tester.prepare_config_and_inputs_for_common()

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




											"""simple docstring"""







											pass





						@slow
						def       __UpperCamelCase     (							self      :	List[Any])						->       List[str]:




											"""simple docstring"""







											for model_name in DPT_PRETRAINED_MODEL_ARCHIVE_LIST[1:]:
																_lowerCAmelCase:str									=  DPTModel.from_pretrained(a__)
																self.assertIsNotNone(a__)







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




											"""simple docstring"""







											_lowerCAmelCase							,   _lowerCAmelCase:List[str]									=  self.model_tester.prepare_config_and_inputs_for_common()
											_lowerCAmelCase:Any									=  '''add'''
											with self.assertRaises(a__):
																_lowerCAmelCase:Any									=  DPTForDepthEstimation(a__)





def 							UpperCAmelCase		(		):
					_lowerCAmelCase: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])						->       Union[str, Any]:




											"""simple docstring"""







											_lowerCAmelCase:List[str]									=  DPTImageProcessor.from_pretrained('''Intel/dpt-hybrid-midas''')
											_lowerCAmelCase:Optional[int]									=  DPTForDepthEstimation.from_pretrained('''Intel/dpt-hybrid-midas''').to(a__)

											_lowerCAmelCase:Tuple									=  prepare_img()
											_lowerCAmelCase:List[str]									=  image_processor(images=a__     ,return_tensors='''pt''').to(a__)

											# forward pass
											with torch.no_grad():
																_lowerCAmelCase:Dict									=  model(**a__)
																_lowerCAmelCase:List[str]									=  outputs.predicted_depth

											# verify the predicted depth
											_lowerCAmelCase:str									=  torch.Size((1, 384, 384))
											self.assertEqual(predicted_depth.shape     ,a__)

											_lowerCAmelCase:Any									=  torch.tensor(
											    [[[5.6437, 5.6146, 5.6511], [5.4371, 5.5649, 5.5958], [5.5215, 5.5184, 5.5293]]]).to(a__)

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






