






import inspect
import unittest

from transformers 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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import MODEL_MAPPING, GLPNConfig, GLPNForDepthEstimation, GLPNModel
			from transformers.models.glpn.modeling_glpn import GLPN_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
			from PIL import Image

			from transformers import GLPNImageProcessor


class 		lowerCAmelCase_							(     lowerCAmelCase__   ):





					def 	lowerCamelCase       (  self     )		->							List[Any]:
								lowerCamelCase											=self.config_class(**self.inputs_dict     )
								self.parent.assertTrue(hasattr(_lowerCamelCase       ,   """hidden_sizes"""     )     )
								self.parent.assertTrue(hasattr(_lowerCamelCase       ,   """num_attention_heads"""     )     )
								self.parent.assertTrue(hasattr(_lowerCamelCase       ,   """num_encoder_blocks"""     )     )




class 		lowerCAmelCase_							:





					def __init__(  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase=13       ,   _UpperCAmelCase=64       ,   _UpperCAmelCase=3       ,   _UpperCAmelCase=4       ,   _UpperCAmelCase=[2, 2, 2, 2]       ,   _UpperCAmelCase=[8, 4, 2, 1]       ,   _UpperCAmelCase=[16, 32, 64, 128]       ,   _UpperCAmelCase=[1, 4, 8, 16]       ,   _UpperCAmelCase=[1, 2, 4, 8]       ,   _UpperCAmelCase=True       ,   _UpperCAmelCase=True       ,   _UpperCAmelCase="gelu"       ,   _UpperCAmelCase=0.1       ,   _UpperCAmelCase=0.1       ,   _UpperCAmelCase=0.02       ,   _UpperCAmelCase=16       ,   _UpperCAmelCase=3       ,   _UpperCAmelCase=None       ,   )		->							str:
								lowerCamelCase											=parent
								lowerCamelCase											=batch_size
								lowerCamelCase											=image_size
								lowerCamelCase											=num_channels
								lowerCamelCase											=num_encoder_blocks
								lowerCamelCase											=sr_ratios
								lowerCamelCase											=depths
								lowerCamelCase											=hidden_sizes
								lowerCamelCase											=downsampling_rates
								lowerCamelCase											=num_attention_heads
								lowerCamelCase											=is_training
								lowerCamelCase											=use_labels
								lowerCamelCase											=hidden_act
								lowerCamelCase											=hidden_dropout_prob
								lowerCamelCase											=attention_probs_dropout_prob
								lowerCamelCase											=initializer_range
								lowerCamelCase											=decoder_hidden_size
								lowerCamelCase											=num_labels
								lowerCamelCase											=scope





					def 	lowerCamelCase       (  self     )		->							str:
								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     )		->							Any:
								return GLPNConfig(
								    image_size=self.image_size       ,   num_channels=self.num_channels       ,   num_encoder_blocks=self.num_encoder_blocks       ,   depths=self.depths       ,   hidden_sizes=self.hidden_sizes       ,   num_attention_heads=self.num_attention_heads       ,   hidden_act=self.hidden_act       ,   hidden_dropout_prob=self.hidden_dropout_prob       ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,   initializer_range=self.initializer_range       ,   decoder_hidden_size=self.decoder_hidden_size       ,   )





					def 	lowerCamelCase       (  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase     )		->							Dict:
								lowerCamelCase											=GLPNModel(config=_lowerCamelCase     )
								model.to(_lowerCamelCase     )
								model.eval()
								lowerCamelCase											=model(_lowerCamelCase     )
								lowerCamelCase											=self.image_size // (self.downsampling_rates[-1] * 2)
								self.parent.assertEqual(
								    result.last_hidden_state.shape       ,   (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)     )





					def 	lowerCamelCase       (  self       ,   _UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase     )		->							Any:
								lowerCamelCase											=self.num_labels
								lowerCamelCase											=GLPNForDepthEstimation(_lowerCamelCase     )
								model.to(_lowerCamelCase     )
								model.eval()
								lowerCamelCase											=model(_lowerCamelCase     )
								self.parent.assertEqual(result.predicted_depth.shape       ,   (self.batch_size, self.image_size, self.image_size)     )
								lowerCamelCase											=model(_lowerCamelCase       ,   labels=_lowerCamelCase     )
								self.parent.assertEqual(result.predicted_depth.shape       ,   (self.batch_size, self.image_size, self.image_size)     )





					def 	lowerCamelCase       (  self     )		->							Any:
								lowerCamelCase											=self.prepare_config_and_inputs()
								lowerCamelCase											=config_and_inputs
								lowerCamelCase											={"""pixel_values""": pixel_values}
								return config, inputs_dict




