

import unittest

from parameterized import parameterized

from transformers import AutoTokenizer, GPTNeoXConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    GPTNeoXForCausalLM,
		    GPTNeoXForQuestionAnswering,
		    GPTNeoXForSequenceClassification,
		    GPTNeoXForTokenClassification,
		    GPTNeoXModel,
		)


class SCREAMING_SNAKE_CASE	:






			"""simple docstring"""




			def __init__(     self			,					__UpperCamelCase			,					__UpperCamelCase=13			,					__UpperCamelCase=7			,					__UpperCamelCase=True			,					__UpperCamelCase=True			,					__UpperCamelCase=True			,					__UpperCamelCase=True			,					__UpperCamelCase=99			,					__UpperCamelCase=64			,					__UpperCamelCase=5			,					__UpperCamelCase=4			,					__UpperCamelCase=37			,					__UpperCamelCase="gelu"			,					__UpperCamelCase=0.1			,					__UpperCamelCase=0.1			,					__UpperCamelCase=5_12			,					__UpperCamelCase=16			,					__UpperCamelCase=2			,					__UpperCamelCase=0.02			,					__UpperCamelCase=3			,					__UpperCamelCase=4			,					__UpperCamelCase=None			,					):

				"""simple docstring"""


				snake_case_   		=			parent
				snake_case_   		=			batch_size
				snake_case_   		=			seq_length
				snake_case_   		=			is_training
				snake_case_   		=			use_input_mask
				snake_case_   		=			use_token_type_ids
				snake_case_   		=			use_labels
				snake_case_   		=			vocab_size
				snake_case_   		=			hidden_size
				snake_case_   		=			num_hidden_layers
				snake_case_   		=			num_attention_heads
				snake_case_   		=			intermediate_size
				snake_case_   		=			hidden_act
				snake_case_   		=			hidden_dropout_prob
				snake_case_   		=			attention_probs_dropout_prob
				snake_case_   		=			max_position_embeddings
				snake_case_   		=			type_vocab_size
				snake_case_   		=			type_sequence_label_size
				snake_case_   		=			initializer_range
				snake_case_   		=			num_labels
				snake_case_   		=			num_choices
				snake_case_   		=			scope
				snake_case_   		=			vocab_size - 1


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			ids_tensor([self.batch_size, self.seq_length]			,					self.vocab_size				)

				snake_case_   		=			None
				if self.use_input_mask:
					snake_case_   		=			random_attention_mask([self.batch_size, self.seq_length]				)

				snake_case_   		=			None
				if self.use_labels:
					snake_case_   		=			ids_tensor([self.batch_size, self.seq_length]			,					self.num_labels				)

				snake_case_   		=			self.get_config()

				return config, input_ids, input_mask, token_labels


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				return GPTNeoXConfig(
				    vocab_size=self.vocab_size			,					hidden_size=self.hidden_size			,					num_hidden_layers=self.num_hidden_layers			,					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			,					max_position_embeddings=self.max_position_embeddings			,					type_vocab_size=self.type_vocab_size			,					is_decoder=__UpperCamelCase			,					initializer_range=self.initializer_range			,					pad_token_id=self.pad_token_id			,					)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			self.prepare_config_and_inputs()

				snake_case_   		=			True

				return config, input_ids, input_mask, token_labels


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			GPTNeoXModel(config=__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase				)
				snake_case_   		=			model(__UpperCamelCase				)
				self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			True
				snake_case_   		=			GPTNeoXModel(__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase				)
				self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			GPTNeoXForCausalLM(config=__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					labels=__UpperCamelCase				)
				self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.seq_length, self.vocab_size)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			self.num_labels
				snake_case_   		=			GPTNeoXForQuestionAnswering(__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase				)
				self.parent.assertEqual(result.start_logits.shape			,					(self.batch_size, self.seq_length)				)
				self.parent.assertEqual(result.end_logits.shape			,					(self.batch_size, self.seq_length)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			self.num_labels
				snake_case_   		=			GPTNeoXForSequenceClassification(__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			ids_tensor([self.batch_size]			,					self.type_sequence_label_size				)
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					labels=__UpperCamelCase				)
				self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_labels)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			self.num_labels
				snake_case_   		=			GPTNeoXForTokenClassification(__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					labels=__UpperCamelCase				)
				self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.seq_length, self.num_labels)				)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			True
				snake_case_   		=			GPTNeoXForCausalLM(config=__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()

				# first forward pass
				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					use_cache=__UpperCamelCase				)
				snake_case_   		=			outputs.past_key_values

				# create hypothetical multiple next token and extent to next_input_ids
				snake_case_   		=			ids_tensor((self.batch_size, 3)			,					config.vocab_size				)
				snake_case_   		=			ids_tensor((self.batch_size, 3)			,					vocab_size=2				)

				# append to next input_ids and
				snake_case_   		=			torch.cat([input_ids, next_tokens]			,					dim=-1				)
				snake_case_   		=			torch.cat([input_mask, next_mask]			,					dim=-1				)

				snake_case_   		=			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					output_hidden_states=__UpperCamelCase				)
				snake_case_   		=			output_from_no_past['hidden_states'][0]
				snake_case_   		=			model(
				    __UpperCamelCase			,					attention_mask=__UpperCamelCase			,					past_key_values=__UpperCamelCase			,					output_hidden_states=__UpperCamelCase			,					)['hidden_states'][0]

				# select random slice
				snake_case_   		=			ids_tensor((1,)			,					output_from_past.shape[-1]				).item()
				snake_case_   		=			output_from_no_past[:, -3:, random_slice_idx].detach()
				snake_case_   		=			output_from_past[:, :, random_slice_idx].detach()

				self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]				)

				# test that outputs are equal for slice
				self.parent.assertTrue(torch.allclose(__UpperCamelCase			,					__UpperCamelCase			,					atol=1E-3				)				)







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.prepare_config_and_inputs()
				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			config_and_inputs
				snake_case_   		=			{'input_ids': input_ids, 'attention_mask': input_mask}
				return config, inputs_dict







