


import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
							import torch

							from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

							if is_vision_available():
														from transformers import MaskaFormerImageProcessor

if is_vision_available():
							from PIL import Image







class        UpperCamelCase__   :

					def __init__(     self       :   Any							,					UpperCamelCase__       :   List[Any]							,					UpperCamelCase__       :   Any=2							,					UpperCamelCase__       :   Union[str, Any]=True							,					UpperCamelCase__       :   List[Any]=False							,					UpperCamelCase__       :   Any=10							,					UpperCamelCase__       :   List[Any]=3							,					UpperCamelCase__       :   int=32 * 8							,					UpperCamelCase__       :   Union[str, Any]=32 * 8							,					UpperCamelCase__       :   int=4							,					UpperCamelCase__       :   Any=64							,					):






										'''simple docstring'''






										lowercase_  							=			parent
										lowercase_  							=			batch_size
										lowercase_  							=			is_training
										lowercase_  							=			use_auxiliary_loss
										lowercase_  							=			num_queries
										lowercase_  							=			num_channels
										lowercase_  							=			min_size
										lowercase_  							=			max_size
										lowercase_  							=			num_labels
										lowercase_  							=			hidden_dim
										lowercase_  							=			hidden_dim

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]       ).to(
										    UpperCAmelCase__       )

										lowercase_  							=			torch.ones([self.batch_size, self.min_size, self.max_size]							,					device=UpperCAmelCase__       )

										lowercase_  							=			(
										    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]							,					device=UpperCAmelCase__       ) > 0.5
										).float()
										lowercase_  							=			(torch.rand((self.batch_size, self.num_labels)							,					device=UpperCAmelCase__       ) > 0.5).long()

										lowercase_  							=			self.get_config()
										return config, pixel_values, pixel_mask, mask_labels, class_labels

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			MaskaFormerConfig(
										    hidden_size=self.hidden_dim							,					)
										lowercase_  							=			self.num_queries
										lowercase_  							=			self.num_labels

										lowercase_  							=			[1, 1, 1, 1]
										lowercase_  							=			self.num_channels

										lowercase_  							=			64
										lowercase_  							=			128
										lowercase_  							=			self.hidden_dim
										lowercase_  							=			self.hidden_dim
										lowercase_  							=			self.hidden_dim
										return config

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			self.prepare_config_and_inputs()
										lowercase_  							=			{'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
										return config, inputs_dict

					def   UpperCAmelCase__       (     self       :   Dict							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			output.encoder_hidden_states
										lowercase_  							=			output.pixel_decoder_hidden_states
										lowercase_  							=			output.transformer_decoder_hidden_states

										self.parent.assertTrue(len(UpperCAmelCase__       )							,					len(config.backbone_config.depths       )       )
										self.parent.assertTrue(len(UpperCAmelCase__       )							,					len(config.backbone_config.depths       )       )
										self.parent.assertTrue(len(UpperCAmelCase__       )							,					config.decoder_layers       )

					def   UpperCAmelCase__       (     self       :   Optional[int]							,					UpperCamelCase__       :   Dict							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   int=False       ):






										'''simple docstring'''






										with torch.no_grad():
															lowercase_  							=			MaskaFormerModel(config=UpperCAmelCase__       )
															model.to(UpperCAmelCase__       )
															model.eval()

															lowercase_  							=			model(pixel_values=UpperCAmelCase__							,					pixel_mask=UpperCAmelCase__       )
															lowercase_  							=			model(UpperCAmelCase__							,					output_hidden_states=UpperCAmelCase__       )

										self.parent.assertEqual(
										    output.transformer_decoder_last_hidden_state.shape							,					(self.batch_size, self.num_queries, self.hidden_dim)							,					)
										# let's ensure the other two hidden state exists
										self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None       )
										self.parent.assertTrue(output.encoder_last_hidden_state is not None       )

										if output_hidden_states:
															self.check_output_hidden_state(UpperCAmelCase__							,					UpperCAmelCase__       )







					def   UpperCAmelCase__       (     self       :   List[Any]							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   Optional[int]							,					UpperCamelCase__       :   Dict							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			MaskaFormerForUniversalSegmentation(config=UpperCAmelCase__       )
										model.to(UpperCAmelCase__       )
										model.eval()

										def comm_check_on_output(UpperCamelCase__       :   Union[str, Any]       ):
															# let's still check that all the required stuff is there
															self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None       )
															self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None       )
															self.parent.assertTrue(result.encoder_last_hidden_state is not None       )
															# okay, now we need to check the logits shape
															# due to the encoder compression, masks have a //4 spatial size
															self.parent.assertEqual(
															    result.masks_queries_logits.shape							,					(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)							,					)
															# + 1 for null class
															self.parent.assertEqual(
															    result.class_queries_logits.shape							,					(self.batch_size, self.num_queries, self.num_labels + 1)       )

										with torch.no_grad():
															lowercase_  							=			model(pixel_values=UpperCAmelCase__							,					pixel_mask=UpperCAmelCase__       )
															lowercase_  							=			model(UpperCAmelCase__       )

															comm_check_on_output(UpperCAmelCase__       )

															lowercase_  							=			model(
															    pixel_values=UpperCAmelCase__							,					pixel_mask=UpperCAmelCase__							,					mask_labels=UpperCAmelCase__							,					class_labels=UpperCAmelCase__       )

										comm_check_on_output(UpperCAmelCase__       )

										self.parent.assertTrue(result.loss is not None       )
										self.parent.assertEqual(result.loss.shape							,					torch.Size([1]       )       )







