


'''simple docstring'''







import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







class A__	(						unittest.TestCase				):






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




             '''simple docstring'''
             # clean up the VRAM after each test
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()






      @property
      def __UpperCAmelCase	(			self      :str     )	-> List[str]:




             '''simple docstring'''
             _a   :			int					 =1
             _a   :			Optional[int]					 =3
             _a   :			Any					 =(3_2, 3_2)

             _a   :			Any					 =floats_tensor((batch_size, num_channels) + sizes					,						rng=random.Random(0     )     ).to(SCREAMING_SNAKE_CASE     )
             return image






      @property
      def __UpperCAmelCase	(			self      :List[str]     )	-> Any:




             '''simple docstring'''
             torch.manual_seed(0     )
             _a   :			List[str]					 =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					,						)
             return model






      @property
      def __UpperCAmelCase	(			self      :Dict     )	-> Union[str, Any]:




             '''simple docstring'''
             torch.manual_seed(0     )
             _a   :			Optional[int]					 =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					,						)
             return model






      @property
      def __UpperCAmelCase	(			self      :str     )	-> Optional[int]:




             '''simple docstring'''
             torch.manual_seed(0     )
             _a   :			Optional[Any]					 =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					,						)
             return CLIPTextModel(SCREAMING_SNAKE_CASE     )






      @property
      def __UpperCAmelCase	(			self      :Union[str, Any]     )	-> List[Any]:




             '''simple docstring'''
             def extract(*SCREAMING_SNAKE_CASE      :Optional[int]					,						**SCREAMING_SNAKE_CASE      :Optional[int]     ):







                    class A__	:






                          def __init__(			self      :List[Any]     )	-> int:




                                 '''simple docstring'''
                                 _a   :			List[str]					 =torch.ones([0]     )






                          def __UpperCAmelCase	(			self      :int					,						SCREAMING_SNAKE_CASE      :Dict     )	-> str:




                                 '''simple docstring'''
                                 self.pixel_values.to(SCREAMING_SNAKE_CASE     )
                                 return self

                    return Out()

             return extract






      def __UpperCAmelCase	(			self      :Tuple     )	-> Optional[Any]:




             '''simple docstring'''
             _a   :			Dict					 ="""cpu"""  # ensure determinism for the device-dependent torch.Generator
             _a   :			str					 =self.dummy_cond_unet
             _a   :			Optional[int]					 =DDIMScheduler(
                 beta_start=0.00_085					,						beta_end=0.012					,						beta_schedule="""scaled_linear"""					,						clip_sample=SCREAMING_SNAKE_CASE					,						set_alpha_to_one=SCREAMING_SNAKE_CASE					,						)

             _a   :			str					 =self.dummy_vae
             _a   :			Tuple					 =self.dummy_text_encoder
             _a   :			int					 =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )

             # make sure here that pndm scheduler skips prk
             _a   :			Tuple					 =StableDiffusionPipeline(
                 unet=SCREAMING_SNAKE_CASE					,						scheduler=SCREAMING_SNAKE_CASE					,						vae=SCREAMING_SNAKE_CASE					,						text_encoder=SCREAMING_SNAKE_CASE					,						tokenizer=SCREAMING_SNAKE_CASE					,						safety_checker=SCREAMING_SNAKE_CASE					,						feature_extractor=self.dummy_extractor					,						)
             _a   :			Tuple					 =sd_pipe.to(SCREAMING_SNAKE_CASE     )
             sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Any					 ="""A painting of a squirrel eating a burger"""

             _a   :			Optional[Any]					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(0     )
             _a   :			Dict					 =sd_pipe([prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=6.0					,						num_inference_steps=2					,						output_type="""np"""     )
             _a   :			Optional[int]					 =output.images

             _a   :			str					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(0     )
             _a   :			str					 =sd_pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=6.0					,						num_inference_steps=2					,						output_type="""np"""					,						return_dict=SCREAMING_SNAKE_CASE					,						)[0]

             _a   :			Dict					 =image[0, -3:, -3:, -1]
             _a   :			int					 =image_from_tuple[0, -3:, -3:, -1]

             assert image.shape == (1, 6_4, 6_4, 3)
             _a   :			List[str]					 =np.array([0.5_753, 0.6_114, 0.5_001, 0.5_034, 0.5_470, 0.4_729, 0.4_971, 0.4_867, 0.4_867]     )

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






      def __UpperCAmelCase	(			self      :int     )	-> Tuple:




             '''simple docstring'''
             _a   :			str					 ="""cpu"""  # ensure determinism for the device-dependent torch.Generator
             _a   :			List[Any]					 =self.dummy_cond_unet
             _a   :			List[Any]					 =PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE     )
             _a   :			List[str]					 =self.dummy_vae
             _a   :			Tuple					 =self.dummy_text_encoder
             _a   :			Tuple					 =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )

             # make sure here that pndm scheduler skips prk
             _a   :			Any					 =StableDiffusionPipeline(
                 unet=SCREAMING_SNAKE_CASE					,						scheduler=SCREAMING_SNAKE_CASE					,						vae=SCREAMING_SNAKE_CASE					,						text_encoder=SCREAMING_SNAKE_CASE					,						tokenizer=SCREAMING_SNAKE_CASE					,						safety_checker=SCREAMING_SNAKE_CASE					,						feature_extractor=self.dummy_extractor					,						)
             _a   :			List[Any]					 =sd_pipe.to(SCREAMING_SNAKE_CASE     )
             sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Optional[Any]					 ="""A painting of a squirrel eating a burger"""
             _a   :			List[str]					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(0     )
             _a   :			Optional[int]					 =sd_pipe([prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=6.0					,						num_inference_steps=2					,						output_type="""np"""     )

             _a   :			Union[str, Any]					 =output.images

             _a   :			List[str]					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(0     )
             _a   :			Optional[int]					 =sd_pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=6.0					,						num_inference_steps=2					,						output_type="""np"""					,						return_dict=SCREAMING_SNAKE_CASE					,						)[0]

             _a   :			Union[str, Any]					 =image[0, -3:, -3:, -1]
             _a   :			Tuple					 =image_from_tuple[0, -3:, -3:, -1]

             assert image.shape == (1, 6_4, 6_4, 3)
             _a   :			Union[str, Any]					 =np.array([0.5_122, 0.5_712, 0.4_825, 0.5_053, 0.5_646, 0.4_769, 0.5_179, 0.4_894, 0.4_994]     )

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






      def __UpperCAmelCase	(			self      :str     )	-> str:




             '''simple docstring'''
             _a   :			Dict					 =StableDiffusionPipeline.from_pretrained(
                 """hf-internal-testing/tiny-stable-diffusion-lms-pipe"""					,						safety_checker=SCREAMING_SNAKE_CASE     )
             assert isinstance(SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE     )
             assert isinstance(pipe.scheduler					,						SCREAMING_SNAKE_CASE     )
             assert pipe.safety_checker is None

             _a   :			Tuple					 =pipe("""example prompt"""					,						num_inference_steps=2     ).images[0]
             assert image is not None

             # check that there's no error when saving a pipeline with one of the models being None
             with tempfile.TemporaryDirectory() as tmpdirname:
                    pipe.save_pretrained(SCREAMING_SNAKE_CASE     )
                    _a   :			List[Any]					 =StableDiffusionPipeline.from_pretrained(SCREAMING_SNAKE_CASE     )

             # sanity check that the pipeline still works
             assert pipe.safety_checker is None
             _a   :			str					 =pipe("""example prompt"""					,						num_inference_steps=2     ).images[0]
             assert image is not None






      @unittest.skipIf(torch_device != """cuda"""					,						"""This test requires a GPU"""     )
      def __UpperCAmelCase	(			self      :Optional[Any]     )	-> Optional[int]:




             '''simple docstring'''
             _a   :			Optional[int]					 =self.dummy_cond_unet
             _a   :			Tuple					 =PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE     )
             _a   :			int					 =self.dummy_vae
             _a   :			Tuple					 =self.dummy_text_encoder
             _a   :			Any					 =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )

             # put models in fp16
             _a   :			str					 =unet.half()
             _a   :			Optional[int]					 =vae.half()
             _a   :			Optional[Any]					 =bert.half()

             # make sure here that pndm scheduler skips prk
             _a   :			List[str]					 =StableDiffusionPipeline(
                 unet=SCREAMING_SNAKE_CASE					,						scheduler=SCREAMING_SNAKE_CASE					,						vae=SCREAMING_SNAKE_CASE					,						text_encoder=SCREAMING_SNAKE_CASE					,						tokenizer=SCREAMING_SNAKE_CASE					,						safety_checker=SCREAMING_SNAKE_CASE					,						feature_extractor=self.dummy_extractor					,						)
             _a   :			Tuple					 =sd_pipe.to(SCREAMING_SNAKE_CASE     )
             sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Optional[int]					 ="""A painting of a squirrel eating a burger"""
             _a   :			str					 =sd_pipe([prompt]					,						num_inference_steps=2					,						output_type="""np"""     ).images

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