@require_torch
class SCREAMING_SNAKE_CASE	(		__snake_case				,    __snake_case				,    __snake_case				,    unittest.TestCase				):






			"""simple docstring"""




			__A    	=	(
			    (
			        GPTNeoXModel,
			        GPTNeoXForCausalLM,
			        GPTNeoXForQuestionAnswering,
			        GPTNeoXForSequenceClassification,
			        GPTNeoXForTokenClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			__A    	=	(GPTNeoXForCausalLM,) if is_torch_available() else ()
			__A    	=	(
			    {
			        """feature-extraction""": GPTNeoXModel,
			        """question-answering""": GPTNeoXForQuestionAnswering,
			        """text-classification""": GPTNeoXForSequenceClassification,
			        """text-generation""": GPTNeoXForCausalLM,
			        """token-classification""": GPTNeoXForTokenClassification,
			        """zero-shot""": GPTNeoXForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			__A    	=	False
			__A    	=	False
			__A    	=	False
			__A    	=	False


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			GPTNeoXModelTester(self				)
				snake_case_   		=			ConfigTester(self			,					config_class=__UpperCamelCase			,					hidden_size=64			,					num_attention_heads=8				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				self.config_tester.run_common_tests()


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			self.model_tester.prepare_config_and_inputs_for_decoder()
				self.model_tester.create_and_check_model_as_decoder(__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			self.model_tester.prepare_config_and_inputs_for_decoder()

				snake_case_   		=			None

				self.model_tester.create_and_check_model_as_decoder(__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_		,							snake_case_		,							snake_case_		,							snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_decoder_model_past_large_inputs(__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_causal_lm(*__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_question_answering(*__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_sequence_classification(*__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_token_classification(*__UpperCamelCase				)


			@unittest.skip(reason='Feed forward chunking is not implemented'				)
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				pass







			@parameterized.expand([('linear',), ('dynamic',)]				)
			def       __lowerCAmelCase			(     self			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_		,							snake_case_   		=			self.model_tester.prepare_config_and_inputs_for_common()
				snake_case_   		=			ids_tensor([1, 10]			,					config.vocab_size				)
				snake_case_   		=			ids_tensor([1, int(config.max_position_embeddings * 1.5				)]			,					config.vocab_size				)

				set_seed(42				)  # Fixed seed at init time so the two models get the same random weights
				snake_case_   		=			GPTNeoXModel(__UpperCamelCase				)
				original_model.to(__UpperCamelCase				)
				original_model.eval()
				snake_case_   		=			original_model(__UpperCamelCase				).last_hidden_state
				snake_case_   		=			original_model(__UpperCamelCase				).last_hidden_state

				set_seed(42				)  # Fixed seed at init time so the two models get the same random weights
				snake_case_   		=			{'type': scaling_type, 'factor': 10.0}
				snake_case_   		=			GPTNeoXModel(__UpperCamelCase				)
				scaled_model.to(__UpperCamelCase				)
				scaled_model.eval()
				snake_case_   		=			scaled_model(__UpperCamelCase				).last_hidden_state
				snake_case_   		=			scaled_model(__UpperCamelCase				).last_hidden_state

				# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
				# maximum sequence length, so the outputs for the short input should match.
				if scaling_type == "dynamic":
					self.assertTrue(torch.allclose(__UpperCamelCase			,					__UpperCamelCase			,					atol=1E-5				)				)
				else:
					self.assertFalse(torch.allclose(__UpperCamelCase			,					__UpperCamelCase			,					atol=1E-5				)				)

				# The output should be different for long inputs
				self.assertFalse(torch.allclose(__UpperCamelCase			,					__UpperCamelCase			,					atol=1E-5				)				)







@require_torch
class SCREAMING_SNAKE_CASE	(		unittest.TestCase				):






			"""simple docstring"""




			@slow
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			AutoTokenizer.from_pretrained('EleutherAI/pythia-410m-deduped'				)
				for checkpointing in [True, False]:
					snake_case_   		=			GPTNeoXForCausalLM.from_pretrained('EleutherAI/pythia-410m-deduped'				)

					if checkpointing:
						model.gradient_checkpointing_enable()
					else:
						model.gradient_checkpointing_disable()
					model.to(__UpperCamelCase				)

					snake_case_   		=			tokenizer('My favorite food is'			,					return_tensors='pt'				).to(__UpperCamelCase				)
					# The hub repo. is updated on 2023-04-04, resulting in poor outputs.
					# See: https://github.com/huggingface/transformers/pull/24193
					snake_case_   		=			'My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI\'m not sure'

					snake_case_   		=			model.generate(**__UpperCamelCase			,					do_sample=__UpperCamelCase			,					max_new_tokens=20				)
					snake_case_   		=			tokenizer.batch_decode(__UpperCamelCase				)[0]

					self.assertEqual(__UpperCamelCase			,					__UpperCamelCase				)



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 SCREAMING_SNAKE_CASE	(		__snake_case				,    __snake_case				,    unittest.TestCase				):






			"""simple docstring"""




			__A    	=	StableDiffusionDiffEditPipeline
			__A    	=	TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""}
			__A    	=	TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""}
			__A    	=	frozenset(
			    []				)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
			__A    	=	frozenset([]				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				torch.manual_seed(0				)
				snake_case_   		=			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			,					)
				snake_case_   		=			DDIMScheduler(
				    beta_start=0.0_0085			,					beta_end=0.012			,					beta_schedule='scaled_linear'			,					clip_sample=__UpperCamelCase			,					set_alpha_to_one=__UpperCamelCase			,					)
				snake_case_   		=			DDIMInverseScheduler(
				    beta_start=0.0_0085			,					beta_end=0.012			,					beta_schedule='scaled_linear'			,					clip_sample=__UpperCamelCase			,					set_alpha_to_zero=__UpperCamelCase			,					)
				torch.manual_seed(0				)
				snake_case_   		=			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=1_28			,					)
				torch.manual_seed(0				)
				snake_case_   		=			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=10_00			,					hidden_act='gelu'			,					projection_dim=5_12			,					)
				snake_case_   		=			CLIPTextModel(__UpperCamelCase				)
				snake_case_   		=			CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

				snake_case_   		=			{
				    '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       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase=0				):

				"""simple docstring"""


				snake_case_   		=			floats_tensor((1, 16, 16)			,					rng=random.Random(__UpperCamelCase				)				).to(__UpperCamelCase				)
				snake_case_   		=			floats_tensor((1, 2, 4, 16, 16)			,					rng=random.Random(__UpperCamelCase				)				).to(__UpperCamelCase				)
				if str(__UpperCamelCase				).startswith('mps'				):
					snake_case_   		=			torch.manual_seed(__UpperCamelCase				)
				else:
					snake_case_   		=			torch.Generator(device=__UpperCamelCase				).manual_seed(__UpperCamelCase				)
				snake_case_   		=			{
				    '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       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase=0				):

				"""simple docstring"""


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

				"""simple docstring"""


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

				"""simple docstring"""


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

				snake_case_   		=			self.get_dummy_components()
				snake_case_   		=			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}				)

				snake_case_   		=			self.get_dummy_inputs(__UpperCamelCase				)
				snake_case_   		=			pipe(**__UpperCamelCase				)[0]

				with tempfile.TemporaryDirectory() as tmpdir:
					pipe.save_pretrained(__UpperCamelCase				)
					snake_case_   		=			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."""			,					)

				snake_case_   		=			self.get_dummy_inputs(__UpperCamelCase				)
				snake_case_   		=			pipe_loaded(**__UpperCamelCase				)[0]

				snake_case_   		=			np.abs(output - output_loaded				).max()
				self.assertLess(__UpperCamelCase			,					1E-4				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			'cpu'

				snake_case_   		=			self.get_dummy_components()
				snake_case_   		=			self.pipeline_class(**__UpperCamelCase				)
				pipe.to(__UpperCamelCase				)
				pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

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


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			'cpu'

				snake_case_   		=			self.get_dummy_components()
				snake_case_   		=			self.pipeline_class(**__UpperCamelCase				)
				pipe.to(__UpperCamelCase				)
				pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

				self.assertEqual(image.shape			,					(2, 32, 32, 3)				)
				snake_case_   		=			np.array(
				    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]			,					)
				snake_case_   		=			np.abs(image_slice.flatten() - expected_slice				).max()
				self.assertLessEqual(__UpperCamelCase			,					1E-3				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


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







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			'cpu'

				snake_case_   		=			self.get_dummy_components()

				snake_case_   		=			{'beta_start': 0.0_0085, 'beta_end': 0.012, 'beta_schedule': 'scaled_linear'}
				snake_case_   		=			DPMSolverMultistepScheduler(**__UpperCamelCase				)
				snake_case_   		=			DPMSolverMultistepInverseScheduler(**__UpperCamelCase				)

				snake_case_   		=			self.pipeline_class(**__UpperCamelCase				)
				pipe.to(__UpperCamelCase				)
				pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

				self.assertEqual(image.shape			,					(2, 32, 32, 3)				)
				snake_case_   		=			np.array(
				    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]			,					)
				snake_case_   		=			np.abs(image_slice.flatten() - expected_slice				).max()
				self.assertLessEqual(__UpperCamelCase			,					1E-3				)







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






			"""simple docstring"""




			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


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


			@classmethod
			def       __lowerCAmelCase			(     cls				):

				"""simple docstring"""


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

				snake_case_   		=			raw_image.convert('RGB'				).resize((7_68, 7_68)				)

				snake_case_   		=			raw_image


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			torch.manual_seed(0				)

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

				snake_case_   		=			'a bowl of fruit'
				snake_case_   		=			'a bowl of pears'

				snake_case_   		=			pipe.generate_mask(
				    image=self.raw_image			,					source_prompt=__UpperCamelCase			,					target_prompt=__UpperCamelCase			,					generator=__UpperCamelCase			,					)

				snake_case_   		=			pipe.invert(
				    prompt=__UpperCamelCase			,					image=self.raw_image			,					inpaint_strength=0.7			,					generator=__UpperCamelCase				).latents

				snake_case_   		=			pipe(
				    prompt=__UpperCamelCase			,					mask_image=__UpperCamelCase			,					image_latents=__UpperCamelCase			,					generator=__UpperCamelCase			,					negative_prompt=__UpperCamelCase			,					inpaint_strength=0.7			,					output_type='numpy'			,					).images[0]

				snake_case_   		=			(
				    np.array(
				        load_image(
				            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
				            '/diffedit/pears.png'				).resize((7_68, 7_68)				)				)
				    / 2_55
				)
				assert np.abs((expected_image - image).max()				) < 5E-1







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			torch.manual_seed(0				)

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

				snake_case_   		=			'a bowl of fruit'
				snake_case_   		=			'a bowl of pears'

				snake_case_   		=			pipe.generate_mask(
				    image=self.raw_image			,					source_prompt=__UpperCamelCase			,					target_prompt=__UpperCamelCase			,					generator=__UpperCamelCase			,					)

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

				snake_case_   		=			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]

				snake_case_   		=			(
				    np.array(
				        load_image(
				            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
				            '/diffedit/pears.png'				).resize((7_68, 7_68)				)				)
				    / 2_55
				)
				assert np.abs((expected_image - image).max()				) < 5E-1