@require_torch
class        UpperCamelCase__   (	lowercase__							,				lowercase__							,				unittest.TestCase   ):
					__SCREAMING_SNAKE_CASE       :  Optional[int]						=   (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
					__SCREAMING_SNAKE_CASE       :  Any						=   {'feature-extraction': MaskaFormerModel} if is_torch_available() else {}

					__SCREAMING_SNAKE_CASE       :  Optional[int]						=   False
					__SCREAMING_SNAKE_CASE       :  List[str]						=   False
					__SCREAMING_SNAKE_CASE       :  Optional[int]						=   False
					__SCREAMING_SNAKE_CASE       :  List[Any]						=   False

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






										'''simple docstring'''






										lowercase_  							=			MaskaFormerModelTester(self       )
										lowercase_  							=			ConfigTester(self							,					config_class=UpperCAmelCase__							,					has_text_modality=UpperCAmelCase__       )

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






										self.config_tester.run_common_tests()

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskaformer_model(UpperCAmelCase__							,					**UpperCAmelCase__							,					output_hidden_states=UpperCAmelCase__       )

					def   UpperCAmelCase__       (     self       :   List[Any]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*UpperCAmelCase__       )

					@unittest.skip(reason="""Mask2Former does not use inputs_embeds"""       )
					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										pass

					@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""       )
					def   UpperCAmelCase__       (     self       :   List[Any]       ):






										'''simple docstring'''






										pass

					@unittest.skip(reason="""Mask2Former is not a generative model"""       )
					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										pass

					@unittest.skip(reason="""Mask2Former does not use token embeddings"""       )
					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										pass

					@require_torch_multi_gpu
					@unittest.skip(
					    reason="""Mask2Former has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`"""       )
					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										pass

					@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""       )
					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										pass

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

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

															lowercase_  							=			['''pixel_values''']
															self.assertListEqual(arg_names[:1]							,					UpperCAmelCase__       )

					@slow
					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
															lowercase_  							=			MaskaFormerModel.from_pretrained(UpperCAmelCase__       )
															self.assertIsNotNone(UpperCAmelCase__       )

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										lowercase_  							=			(self.model_tester.min_size,) * 2
										lowercase_  							=			{
										    '''pixel_values''': torch.randn((2, 3, *size)							,					device=UpperCAmelCase__       ),
										    '''mask_labels''': torch.randn((2, 10, *size)							,					device=UpperCAmelCase__       ),
										    '''class_labels''': torch.zeros(2							,					10							,					device=UpperCAmelCase__       ).long(),
										}
										lowercase_  							=			self.model_tester.get_config()

										lowercase_  							=			MaskaFormerForUniversalSegmentation(UpperCAmelCase__       ).to(UpperCAmelCase__       )
										lowercase_  							=			model(**UpperCAmelCase__       )
										self.assertTrue(outputs.loss is not None       )

					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()
										self.model_tester.create_and_check_maskaformer_model(UpperCAmelCase__							,					**UpperCAmelCase__							,					output_hidden_states=UpperCAmelCase__       )

					def   UpperCAmelCase__       (     self       :   List[str]       ):






										'''simple docstring'''






										lowercase_  							=			self.model_tester.prepare_config_and_inputs_for_common()

										for model_class in self.all_model_classes:
															lowercase_  							=			model_class(UpperCAmelCase__       ).to(UpperCAmelCase__       )
															lowercase_  							=			model(**UpperCAmelCase__							,					output_attentions=UpperCAmelCase__       )
															self.assertTrue(outputs.attentions is not None       )

					def   UpperCAmelCase__       (     self       :   int       ):






										'''simple docstring'''






										if not self.model_tester.is_training:
															return

										lowercase_  							=			self.all_model_classes[1]
										lowercase_  							=			self.model_tester.prepare_config_and_inputs()

										lowercase_  							=			model_class(UpperCAmelCase__       )
										model.to(UpperCAmelCase__       )
										model.train()

										lowercase_  							=			model(UpperCAmelCase__							,					mask_labels=UpperCAmelCase__							,					class_labels=UpperCAmelCase__       ).loss
										loss.backward()







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






										'''simple docstring'''






										lowercase_  							=			self.all_model_classes[1]
										lowercase_  							=			self.model_tester.prepare_config_and_inputs()
										lowercase_  							=			True
										lowercase_  							=			True

										lowercase_  							=			model_class(UpperCAmelCase__       ).to(UpperCAmelCase__       )
										model.train()

										lowercase_  							=			model(UpperCAmelCase__							,					mask_labels=UpperCAmelCase__							,					class_labels=UpperCAmelCase__       )

										lowercase_  							=			outputs.encoder_hidden_states[0]
										encoder_hidden_states.retain_grad()

										lowercase_  							=			outputs.pixel_decoder_hidden_states[0]
										pixel_decoder_hidden_states.retain_grad()

										lowercase_  							=			outputs.transformer_decoder_hidden_states[0]
										transformer_decoder_hidden_states.retain_grad()

										lowercase_  							=			outputs.attentions[0]
										attentions.retain_grad()

										outputs.loss.backward(retain_graph=UpperCAmelCase__       )

										self.assertIsNotNone(encoder_hidden_states.grad       )
										self.assertIsNotNone(pixel_decoder_hidden_states.grad       )
										self.assertIsNotNone(transformer_decoder_hidden_states.grad       )
										self.assertIsNotNone(attentions.grad       )