@nightly
@require_torch_gpu
class A__	(						unittest.TestCase				):






      def __UpperCAmelCase	(			self      :Any     )	-> Dict:




             '''simple docstring'''
             # clean up the VRAM after each test
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()






      def __UpperCAmelCase	(			self      :str     )	-> Any:




             '''simple docstring'''
             _a   :			Union[str, Any]					 ="""cuda"""
             _a   :			str					 =StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""     )
             _a   :			int					 =pipe.to(SCREAMING_SNAKE_CASE     )
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Any					 ="""a photo of a cat"""
             _a   :			List[Any]					 ={
                 """editing_prompt""": ["""sunglasses"""],
                 """reverse_editing_direction""": [False],
                 """edit_warmup_steps""": 1_0,
                 """edit_guidance_scale""": 6,
                 """edit_threshold""": 0.95,
                 """edit_momentum_scale""": 0.5,
                 """edit_mom_beta""": 0.6,
             }

             _a   :			List[Any]					 =3
             _a   :			Union[str, Any]					 =7

             # no sega enabled
             _a   :			int					 =torch.Generator(SCREAMING_SNAKE_CASE     )
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			List[str]					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						)

             _a   :			str					 =output.images
             _a   :			int					 =image[0, -3:, -3:, -1]
             _a   :			List[Any]					 =[
                 0.34_673_113,
                 0.38_492_733,
                 0.37_597_352,
                 0.34_086_335,
                 0.35_650_748,
                 0.35_579_205,
                 0.3_384_763,
                 0.34_340_236,
                 0.3_573_271,
             ]

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

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

             # with sega enabled
             # generator = torch.manual_seed(seed)
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			List[str]					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						**SCREAMING_SNAKE_CASE					,						)

             _a   :			Tuple					 =output.images
             _a   :			Optional[int]					 =image[0, -3:, -3:, -1]
             _a   :			List[str]					 =[
                 0.41_887_826,
                 0.37_728_766,
                 0.30_138_272,
                 0.41_416_335,
                 0.41_664_985,
                 0.36_283_392,
                 0.36_191_246,
                 0.43_364_465,
                 0.43_001_732,
             ]

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

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






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




             '''simple docstring'''
             _a   :			List[Any]					 ="""cuda"""
             _a   :			Any					 =StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""     )
             _a   :			List[Any]					 =pipe.to(SCREAMING_SNAKE_CASE     )
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			int					 ="""an image of a crowded boulevard, realistic, 4k"""
             _a   :			str					 ={
                 """editing_prompt""": """crowd, crowded, people""",
                 """reverse_editing_direction""": True,
                 """edit_warmup_steps""": 1_0,
                 """edit_guidance_scale""": 8.3,
                 """edit_threshold""": 0.9,
                 """edit_momentum_scale""": 0.5,
                 """edit_mom_beta""": 0.6,
             }

             _a   :			Optional[Any]					 =9
             _a   :			Tuple					 =7

             # no sega enabled
             _a   :			int					 =torch.Generator(SCREAMING_SNAKE_CASE     )
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Optional[int]					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						)

             _a   :			List[Any]					 =output.images
             _a   :			List[str]					 =image[0, -3:, -3:, -1]
             _a   :			Tuple					 =[
                 0.43_497_998,
                 0.91_814_065,
                 0.7_540_739,
                 0.55_580_205,
                 0.8_467_265,
                 0.5_389_691,
                 0.62_574_506,
                 0.58_897_763,
                 0.50_926_757,
             ]

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

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

             # with sega enabled
             # generator = torch.manual_seed(seed)
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Any					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						**SCREAMING_SNAKE_CASE					,						)

             _a   :			Optional[Any]					 =output.images
             _a   :			Any					 =image[0, -3:, -3:, -1]
             _a   :			Any					 =[
                 0.3_089_719,
                 0.30_500_144,
                 0.29_016_042,
                 0.30_630_964,
                 0.325_687,
                 0.29_419_225,
                 0.2_908_091,
                 0.28_723_598,
                 0.27_696_294,
             ]

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

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






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




             '''simple docstring'''
             _a   :			str					 ="""cuda"""
             _a   :			Optional[Any]					 =StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""     )
             _a   :			Tuple					 =pipe.to(SCREAMING_SNAKE_CASE     )
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Optional[int]					 ="""a castle next to a river"""
             _a   :			int					 ={
                 """editing_prompt""": ["""boat on a river, boat""", """monet, impression, sunrise"""],
                 """reverse_editing_direction""": False,
                 """edit_warmup_steps""": [1_5, 1_8],
                 """edit_guidance_scale""": 6,
                 """edit_threshold""": [0.9, 0.8],
                 """edit_momentum_scale""": 0.5,
                 """edit_mom_beta""": 0.6,
             }

             _a   :			Optional[Any]					 =4_8
             _a   :			Optional[int]					 =7

             # no sega enabled
             _a   :			Any					 =torch.Generator(SCREAMING_SNAKE_CASE     )
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Dict					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						)

             _a   :			Optional[int]					 =output.images
             _a   :			List[str]					 =image[0, -3:, -3:, -1]
             _a   :			Dict					 =[
                 0.75_163_555,
                 0.76_037_145,
                 0.61_785,
                 0.9_189_673,
                 0.8_627_701,
                 0.85_189_694,
                 0.8_512_813,
                 0.87_012_076,
                 0.8_312_857,
             ]

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

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

             # with sega enabled
             # generator = torch.manual_seed(seed)
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Optional[int]					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						**SCREAMING_SNAKE_CASE					,						)

             _a   :			Dict					 =output.images
             _a   :			str					 =image[0, -3:, -3:, -1]
             _a   :			List[str]					 =[
                 0.73_553_365,
                 0.7_537_271,
                 0.74_341_905,
                 0.66_480_356,
                 0.6_472_925,
                 0.63_039_416,
                 0.64_812_905,
                 0.6_749_717,
                 0.6_517_102,
             ]

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

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






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




             '''simple docstring'''
             _a   :			int					 ="""cuda"""
             _a   :			Dict					 =StableDiffusionPipeline.from_pretrained("""runwayml/stable-diffusion-v1-5"""					,						torch_dtype=torch.floataa     )
             _a   :			Tuple					 =pipe.to(SCREAMING_SNAKE_CASE     )
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			int					 ="""a photo of a cat"""
             _a   :			Union[str, Any]					 ={
                 """editing_prompt""": ["""sunglasses"""],
                 """reverse_editing_direction""": [False],
                 """edit_warmup_steps""": 1_0,
                 """edit_guidance_scale""": 6,
                 """edit_threshold""": 0.95,
                 """edit_momentum_scale""": 0.5,
                 """edit_mom_beta""": 0.6,
             }

             _a   :			Optional[Any]					 =3
             _a   :			List[str]					 =7

             # no sega enabled
             _a   :			Optional[Any]					 =torch.Generator(SCREAMING_SNAKE_CASE     )
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Any					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						)

             _a   :			Any					 =output.images
             _a   :			int					 =image[0, -3:, -3:, -1]
             _a   :			Optional[int]					 =[
                 0.34_887_695,
                 0.3_876_953,
                 0.375,
                 0.34_423_828,
                 0.3_581_543,
                 0.35_717_773,
                 0.3_383_789,
                 0.34_570_312,
                 0.359_375,
             ]

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

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

             # with sega enabled
             # generator = torch.manual_seed(seed)
             generator.manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			Any					 =pipe(
                 [prompt]					,						generator=SCREAMING_SNAKE_CASE					,						guidance_scale=SCREAMING_SNAKE_CASE					,						num_inference_steps=5_0					,						output_type="""np"""					,						width=5_1_2					,						height=5_1_2					,						**SCREAMING_SNAKE_CASE					,						)

             _a   :			Any					 =output.images
             _a   :			List[Any]					 =image[0, -3:, -3:, -1]
             _a   :			List[str]					 =[
                 0.42_285_156,
                 0.36_914_062,
                 0.29_077_148,
                 0.42_041_016,
                 0.41_918_945,
                 0.35_498_047,
                 0.3_618_164,
                 0.4_423_828,
                 0.43_115_234,
             ]

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

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






