
'''simple docstring'''


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




@skip_mps
class 						__snake_case (						_a				, _a				, _a				, unittest.TestCase  ):
		a_        =				StableDiffusionModelEditingPipeline
		a_        =				TEXT_TO_IMAGE_PARAMS
		a_        =				TEXT_TO_IMAGE_BATCH_PARAMS
		a_        =				TEXT_TO_IMAGE_IMAGE_PARAMS
		a_        =				TEXT_TO_IMAGE_IMAGE_PARAMS




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






								'''simple docstring'''






								torch.manual_seed(0)
								UpperCamelCase_    :  int				    =    UNetaDConditionModel(
								    block_out_channels=(3_2, 6_4) ,						layers_per_block=2 ,						sample_size=3_2 ,						in_channels=4 ,						out_channels=4 ,						down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,						up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,						cross_attention_dim=3_2 ,						)
								UpperCamelCase_    :  List[Any]				    =    DDIMScheduler()
								torch.manual_seed(0)
								UpperCamelCase_    :  List[str]				    =    AutoencoderKL(
								    block_out_channels=[3_2, 6_4] ,						in_channels=3 ,						out_channels=3 ,						down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,						up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,						latent_channels=4 ,						)
								torch.manual_seed(0)
								UpperCamelCase_    :  str				    =    CLIPTextConfig(
								    bos_token_id=0 ,						eos_token_id=2 ,						hidden_size=3_2 ,						intermediate_size=3_7 ,						layer_norm_eps=1E-05 ,						num_attention_heads=4 ,						num_hidden_layers=5 ,						pad_token_id=1 ,						vocab_size=1_0_0_0 ,						)
								UpperCamelCase_    :  Any				    =    CLIPTextModel(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Dict				    =    CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

								UpperCamelCase_    :  List[Any]				    =    {
								    """unet""": unet,
								    """scheduler""": scheduler,
								    """vae""": vae,
								    """text_encoder""": text_encoder,
								    """tokenizer""": tokenizer,
								    """safety_checker""": None,
								    """feature_extractor""": None,
								}
								return components




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






								'''simple docstring'''






								UpperCamelCase_    :  Union[str, Any]				    =    torch.manual_seed(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  List[str]				    =    {
								    """prompt""": """A field of roses""",
								    """generator""": generator,
								    # Setting height and width to None to prevent OOMs on CPU.
								    """height""": None,
								    """width""": None,
								    """num_inference_steps""": 2,
								    """guidance_scale""": 6.0,
								    """output_type""": """numpy""",
								}
								return inputs




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






								'''simple docstring'''






								UpperCamelCase_    :  Tuple				    =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCamelCase_    :  Union[str, Any]				    =    self.get_dummy_components()
								UpperCamelCase_    :  Any				    =    StableDiffusionModelEditingPipeline(**_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Dict				    =    sd_pipe.to(_SCREAMING_SNAKE_CASE)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

								UpperCamelCase_    :  Dict				    =    self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Optional[int]				    =    sd_pipe(**_SCREAMING_SNAKE_CASE).images
								UpperCamelCase_    :  List[Any]				    =    image[0, -3:, -3:, -1]
								assert image.shape == (1, 6_4, 6_4, 3)

								UpperCamelCase_    :  Any				    =    np.array([0.4755, 0.5132, 0.4976, 0.3904, 0.3554, 0.4765, 0.5139, 0.5158, 0.4889])

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




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






								'''simple docstring'''






								UpperCamelCase_    :  Union[str, Any]				    =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCamelCase_    :  List[str]				    =    self.get_dummy_components()
								UpperCamelCase_    :  Any				    =    StableDiffusionModelEditingPipeline(**_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  List[str]				    =    sd_pipe.to(_SCREAMING_SNAKE_CASE)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

								UpperCamelCase_    :  str				    =    self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Optional[int]				    =    """french fries"""
								UpperCamelCase_    :  Optional[int]				    =    sd_pipe(**_SCREAMING_SNAKE_CASE ,						negative_prompt=_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  List[Any]				    =    output.images
								UpperCamelCase_    :  Optional[int]				    =    image[0, -3:, -3:, -1]

								assert image.shape == (1, 6_4, 6_4, 3)

								UpperCamelCase_    :  Dict				    =    np.array([0.4992, 0.5101, 0.5004, 0.3949, 0.3604, 0.4735, 0.5216, 0.5204, 0.4913])

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




		def   _snake_case  (     self				:Any)				-> int:






								'''simple docstring'''






								UpperCamelCase_    :  Tuple				    =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCamelCase_    :  Union[str, Any]				    =    self.get_dummy_components()
								UpperCamelCase_    :  Optional[int]				    =    EulerAncestralDiscreteScheduler(
								    beta_start=0.00085 ,						beta_end=0.012 ,						beta_schedule="""scaled_linear""")
								UpperCamelCase_    :  Tuple				    =    StableDiffusionModelEditingPipeline(**_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Dict				    =    sd_pipe.to(_SCREAMING_SNAKE_CASE)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

								UpperCamelCase_    :  str				    =    self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  int				    =    sd_pipe(**_SCREAMING_SNAKE_CASE).images
								UpperCamelCase_    :  Tuple				    =    image[0, -3:, -3:, -1]

								assert image.shape == (1, 6_4, 6_4, 3)

								UpperCamelCase_    :  int				    =    np.array([0.4747, 0.5372, 0.4779, 0.4982, 0.5543, 0.4816, 0.5238, 0.4904, 0.5027])

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




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






								'''simple docstring'''






								UpperCamelCase_    :  int				    =    """cpu"""  # ensure determinism for the device-dependent torch.Generator
								UpperCamelCase_    :  int				    =    self.get_dummy_components()
								UpperCamelCase_    :  List[Any]				    =    PNDMScheduler()
								UpperCamelCase_    :  str				    =    StableDiffusionModelEditingPipeline(**_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Union[str, Any]				    =    sd_pipe.to(_SCREAMING_SNAKE_CASE)
								sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

								UpperCamelCase_    :  Dict				    =    self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
								# the pipeline does not expect pndm so test if it raises error.
								with self.assertRaises(_SCREAMING_SNAKE_CASE):
														UpperCamelCase_    :  List[str]				    =    sd_pipe(**_SCREAMING_SNAKE_CASE).images




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






								'''simple docstring'''






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





		def   _snake_case  (     self				:int)				-> Dict:






								'''simple docstring'''






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







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




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






								'''simple docstring'''






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




		def   _snake_case  (     self				:Any ,						_SCREAMING_SNAKE_CASE				:Tuple=0)				-> Optional[Any]:






								'''simple docstring'''






								UpperCamelCase_    :  Tuple				    =    torch.manual_seed(_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Optional[int]				    =    {
								    """prompt""": """A field of roses""",
								    """generator""": generator,
								    """num_inference_steps""": 3,
								    """guidance_scale""": 7.5,
								    """output_type""": """numpy""",
								}
								return inputs




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






								'''simple docstring'''






								UpperCamelCase_    :  Optional[Any]				    =    """CompVis/stable-diffusion-v1-4"""
								UpperCamelCase_    :  Optional[int]				    =    StableDiffusionModelEditingPipeline.from_pretrained(_SCREAMING_SNAKE_CASE ,						safety_checker=_SCREAMING_SNAKE_CASE)
								pipe.to(_SCREAMING_SNAKE_CASE)
								pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)
								pipe.enable_attention_slicing()

								UpperCamelCase_    :  List[str]				    =    self.get_inputs()
								UpperCamelCase_    :  Dict				    =    pipe(**_SCREAMING_SNAKE_CASE).images
								UpperCamelCase_    :  str				    =    image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 5_1_2, 5_1_2, 3)

								UpperCamelCase_    :  int				    =    np.array(
								    [0.6749496, 0.6386453, 0.51443267, 0.66094905, 0.61921215, 0.5491332, 0.5744417, 0.58075106, 0.5174658])

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

								# make sure image changes after editing
								pipe.edit_model("""A pack of roses""" ,						"""A pack of blue roses""")

								UpperCamelCase_    :  Union[str, Any]				    =    pipe(**_SCREAMING_SNAKE_CASE).images
								UpperCamelCase_    :  Any				    =    image[0, -3:, -3:, -1].flatten()

								assert image.shape == (1, 5_1_2, 5_1_2, 3)

								assert np.abs(expected_slice - image_slice).max() > 1E-1





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






								'''simple docstring'''






								torch.cuda.empty_cache()
								torch.cuda.reset_max_memory_allocated()
								torch.cuda.reset_peak_memory_stats()

								UpperCamelCase_    :  int				    =    """CompVis/stable-diffusion-v1-4"""
								UpperCamelCase_    :  str				    =    DDIMScheduler.from_pretrained(_SCREAMING_SNAKE_CASE ,						subfolder="""scheduler""")
								UpperCamelCase_    :  Optional[Any]				    =    StableDiffusionModelEditingPipeline.from_pretrained(
								    _SCREAMING_SNAKE_CASE ,						scheduler=_SCREAMING_SNAKE_CASE ,						safety_checker=_SCREAMING_SNAKE_CASE)
								UpperCamelCase_    :  Union[str, Any]				    =    pipe.to(_SCREAMING_SNAKE_CASE)
								pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)
								pipe.enable_attention_slicing(1)
								pipe.enable_sequential_cpu_offload()

								UpperCamelCase_    :  Dict				    =    self.get_inputs()
								UpperCamelCase_    :  Optional[Any]				    =    pipe(**_SCREAMING_SNAKE_CASE)

								UpperCamelCase_    :  Optional[int]				    =    torch.cuda.max_memory_allocated()
								# make sure that less than 4.4 GB is allocated
								assert mem_bytes < 4.4 * 1_0**9






'''simple docstring'''


import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__SCREAMING_SNAKE_CASE  =			"src/transformers"

# Matches is_xxx_available()
__SCREAMING_SNAKE_CASE  =			re.compile(r"is\_([a-z_]*)_available()")
# Matches from xxx import bla
__SCREAMING_SNAKE_CASE  =			re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
__SCREAMING_SNAKE_CASE  =			re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)")


__SCREAMING_SNAKE_CASE  =			"\n{0} = None\n"

__SCREAMING_SNAKE_CASE  =			"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"


__SCREAMING_SNAKE_CASE  =			"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]  ):
						if _re_test_backend.search(UpperCAmelCase__  ) is None:
												return None
						UpperCamelCase_    :  str				    =    [b[0] for b in _re_backend.findall(UpperCAmelCase__  )]
						backends.sort()
						return "_and_".join(UpperCAmelCase__  )
def 				__magic_name__(					):
						with open(os.path.join(UpperCAmelCase__       ,							"""__init__.py"""  )       ,							"""r"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
												UpperCamelCase_    :  Dict				    =    f.readlines()

						# Get to the point we do the actual imports for type checking
						UpperCamelCase_    :  Tuple				    =    0
						while not lines[line_index].startswith("""if TYPE_CHECKING"""  ):
												line_index += 1

						UpperCamelCase_    :  Optional[int]				    =    {}
						# Go through the end of the file
						while line_index < len(UpperCAmelCase__  ):
												# If the line is an if is_backend_available, we grab all objects associated.
												UpperCamelCase_    :  str				    =    find_backend(lines[line_index]  )
												if backend is not None:
																		while not lines[line_index].startswith("""    else:"""  ):
																								line_index += 1
																		line_index += 1

																		UpperCamelCase_    :  Dict				    =    []
																		# Until we unindent, add backend objects to the list
																		while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(""" """ * 8  ):
																								UpperCamelCase_    :  Any				    =    lines[line_index]
																								UpperCamelCase_    :  str				    =    _re_single_line_import.search(UpperCAmelCase__  )
																								if single_line_import_search is not None:
																														objects.extend(single_line_import_search.groups()[0].split(""", """  )  )
																								elif line.startswith(""" """ * 12  ):
																														objects.append(line[12:-2]  )
																								line_index += 1

																		UpperCamelCase_    :  List[Any]				    =    objects
												else:
																		line_index += 1

						return backend_specific_objects
def 				__magic_name__(					UpperCAmelCase__   :					Any       ,							UpperCAmelCase__   :					Optional[Any]  ):
						if name.isupper():
												return DUMMY_CONSTANT.format(UpperCAmelCase__  )
						elif name.islower():
												return DUMMY_FUNCTION.format(UpperCAmelCase__       ,							UpperCAmelCase__  )
						else:
												return DUMMY_CLASS.format(UpperCAmelCase__       ,							UpperCAmelCase__  )
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]=None  ):
						if backend_specific_objects is None:
												UpperCamelCase_    :  Optional[Any]				    =    read_init()
						# For special correspondence backend to module name as used in the function requires_modulename
						UpperCamelCase_    :  List[str]				    =    {}

						for backend, objects in backend_specific_objects.items():
												UpperCamelCase_    :  Optional[Any]				    =    """[""" + """, """.join(f"""\"{b}\"""" for b in backend.split("""_and_"""  )  ) + """]"""
												UpperCamelCase_    :  Union[str, Any]				    =    """# This file is autogenerated by the command `make fix-copies`, do not edit.\n"""
												dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
												dummy_file += "\n".join([create_dummy_object(UpperCAmelCase__       ,							UpperCAmelCase__  ) for o in objects]  )
												UpperCamelCase_    :  List[Any]				    =    dummy_file

						return dummy_files
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]=False  ):
						UpperCamelCase_    :  int				    =    create_dummy_files()
						# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
						UpperCamelCase_    :  Union[str, Any]				    =    {"""torch""": """pt"""}

						# Locate actual dummy modules and read their content.
						UpperCamelCase_    :  Optional[int]				    =    os.path.join(UpperCAmelCase__       ,							"""utils"""  )
						UpperCamelCase_    :  str				    =    {
						    backend: os.path.join(UpperCAmelCase__       ,							f"""dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py"""  )
						    for backend in dummy_files.keys()
						}

						UpperCamelCase_    :  int				    =    {}
						for backend, file_path in dummy_file_paths.items():
												if os.path.isfile(UpperCAmelCase__  ):
																		with open(UpperCAmelCase__       ,							"""r"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
																								UpperCamelCase_    :  str				    =    f.read()
												else:
																		UpperCamelCase_    :  str				    =    """"""

						for backend in dummy_files.keys():
												if dummy_files[backend] != actual_dummies[backend]:
																		if overwrite:
																								print(
																								    f"""Updating transformers.utils.dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py as the main """
																								    """__init__ has new objects."""  )
																								with open(dummy_file_paths[backend]       ,							"""w"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
																														f.write(dummy_files[backend]  )
																		else:
																								raise ValueError(
																								    """The main __init__ has objects that are not present in """
																								    f"""transformers.utils.dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py. Run `make fix-copies` """
																								    """to fix this."""  )


if __name__ == "__main__":
	__SCREAMING_SNAKE_CASE  =			argparse.ArgumentParser()
	parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
	__SCREAMING_SNAKE_CASE  =			parser.parse_args()

	check_dummies(args.fix_and_overwrite)