@require_torch
class 		lowerCAmelCase_							(     lowerCAmelCase__							,    lowerCAmelCase__							,    unittest.TestCase   ):
					__lowerCamelCase					:						List[Any]     =    (GLPNModel, GLPNForDepthEstimation) if is_torch_available() else ()
					__lowerCamelCase					:						Union[str, Any]     =    (
					    {'''depth-estimation''': GLPNForDepthEstimation, '''feature-extraction''': GLPNModel} if is_torch_available() else {}
					)

					__lowerCamelCase					:						List[str]     =    False
					__lowerCamelCase					:						str     =    False
					__lowerCamelCase					:						List[str]     =    False





					def 	lowerCamelCase       (  self     )		->							List[Any]:
								lowerCamelCase											=GLPNModelTester(self     )
								lowerCamelCase											=GLPNConfigTester(self       ,   config_class=_lowerCamelCase     )





					def 	lowerCamelCase       (  self     )		->							Optional[Any]:
								self.config_tester.run_common_tests()





					def 	lowerCamelCase       (  self     )		->							str:
								lowerCamelCase											=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowerCamelCase     )





					def 	lowerCamelCase       (  self     )		->							Dict:
								lowerCamelCase											=self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_depth_estimation(*_lowerCamelCase     )





					@unittest.skip("""GLPN does not use inputs_embeds"""     )
					def 	lowerCamelCase       (  self     )		->							Optional[Any]:
								pass





					@unittest.skip("""GLPN does not have get_input_embeddings method and get_output_embeddings methods"""     )
					def 	lowerCamelCase       (  self     )		->							int:
								pass





					def 	lowerCamelCase       (  self     )		->							str:
								lowerCamelCase											=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase											=model_class(_lowerCamelCase     )
											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]       ,   _lowerCamelCase     )





					def 	lowerCamelCase       (  self     )		->							Optional[int]:
								lowerCamelCase											=self.model_tester.prepare_config_and_inputs_for_common()
								lowerCamelCase											=True

								for model_class in self.all_model_classes:
											lowerCamelCase											=True
											lowerCamelCase											=False
											lowerCamelCase											=True
											lowerCamelCase											=model_class(_lowerCamelCase     )
											model.to(_lowerCamelCase     )
											model.eval()
											with torch.no_grad():
														lowerCamelCase											=model(**self._prepare_for_class(_lowerCamelCase       ,   _lowerCamelCase     )     )
											lowerCamelCase											=outputs.attentions

											lowerCamelCase											=sum(self.model_tester.depths     )
											self.assertEqual(len(_lowerCamelCase     )       ,   _lowerCamelCase     )

											# check that output_attentions also work using config
											del inputs_dict["output_attentions"]
											lowerCamelCase											=True
											lowerCamelCase											=model_class(_lowerCamelCase     )
											model.to(_lowerCamelCase     )
											model.eval()
											with torch.no_grad():
														lowerCamelCase											=model(**self._prepare_for_class(_lowerCamelCase       ,   _lowerCamelCase     )     )
											lowerCamelCase											=outputs.attentions

											self.assertEqual(len(_lowerCamelCase     )       ,   _lowerCamelCase     )

											# verify the first attentions (first block, first layer)
											lowerCamelCase											=(self.model_tester.image_size // 4) ** 2
											lowerCamelCase											=(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
											self.assertListEqual(
											    list(attentions[0].shape[-3:]     )       ,   [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,   )

											# verify the last attentions (last block, last layer)
											lowerCamelCase											=(self.model_tester.image_size // 32) ** 2
											lowerCamelCase											=(self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
											self.assertListEqual(
											    list(attentions[-1].shape[-3:]     )       ,   [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len]       ,   )
											lowerCamelCase											=len(_lowerCamelCase     )

											# Check attention is always last and order is fine
											lowerCamelCase											=True
											lowerCamelCase											=True
											lowerCamelCase											=model_class(_lowerCamelCase     )
											model.to(_lowerCamelCase     )
											model.eval()
											with torch.no_grad():
														lowerCamelCase											=model(**self._prepare_for_class(_lowerCamelCase       ,   _lowerCamelCase     )     )

											self.assertEqual(out_len + 1       ,   len(_lowerCamelCase     )     )

											lowerCamelCase											=outputs.attentions

											self.assertEqual(len(_lowerCamelCase     )       ,   _lowerCamelCase     )
											# verify the first attentions (first block, first layer)
											lowerCamelCase											=(self.model_tester.image_size // 4) ** 2
											lowerCamelCase											=(self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
											self.assertListEqual(
											    list(self_attentions[0].shape[-3:]     )       ,   [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len]       ,   )





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

								def check_hidden_states_output(_UpperCAmelCase       ,   _UpperCAmelCase       ,   _UpperCAmelCase     ):
											lowerCamelCase											=model_class(_lowerCamelCase     )
											model.to(_lowerCamelCase     )
											model.eval()

											with torch.no_grad():
														lowerCamelCase											=model(**self._prepare_for_class(_lowerCamelCase       ,   _lowerCamelCase     )     )

											lowerCamelCase											=outputs.hidden_states

											lowerCamelCase											=self.model_tester.num_encoder_blocks
											self.assertEqual(len(_lowerCamelCase     )       ,   _lowerCamelCase     )

											# verify the first hidden states (first block)
											self.assertListEqual(
											    list(hidden_states[0].shape[-3:]     )       ,   [
											        self.model_tester.hidden_sizes[0],
											        self.model_tester.image_size // 4,
											        self.model_tester.image_size // 4,
											    ]       ,   )

								lowerCamelCase											=self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											lowerCamelCase											=True
											check_hidden_states_output(_lowerCamelCase       ,   _lowerCamelCase       ,   _lowerCamelCase     )

											# check that output_hidden_states also work using config
											del inputs_dict["output_hidden_states"]
											lowerCamelCase											=True

											check_hidden_states_output(_lowerCamelCase       ,   _lowerCamelCase       ,   _lowerCamelCase     )





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

								if not self.model_tester.is_training:
											return

								lowerCamelCase											=self.model_tester.prepare_config_and_inputs_for_common()
								lowerCamelCase											=True

								for model_class in self.all_model_classes:
											if model_class in get_values(_lowerCamelCase     ):
														continue
											# TODO: remove the following 3 lines once we have a MODEL_FOR_DEPTH_ESTIMATION_MAPPING
											# this can then be incorporated into _prepare_for_class in test_modeling_common.py
											if model_class.__name__ == "GLPNForDepthEstimation":
														lowerCamelCase											=inputs_dict["""pixel_values"""].shape
														lowerCamelCase											=torch.zeros(
														    [self.model_tester.batch_size, height, width]       ,   device=_lowerCamelCase     ).long()
											lowerCamelCase											=model_class(_lowerCamelCase     )
											model.to(_lowerCamelCase     )
											model.train()
											lowerCamelCase											=self._prepare_for_class(_lowerCamelCase       ,   _lowerCamelCase       ,   return_labels=_lowerCamelCase     )
											lowerCamelCase											=model(**_lowerCamelCase     ).loss
											loss.backward()





					@slow
					def 	lowerCamelCase       (  self     )		->							int:

								for model_name in GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCamelCase											=GLPNModel.from_pretrained(_lowerCamelCase     )
											self.assertIsNotNone(_lowerCamelCase     )






def    UpperCAmelCase__	(						):
			lowerCamelCase											=Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
			return image







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





					@slow
					def 	lowerCamelCase       (  self     )		->							List[str]:
								lowerCamelCase											=GLPNImageProcessor.from_pretrained(GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )
								lowerCamelCase											=GLPNForDepthEstimation.from_pretrained(GLPN_PRETRAINED_MODEL_ARCHIVE_LIST[0]     ).to(_lowerCamelCase     )

								lowerCamelCase											=prepare_img()
								lowerCamelCase											=image_processor(images=_lowerCamelCase       ,   return_tensors="""pt"""     ).to(_lowerCamelCase     )

								# forward pass
								with torch.no_grad():
											lowerCamelCase											=model(**_lowerCamelCase     )

								# verify the predicted depth
								lowerCamelCase											=torch.Size([1, 480, 640]     )
								self.assertEqual(outputs.predicted_depth.shape       ,   _lowerCamelCase     )

								lowerCamelCase											=torch.tensor(
								    [[3.4291, 2.7865, 2.5151], [3.2841, 2.7021, 2.3502], [3.1147, 2.4625, 2.2481]]     ).to(_lowerCamelCase     )

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







import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()


class 		lowerCAmelCase_							(     unittest.TestCase   ):





     @property
     def 	lowerCamelCase       (  self     )		->							Tuple:
        lowerCamelCase											=1
        lowerCamelCase											=3
        lowerCamelCase											=(32, 32)

        lowerCamelCase											=floats_tensor((batch_size, num_channels) + sizes       ,   rng=random.Random(0     )     ).to(_UpperCAmelCase     )
        return image





     @property
     def 	lowerCamelCase       (  self     )		->							Optional[int]:
        torch.manual_seed(0     )
        lowerCamelCase											=UNetaDModel(
            block_out_channels=(32, 64)       ,   layers_per_block=2       ,   sample_size=32       ,   in_channels=6       ,   out_channels=3       ,   down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")       ,   up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")       ,   )
        return model





     @property
     def 	lowerCamelCase       (  self     )		->							int:
        torch.manual_seed(0     )
        lowerCamelCase											=VQModel(
            block_out_channels=[32, 64]       ,   in_channels=3       ,   out_channels=3       ,   down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]       ,   up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]       ,   latent_channels=3       ,   )
        return model





     def 	lowerCamelCase       (  self     )		->							Any:
        lowerCamelCase											="""cpu"""
        lowerCamelCase											=self.dummy_uncond_unet
        lowerCamelCase											=DDIMScheduler()
        lowerCamelCase											=self.dummy_vq_model

        lowerCamelCase											=LDMSuperResolutionPipeline(unet=_UpperCAmelCase       ,   vqvae=_UpperCAmelCase       ,   scheduler=_UpperCAmelCase     )
        ldm.to(_UpperCAmelCase     )
        ldm.set_progress_bar_config(disable=_UpperCAmelCase     )

        lowerCamelCase											=self.dummy_image.to(_UpperCAmelCase     )

        lowerCamelCase											=torch.Generator(device=_UpperCAmelCase     ).manual_seed(0     )
        lowerCamelCase											=ldm(image=_UpperCAmelCase       ,   generator=_UpperCAmelCase       ,   num_inference_steps=2       ,   output_type="""numpy"""     ).images

        lowerCamelCase											=image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        lowerCamelCase											=np.array([0.8678, 0.8245, 0.6381, 0.6830, 0.4385, 0.5599, 0.4641, 0.6201, 0.5150]     )

        assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2





     @unittest.skipIf(torch_device != """cuda"""       ,   """This test requires a GPU"""     )
     def 	lowerCamelCase       (  self     )		->							int:
        lowerCamelCase											=self.dummy_uncond_unet
        lowerCamelCase											=DDIMScheduler()
        lowerCamelCase											=self.dummy_vq_model

        # put models in fp16
        lowerCamelCase											=unet.half()
        lowerCamelCase											=vqvae.half()

        lowerCamelCase											=LDMSuperResolutionPipeline(unet=_UpperCAmelCase       ,   vqvae=_UpperCAmelCase       ,   scheduler=_UpperCAmelCase     )
        ldm.to(_UpperCAmelCase     )
        ldm.set_progress_bar_config(disable=_UpperCAmelCase     )

        lowerCamelCase											=self.dummy_image.to(_UpperCAmelCase     )

        lowerCamelCase											=ldm(_UpperCAmelCase       ,   num_inference_steps=2       ,   output_type="""numpy"""     ).images

        assert image.shape == (1, 64, 64, 3)




@slow
@require_torch
class 		lowerCAmelCase_							(     unittest.TestCase   ):





     def 	lowerCamelCase       (  self     )		->							Optional[int]:
        lowerCamelCase											=load_image(
            """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
            """/vq_diffusion/teddy_bear_pool.png"""     )
        lowerCamelCase											=init_image.resize((64, 64)       ,   resample=PIL_INTERPOLATION["""lanczos"""]     )

        lowerCamelCase											=LDMSuperResolutionPipeline.from_pretrained("""duongna/ldm-super-resolution"""       ,   device_map="""auto"""     )
        ldm.set_progress_bar_config(disable=_UpperCAmelCase     )

        lowerCamelCase											=torch.manual_seed(0     )
        lowerCamelCase											=ldm(image=_UpperCAmelCase       ,   generator=_UpperCAmelCase       ,   num_inference_steps=20       ,   output_type="""numpy"""     ).images

        lowerCamelCase											=image[0, -3:, -3:, -1]

        assert image.shape == (1, 256, 256, 3)
        lowerCamelCase											=np.array([0.7644, 0.7679, 0.7642, 0.7633, 0.7666, 0.7560, 0.7425, 0.7257, 0.6907]     )

        assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2