'''simple docstring'''







import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()







class A__	(						UpperCAmelCase__			,					unittest.TestCase				):
      __UpperCamelCase	:  str     	=							RePaintPipeline
      __UpperCamelCase	:  Dict     	=							IMAGE_INPAINTING_PARAMS - {"width", "height", "guidance_scale"}
      __UpperCamelCase	:  List[str]     	=							PipelineTesterMixin.required_optional_params - {
          "latents",
          "num_images_per_prompt",
          "callback",
          "callback_steps",
      }
      __UpperCamelCase	:  List[Any]     	=							IMAGE_INPAINTING_BATCH_PARAMS
      __UpperCamelCase	:  Tuple     	=							False






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




             '''simple docstring'''
             torch.manual_seed(0     )
             torch.manual_seed(0     )
             _a   :			Tuple					 =UNetaDModel(
                 block_out_channels=(3_2, 6_4)					,						layers_per_block=2					,						sample_size=3_2					,						in_channels=3					,						out_channels=3					,						down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")					,						up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")					,						)
             _a   :			Any					 =RePaintScheduler()
             _a   :			Optional[Any]					 ={"""unet""": unet, """scheduler""": scheduler}
             return components






      def __UpperCAmelCase	(			self      :List[Any]					,						SCREAMING_SNAKE_CASE      :str					,						SCREAMING_SNAKE_CASE      :Optional[Any]=0     )	-> Any:




             '''simple docstring'''
             if str(SCREAMING_SNAKE_CASE     ).startswith("""mps"""     ):
                    _a   :			Optional[Any]					 =torch.manual_seed(SCREAMING_SNAKE_CASE     )
             else:
                    _a   :			Any					 =torch.Generator(device=SCREAMING_SNAKE_CASE     ).manual_seed(SCREAMING_SNAKE_CASE     )
             _a   :			int					 =np.random.RandomState(SCREAMING_SNAKE_CASE     ).standard_normal((1, 3, 3_2, 3_2)     )
             _a   :			Union[str, Any]					 =torch.from_numpy(SCREAMING_SNAKE_CASE     ).to(device=SCREAMING_SNAKE_CASE					,						dtype=torch.floataa     )
             _a   :			List[Any]					 =(image > 0).to(device=SCREAMING_SNAKE_CASE					,						dtype=torch.floataa     )
             _a   :			str					 ={
                 """image""": image,
                 """mask_image""": mask,
                 """generator""": generator,
                 """num_inference_steps""": 5,
                 """eta""": 0.0,
                 """jump_length""": 2,
                 """jump_n_sample""": 2,
                 """output_type""": """numpy""",
             }
             return inputs






      def __UpperCAmelCase	(			self      :Dict     )	-> Dict:




             '''simple docstring'''
             _a   :			Tuple					 ="""cpu"""  # ensure determinism for the device-dependent torch.Generator
             _a   :			Tuple					 =self.get_dummy_components()
             _a   :			str					 =RePaintPipeline(**SCREAMING_SNAKE_CASE     )
             _a   :			int					 =sd_pipe.to(SCREAMING_SNAKE_CASE     )
             sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )

             _a   :			Optional[int]					 =self.get_dummy_inputs(SCREAMING_SNAKE_CASE     )
             _a   :			Optional[Any]					 =sd_pipe(**SCREAMING_SNAKE_CASE     ).images
             _a   :			Any					 =image[0, -3:, -3:, -1]

             assert image.shape == (1, 3_2, 3_2, 3)
             _a   :			str					 =np.array([1.0_000, 0.5_426, 0.5_497, 0.2_200, 1.0_000, 1.0_000, 0.5_623, 1.0_000, 0.6_274]     )

             assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-3






      @skip_mps
      def __UpperCAmelCase	(			self      :Union[str, Any]     )	-> Optional[int]:




             '''simple docstring'''
             return super().test_save_load_local()






      @unittest.skip("""non-deterministic pipeline"""     )
      def __UpperCAmelCase	(			self      :Tuple     )	-> int:




             '''simple docstring'''
             return super().test_inference_batch_single_identical()






      @skip_mps
      def __UpperCAmelCase	(			self      :Any     )	-> Tuple:




             '''simple docstring'''
             return super().test_dict_tuple_outputs_equivalent()






      @skip_mps
      def __UpperCAmelCase	(			self      :str     )	-> Optional[Any]:




             '''simple docstring'''
             return super().test_save_load_optional_components()






      @skip_mps
      def __UpperCAmelCase	(			self      :Dict     )	-> List[str]:




             '''simple docstring'''
             return super().test_attention_slicing_forward_pass()