a					  =     1E-4


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







@require_vision
@slow
class        UpperCamelCase__   (	unittest.TestCase   ):

					@cached_property
					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										return "facebook/mask2former-swin-small-coco-instance"

					@cached_property
					def   UpperCAmelCase__       (     self       :   Union[str, Any]       ):






										'''simple docstring'''






										return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints       ) if is_vision_available() else None

					def   UpperCAmelCase__       (     self       :   List[Any]       ):






										'''simple docstring'''






										lowercase_  							=			MaskaFormerModel.from_pretrained(self.model_checkpoints       ).to(UpperCAmelCase__       )
										lowercase_  							=			self.default_image_processor
										lowercase_  							=			prepare_img()
										lowercase_  							=			image_processor(UpperCAmelCase__							,					return_tensors="""pt"""       ).to(UpperCAmelCase__       )
										lowercase_  							=			inputs['''pixel_values'''].shape
										# check size is divisible by 32
										self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0       )
										# check size
										self.assertEqual(UpperCAmelCase__							,					(1, 3, 384, 384)       )

										with torch.no_grad():
															lowercase_  							=			model(**UpperCAmelCase__       )

										lowercase_  							=			torch.tensor(
										    [[-0.2_790, -1.0_717, -1.1_668], [-0.5_128, -0.3_128, -0.4_987], [-0.5_832, 0.1_971, -0.0_197]]       ).to(UpperCAmelCase__       )
										self.assertTrue(
										    torch.allclose(
										        outputs.encoder_last_hidden_state[0, 0, :3, :3]							,					UpperCAmelCase__							,					atol=UpperCAmelCase__       )       )

										lowercase_  							=			torch.tensor(
										    [[0.8_973, 1.1_847, 1.1_776], [1.1_934, 1.5_040, 1.5_128], [1.1_153, 1.4_486, 1.4_951]]       ).to(UpperCAmelCase__       )
										self.assertTrue(
										    torch.allclose(
										        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]							,					UpperCAmelCase__							,					atol=UpperCAmelCase__       )       )

										lowercase_  							=			torch.tensor(
										    [[2.1_152, 1.7_000, -0.8_603], [1.5_808, 1.8_004, -0.9_353], [1.6_043, 1.7_495, -0.5_999]]       ).to(UpperCAmelCase__       )
										self.assertTrue(
										    torch.allclose(
										        outputs.transformer_decoder_last_hidden_state[0, :3, :3]							,					UpperCAmelCase__							,					atol=UpperCAmelCase__       )       )

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






										'''simple docstring'''






										lowercase_  							=			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints       ).to(UpperCAmelCase__       ).eval()
										lowercase_  							=			self.default_image_processor
										lowercase_  							=			prepare_img()
										lowercase_  							=			image_processor(UpperCAmelCase__							,					return_tensors="""pt"""       ).to(UpperCAmelCase__       )
										lowercase_  							=			inputs['''pixel_values'''].shape
										# check size is divisible by 32
										self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0       )
										# check size
										self.assertEqual(UpperCAmelCase__							,					(1, 3, 384, 384)       )

										with torch.no_grad():
															lowercase_  							=			model(**UpperCAmelCase__       )
										# masks_queries_logits
										lowercase_  							=			outputs.masks_queries_logits
										self.assertEqual(
										    masks_queries_logits.shape							,					(1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)       )
										lowercase_  							=			[
										    [-8.7_839, -9.0_056, -8.8_121],
										    [-7.4_104, -7.0_313, -6.5_401],
										    [-6.6_105, -6.3_427, -6.4_675],
										]
										lowercase_  							=			torch.tensor(UpperCAmelCase__       ).to(UpperCAmelCase__       )
										self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]							,					UpperCAmelCase__							,					atol=UpperCAmelCase__       )       )
										# class_queries_logits
										lowercase_  							=			outputs.class_queries_logits
										self.assertEqual(class_queries_logits.shape							,					(1, model.config.num_queries, model.config.num_labels + 1)       )
										lowercase_  							=			torch.tensor(
										    [
										        [1.8_324, -8.0_835, -4.1_922],
										        [0.8_450, -9.0_050, -3.6_053],
										        [0.3_045, -7.7_293, -3.0_275],
										    ]       ).to(UpperCAmelCase__       )
										self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]							,					UpperCAmelCase__							,					atol=UpperCAmelCase__       )       )







					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






										lowercase_  							=			MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints       ).to(UpperCAmelCase__       ).eval()
										lowercase_  							=			self.default_image_processor

										lowercase_  							=			image_processor(
										    [np.zeros((3, 800, 1_333)       ), np.zeros((3, 800, 1_333)       )]							,					segmentation_maps=[np.zeros((384, 384)       ).astype(np.floataa       ), np.zeros((384, 384)       ).astype(np.floataa       )]							,					return_tensors="""pt"""							,					)

										lowercase_  							=			inputs['''pixel_values'''].to(UpperCAmelCase__       )
										lowercase_  							=			[el.to(UpperCAmelCase__       ) for el in inputs['''mask_labels''']]
										lowercase_  							=			[el.to(UpperCAmelCase__       ) for el in inputs['''class_labels''']]

										with torch.no_grad():
															lowercase_  							=			model(**UpperCAmelCase__       )

										self.assertTrue(outputs.loss is not None       )








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        UpperCamelCase__   (	__magic_name__							,				__magic_name__							,				unittest.TestCase   ):
					__SCREAMING_SNAKE_CASE       :  Optional[int]						=   StableDiffusionDiffEditPipeline
					__SCREAMING_SNAKE_CASE       :  Optional[Any]						=   TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
					__SCREAMING_SNAKE_CASE       :  List[str]						=   TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
					__SCREAMING_SNAKE_CASE       :  int						=   frozenset(
					    []   )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
					__SCREAMING_SNAKE_CASE       :  Any						=   frozenset([]   )

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										torch.manual_seed(0       )
										lowercase_  							=			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=UpperCamelCase__							,					)
										lowercase_  							=			DDIMScheduler(
										    beta_start=0.00_085							,					beta_end=0.012							,					beta_schedule="""scaled_linear"""							,					clip_sample=UpperCamelCase__							,					set_alpha_to_one=UpperCamelCase__							,					)
										lowercase_  							=			DDIMInverseScheduler(
										    beta_start=0.00_085							,					beta_end=0.012							,					beta_schedule="""scaled_linear"""							,					clip_sample=UpperCamelCase__							,					set_alpha_to_zero=UpperCamelCase__							,					)
										torch.manual_seed(0       )
										lowercase_  							=			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       )
										lowercase_  							=			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=1_000							,					hidden_act="""gelu"""							,					projection_dim=512							,					)
										lowercase_  							=			CLIPTextModel(UpperCamelCase__       )
										lowercase_  							=			CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""       )

										lowercase_  							=			{
										    """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       :   int							,					UpperCamelCase__       :   Any							,					UpperCamelCase__       :   Any=0       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor((1, 16, 16)							,					rng=random.Random(UpperCamelCase__       )       ).to(UpperCamelCase__       )
										lowercase_  							=			floats_tensor((1, 2, 4, 16, 16)							,					rng=random.Random(UpperCamelCase__       )       ).to(UpperCamelCase__       )
										if str(UpperCamelCase__       ).startswith("""mps"""       ):
															lowercase_  							=			torch.manual_seed(UpperCamelCase__       )
										else:
															lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(UpperCamelCase__       )
										lowercase_  							=			{
										    """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       :   Optional[int]							,					UpperCamelCase__       :   Union[str, Any]							,					UpperCamelCase__       :   str=0       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor((1, 3, 32, 32)							,					rng=random.Random(UpperCamelCase__       )       ).to(UpperCamelCase__       )
										lowercase_  							=			image.cpu().permute(0							,					2							,					3							,					1       )[0]
										lowercase_  							=			Image.fromarray(np.uinta(UpperCamelCase__       )       ).convert("""RGB"""       )
										if str(UpperCamelCase__       ).startswith("""mps"""       ):
															lowercase_  							=			torch.manual_seed(UpperCamelCase__       )
										else:
															lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(UpperCamelCase__       )
										lowercase_  							=			{
										    """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[Any]							,					UpperCamelCase__       :   Tuple							,					UpperCamelCase__       :   Tuple=0       ):






										'''simple docstring'''






										lowercase_  							=			floats_tensor((1, 3, 32, 32)							,					rng=random.Random(UpperCamelCase__       )       ).to(UpperCamelCase__       )
										lowercase_  							=			image.cpu().permute(0							,					2							,					3							,					1       )[0]
										lowercase_  							=			Image.fromarray(np.uinta(UpperCamelCase__       )       ).convert("""RGB"""       )
										if str(UpperCamelCase__       ).startswith("""mps"""       ):
															lowercase_  							=			torch.manual_seed(UpperCamelCase__       )
										else:
															lowercase_  							=			torch.Generator(device=UpperCamelCase__       ).manual_seed(UpperCamelCase__       )
										lowercase_  							=			{
										    """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       :   int       ):






										'''simple docstring'''






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

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

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

										lowercase_  							=			self.get_dummy_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe(**UpperCamelCase__       )[0]

										with tempfile.TemporaryDirectory() as tmpdir:
															pipe.save_pretrained(UpperCamelCase__       )
															lowercase_  							=			self.pipeline_class.from_pretrained(UpperCamelCase__       )
															pipe_loaded.to(UpperCamelCase__       )
															pipe_loaded.set_progress_bar_config(disable=UpperCamelCase__       )

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

										lowercase_  							=			self.get_dummy_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe_loaded(**UpperCamelCase__       )[0]

										lowercase_  							=			np.abs(output - output_loaded       ).max()
										self.assertLess(UpperCamelCase__							,					1e-4       )

					def   UpperCAmelCase__       (     self       :   Optional[int]       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			self.get_dummy_mask_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe.generate_mask(**UpperCamelCase__       )
										lowercase_  							=			mask[0, -3:, -3:]

										self.assertEqual(mask.shape							,					(1, 16, 16)       )
										lowercase_  							=			np.array([0] * 9       )
										lowercase_  							=			np.abs(mask_slice.flatten() - expected_slice       ).max()
										self.assertLessEqual(UpperCamelCase__							,					1e-3       )
										self.assertEqual(mask[0, -3, -4]							,					0       )

					def   UpperCAmelCase__       (     self       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()
										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			self.get_dummy_inversion_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe.invert(**UpperCamelCase__       ).images
										lowercase_  							=			image[0, -1, -3:, -3:]

										self.assertEqual(image.shape							,					(2, 32, 32, 3)       )
										lowercase_  							=			np.array(
										    [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]							,					)
										lowercase_  							=			np.abs(image_slice.flatten() - expected_slice       ).max()
										self.assertLessEqual(UpperCamelCase__							,					1e-3       )

					def   UpperCAmelCase__       (     self       :   Optional[Any]       ):






										'''simple docstring'''






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







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






										'''simple docstring'''






										lowercase_  							=			"""cpu"""

										lowercase_  							=			self.get_dummy_components()

										lowercase_  							=			{"""beta_start""": 0.00_085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""}
										lowercase_  							=			DPMSolverMultistepScheduler(**UpperCamelCase__       )
										lowercase_  							=			DPMSolverMultistepInverseScheduler(**UpperCamelCase__       )

										lowercase_  							=			self.pipeline_class(**UpperCamelCase__       )
										pipe.to(UpperCamelCase__       )
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			self.get_dummy_inversion_inputs(UpperCamelCase__       )
										lowercase_  							=			pipe.invert(**UpperCamelCase__       ).images
										lowercase_  							=			image[0, -1, -3:, -3:]

										self.assertEqual(image.shape							,					(2, 32, 32, 3)       )
										lowercase_  							=			np.array(
										    [0.5_150, 0.5_134, 0.5_043, 0.5_376, 0.4_694, 0.51_050, 0.5_015, 0.4_407, 0.4_799]							,					)
										lowercase_  							=			np.abs(image_slice.flatten() - expected_slice       ).max()
										self.assertLessEqual(UpperCamelCase__							,					1e-3       )







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

					def   UpperCAmelCase__       (     self       :   Tuple       ):






										'''simple docstring'''






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

					@classmethod
					def   UpperCAmelCase__       (     cls       :   Dict       ):






										'''simple docstring'''






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

										lowercase_  							=			raw_image.convert("""RGB"""       ).resize((768, 768)       )

										lowercase_  							=			raw_image

					def   UpperCAmelCase__       (     self       :   Dict       ):






										'''simple docstring'''






										lowercase_  							=			torch.manual_seed(0       )

										lowercase_  							=			StableDiffusionDiffEditPipeline.from_pretrained(
										    """stabilityai/stable-diffusion-2-1"""							,					safety_checker=UpperCamelCase__							,					torch_dtype=torch.floataa       )
										lowercase_  							=			DDIMScheduler.from_config(pipe.scheduler.config       )
										lowercase_  							=			DDIMInverseScheduler.from_config(pipe.scheduler.config       )
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			"""a bowl of fruit"""
										lowercase_  							=			"""a bowl of pears"""

										lowercase_  							=			pipe.generate_mask(
										    image=self.raw_image							,					source_prompt=UpperCamelCase__							,					target_prompt=UpperCamelCase__							,					generator=UpperCamelCase__							,					)

										lowercase_  							=			pipe.invert(
										    prompt=UpperCamelCase__							,					image=self.raw_image							,					inpaint_strength=0.7							,					generator=UpperCamelCase__       ).latents

										lowercase_  							=			pipe(
										    prompt=UpperCamelCase__							,					mask_image=UpperCamelCase__							,					image_latents=UpperCamelCase__							,					generator=UpperCamelCase__							,					negative_prompt=UpperCamelCase__							,					inpaint_strength=0.7							,					output_type="""numpy"""							,					).images[0]

										lowercase_  							=			(
										    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       :   Any       ):






										'''simple docstring'''






										lowercase_  							=			torch.manual_seed(0       )

										lowercase_  							=			StableDiffusionDiffEditPipeline.from_pretrained(
										    """stabilityai/stable-diffusion-2-1"""							,					safety_checker=UpperCamelCase__							,					torch_dtype=torch.floataa       )
										lowercase_  							=			DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
										lowercase_  							=			DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config       )
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=UpperCamelCase__       )

										lowercase_  							=			"""a bowl of fruit"""
										lowercase_  							=			"""a bowl of pears"""

										lowercase_  							=			pipe.generate_mask(
										    image=self.raw_image							,					source_prompt=UpperCamelCase__							,					target_prompt=UpperCamelCase__							,					generator=UpperCamelCase__							,					)

										lowercase_  							=			pipe.invert(
										    prompt=UpperCamelCase__							,					image=self.raw_image							,					inpaint_strength=0.7							,					generator=UpperCamelCase__							,					num_inference_steps=25							,					).latents

										lowercase_  							=			pipe(
										    prompt=UpperCamelCase__							,					mask_image=UpperCamelCase__							,					image_latents=UpperCamelCase__							,					generator=UpperCamelCase__							,					negative_prompt=UpperCamelCase__							,					inpaint_strength=0.7							,					num_inference_steps=25							,					output_type="""numpy"""							,					).images[0]

										lowercase_  							=			(
										    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