@nightly
@require_torch_gpu
class A__	(						unittest.TestCase				):






      def __UpperCAmelCase	(			self      :Tuple     )	-> Optional[int]:




             '''simple docstring'''
             super().tearDown()
             gc.collect()
             torch.cuda.empty_cache()






      def __UpperCAmelCase	(			self      :str     )	-> int:




             '''simple docstring'''
             _a   :			Optional[int]					 =load_image(
                 """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"""
                 """repaint/celeba_hq_256.png"""     )
             _a   :			Optional[Any]					 =load_image(
                 """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"""     )
             _a   :			Union[str, Any]					 =load_numpy(
                 """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/"""
                 """repaint/celeba_hq_256_result.npy"""     )

             _a   :			str					 ="""google/ddpm-ema-celebahq-256"""
             _a   :			Union[str, Any]					 =UNetaDModel.from_pretrained(SCREAMING_SNAKE_CASE     )
             _a   :			Dict					 =RePaintScheduler.from_pretrained(SCREAMING_SNAKE_CASE     )

             _a   :			str					 =RePaintPipeline(unet=SCREAMING_SNAKE_CASE					,						scheduler=SCREAMING_SNAKE_CASE     ).to(SCREAMING_SNAKE_CASE     )
             repaint.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE     )
             repaint.enable_attention_slicing()

             _a   :			Dict					 =torch.manual_seed(0     )
             _a   :			Any					 =repaint(
                 SCREAMING_SNAKE_CASE					,						SCREAMING_SNAKE_CASE					,						num_inference_steps=2_5_0					,						eta=0.0					,						jump_length=1_0					,						jump_n_sample=1_0					,						generator=SCREAMING_SNAKE_CASE					,						output_type="""np"""					,						)
             _a   :			Any					 =output.images[0]

             assert image.shape == (2_5_6, 2_5_6, 3)
             assert np.abs(expected_image - image     ).mean() < 1e-2


