"""simple docstring"""







import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class 							__snake_case(					_lowerCAmelCase				,	unittest.TestCase	):


    '''simple docstring'''





    _UpperCAmelCase       =			KandinskyPriorPipeline
    _UpperCAmelCase       =			["prompt"]
    _UpperCAmelCase       =			["prompt", "negative_prompt"]
    _UpperCAmelCase       =			[
        "num_images_per_prompt",
        "generator",
        "num_inference_steps",
        "latents",
        "negative_prompt",
        "guidance_scale",
        "output_type",
        "return_dict",
    ]
    _UpperCAmelCase       =			False
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return 32
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return 32
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return self.time_input_dim
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return self.time_input_dim * 4
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         return 100
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'	)
         return tokenizer
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         torch.manual_seed(0	)
         __A					:					Optional[Any]								=		CLIPTextConfig(
             bos_token_id=0					,       eos_token_id=2					,       hidden_size=self.text_embedder_hidden_size					,       projection_dim=self.text_embedder_hidden_size					,       intermediate_size=37					,       layer_norm_eps=1e-05					,       num_attention_heads=4					,       num_hidden_layers=5					,       pad_token_id=1					,       vocab_size=1000					,       )
         return CLIPTextModelWithProjection(lowerCAmelCase__	)
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         torch.manual_seed(0	)

         __A					:					List[Any]								=		{
             '''num_attention_heads''': 2,
             '''attention_head_dim''': 12,
             '''embedding_dim''': self.text_embedder_hidden_size,
             '''num_layers''': 1,
         }

         __A					:					str								=		PriorTransformer(**lowerCAmelCase__	)
         # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
         __A					:					str								=		nn.Parameter(torch.ones(model.clip_std.shape	)	)
         return model
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         torch.manual_seed(0	)
         __A					:					Tuple								=		CLIPVisionConfig(
             hidden_size=self.text_embedder_hidden_size					,       image_size=224					,       projection_dim=self.text_embedder_hidden_size					,       intermediate_size=37					,       num_attention_heads=4					,       num_channels=3					,       num_hidden_layers=5					,       patch_size=14					,       )

         __A					:					int								=		CLIPVisionModelWithProjection(lowerCAmelCase__	)
         return model
    @property
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		CLIPImageProcessor(
             crop_size=224					,       do_center_crop=lowerCAmelCase__					,       do_normalize=lowerCAmelCase__					,       do_resize=lowerCAmelCase__					,       image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]					,       image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]					,       resample=3					,       size=224					,       )

         return image_processor
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		self.dummy_prior
         __A					:					Optional[int]								=		self.dummy_image_encoder
         __A					:					Any								=		self.dummy_text_encoder
         __A					:					Dict								=		self.dummy_tokenizer
         __A					:					int								=		self.dummy_image_processor

         __A					:					str								=		UnCLIPScheduler(
             variance_type='fixed_small_log'					,       prediction_type='sample'					,       num_train_timesteps=1000					,       clip_sample=lowerCAmelCase__					,       clip_sample_range=10.0					,       )

         __A					:					Any								=		{
             '''prior''': prior,
             '''image_encoder''': image_encoder,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
             '''scheduler''': scheduler,
             '''image_processor''': image_processor,
         }

         return components
    def 						_a							(  self					,       __lowerCamelCase					,       __lowerCamelCase=0	):




         '''simple docstring'''



         if str(lowerCAmelCase__	).startswith('mps'	):
              __A					:					Optional[int]								=		torch.manual_seed(lowerCAmelCase__	)
         else:
              __A					:					str								=		torch.Generator(device=lowerCAmelCase__	).manual_seed(lowerCAmelCase__	)
         __A					:					Union[str, Any]								=		{
             '''prompt''': '''horse''',
             '''generator''': generator,
             '''guidance_scale''': 4.0,
             '''num_inference_steps''': 2,
             '''output_type''': '''np''',
         }
         return inputs
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[str]								=		'''cpu'''

         __A					:					int								=		self.get_dummy_components()

         __A					:					Any								=		self.pipeline_class(**lowerCAmelCase__	)
         __A					:					Any								=		pipe.to(lowerCAmelCase__	)

         pipe.set_progress_bar_config(disable=lowerCAmelCase__	)

         __A					:					List[Any]								=		pipe(**self.get_dummy_inputs(lowerCAmelCase__	)	)
         __A					:					int								=		output.image_embeds

         __A					:					Optional[Any]								=		pipe(
             **self.get_dummy_inputs(lowerCAmelCase__	)					,       return_dict=lowerCAmelCase__					,       )[0]

         __A					:					Optional[int]								=		image[0, -10:]
         __A					:					List[Any]								=		image_from_tuple[0, -10:]

         assert image.shape == (1, 32)

         __A					:					Any								=		np.array(
             [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]	)

         assert np.abs(image_slice.flatten() - expected_slice	).max() < 1e-2
         assert np.abs(image_from_tuple_slice.flatten() - expected_slice	).max() < 1e-2
    @skip_mps
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Tuple								=		torch_device == '''cpu'''
         __A					:					List[Any]								=		True
         __A					:					Optional[Any]								=		False

         self._test_inference_batch_single_identical(
             test_max_difference=lowerCAmelCase__					,       relax_max_difference=lowerCAmelCase__					,       test_mean_pixel_difference=lowerCAmelCase__					,       )

    @skip_mps
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[str]								=		torch_device == '''cpu'''
         __A					:					Dict								=		False

         self._test_attention_slicing_forward_pass(
             test_max_difference=lowerCAmelCase__					,       test_mean_pixel_difference=lowerCAmelCase__					,       )










"""simple docstring"""




# This model implementation is heavily based on:

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,
    ControlNetModel,
    DDIMScheduler,
    StableDiffusionControlNetInpaintPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_controlnet import MultiControlNetModel
from diffusers.utils import floats_tensor, load_image, load_numpy, randn_tensor, slow, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
    TEXT_TO_IMAGE_IMAGE_PARAMS,
)
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
)


enable_full_determinism()




class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
				UpperCamelCase								=       frozenset({'''control_image'''}							)  # skip `image` and `mask` for now, only test for control_image
				UpperCamelCase								=       TEXT_TO_IMAGE_IMAGE_PARAMS






				def 							snake_case      (					self						:       Tuple				)      -> Any:




										'''simple docstring'''



										torch.manual_seed(0				)
										_UpperCamelCase     :   Tuple      =       UNetaDConditionModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					sample_size=3_2,					in_channels=9,					out_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),					cross_attention_dim=3_2,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Optional[Any]      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Any      =       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     :   List[str]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   List[str]      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   Dict      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   Tuple      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components






				def 							snake_case      (					self						:       Dict,					lowerCAmelCase__						:       Optional[Any],					lowerCAmelCase__						:       Optional[int]=0				)      -> Optional[int]:




										'''simple docstring'''



										if str(lowerCAmelCase__				).startswith('''mps'''				):
																_UpperCamelCase     :   str      =       torch.manual_seed(lowerCAmelCase__				)
										else:
																_UpperCamelCase     :   Any      =       torch.Generator(device=lowerCAmelCase__				).manual_seed(lowerCAmelCase__				)

										_UpperCamelCase     :   Optional[Any]      =       2
										_UpperCamelCase     :   int      =       randn_tensor(
										    (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					)
										_UpperCamelCase     :   int      =       floats_tensor((1, 3, 3_2, 3_2),					rng=random.Random(lowerCAmelCase__				)				).to(lowerCAmelCase__				)
										_UpperCamelCase     :   List[str]      =       init_image.cpu().permute(0,					2,					3,					1				)[0]

										_UpperCamelCase     :   Optional[int]      =       Image.fromarray(np.uinta(lowerCAmelCase__				)				).convert('''RGB'''				).resize((6_4, 6_4)				)
										_UpperCamelCase     :   Any      =       Image.fromarray(np.uinta(init_image + 4				)				).convert('''RGB'''				).resize((6_4, 6_4)				)

										_UpperCamelCase     :   Tuple      =       {
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										    '''image''': image,
										    '''mask_image''': mask_image,
										    '''control_image''': control_image,
										}

										return inputs






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




										'''simple docstring'''



										return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3				)






				@unittest.skipIf(
				    torch_device != '''cuda''' or not is_xformers_available(),					reason='''XFormers attention is only available with CUDA and `xformers` installed''',					)
				def 							snake_case      (					self						:       Dict				)      -> int:




										'''simple docstring'''



										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3				)






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




										'''simple docstring'''



										self._test_inference_batch_single_identical(expected_max_diff=2e-3				)




class 					_a		( _lowerCAmelCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
				UpperCamelCase								=       frozenset([]							)






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




										'''simple docstring'''



										torch.manual_seed(0				)
										_UpperCamelCase     :   List[Any]      =       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,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   Optional[int]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   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,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   List[str]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   int      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   str      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''scheduler''': scheduler,
										    '''vae''': vae,
										    '''text_encoder''': text_encoder,
										    '''tokenizer''': tokenizer,
										    '''safety_checker''': None,
										    '''feature_extractor''': None,
										}
										return components




class 					_a		( _lowerCAmelCase      ,							_lowerCAmelCase      ,							unittest.TestCase							):
				UpperCamelCase								=       StableDiffusionControlNetInpaintPipeline
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
				UpperCamelCase								=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS






				def 							snake_case      (					self						:       Any				)      -> Dict:




										'''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=9,					out_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D'''),					cross_attention_dim=3_2,					)
										torch.manual_seed(0				)

										def init_weights(lowerCAmelCase__						:       Optional[Any]				):
																if isinstance(lowerCAmelCase__,					torch.nn.Convad				):
																						torch.nn.init.normal(m.weight				)
																						m.bias.data.fill_(1.0				)

										_UpperCamelCase     :   List[Any]      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										controlneta.controlnet_down_blocks.apply(lowerCAmelCase__				)

										torch.manual_seed(0				)
										_UpperCamelCase     :   int      =       ControlNetModel(
										    block_out_channels=(3_2, 6_4),					layers_per_block=2,					in_channels=4,					down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D'''),					cross_attention_dim=3_2,					conditioning_embedding_out_channels=(1_6, 3_2),					)
										controlneta.controlnet_down_blocks.apply(lowerCAmelCase__				)

										torch.manual_seed(0				)
										_UpperCamelCase     :   Tuple      =       DDIMScheduler(
										    beta_start=0.00_085,					beta_end=0.012,					beta_schedule='''scaled_linear''',					clip_sample=lowerCAmelCase__,					set_alpha_to_one=lowerCAmelCase__,					)
										torch.manual_seed(0				)
										_UpperCamelCase     :   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     :   List[Any]      =       CLIPTextConfig(
										    bos_token_id=0,					eos_token_id=2,					hidden_size=3_2,					intermediate_size=3_7,					layer_norm_eps=1e-0_5,					num_attention_heads=4,					num_hidden_layers=5,					pad_token_id=1,					vocab_size=1_0_0_0,					)
										_UpperCamelCase     :   Any      =       CLIPTextModel(lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''				)

										_UpperCamelCase     :   str      =       MultiControlNetModel([controlneta, controlneta]				)

										_UpperCamelCase     :   str      =       {
										    '''unet''': unet,
										    '''controlnet''': controlnet,
										    '''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],					lowerCAmelCase__						:       str,					lowerCAmelCase__						:       Tuple=0				)      -> str:




										'''simple docstring'''



										if str(lowerCAmelCase__				).startswith('''mps'''				):
																_UpperCamelCase     :   List[Any]      =       torch.manual_seed(lowerCAmelCase__				)
										else:
																_UpperCamelCase     :   List[str]      =       torch.Generator(device=lowerCAmelCase__				).manual_seed(lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       2

										_UpperCamelCase     :   Union[str, Any]      =       [
										    randn_tensor(
										        (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					),
										    randn_tensor(
										        (1, 3, 3_2 * controlnet_embedder_scale_factor, 3_2 * controlnet_embedder_scale_factor),					generator=lowerCAmelCase__,					device=torch.device(lowerCAmelCase__				),					),
										]
										_UpperCamelCase     :   int      =       floats_tensor((1, 3, 3_2, 3_2),					rng=random.Random(lowerCAmelCase__				)				).to(lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       init_image.cpu().permute(0,					2,					3,					1				)[0]

										_UpperCamelCase     :   List[str]      =       Image.fromarray(np.uinta(lowerCAmelCase__				)				).convert('''RGB'''				).resize((6_4, 6_4)				)
										_UpperCamelCase     :   int      =       Image.fromarray(np.uinta(init_image + 4				)				).convert('''RGB'''				).resize((6_4, 6_4)				)

										_UpperCamelCase     :   Dict      =       {
										    '''prompt''': '''A painting of a squirrel eating a burger''',
										    '''generator''': generator,
										    '''num_inference_steps''': 2,
										    '''guidance_scale''': 6.0,
										    '''output_type''': '''numpy''',
										    '''image''': image,
										    '''mask_image''': mask_image,
										    '''control_image''': control_image,
										}

										return inputs






				def 							snake_case      (					self						:       Optional[int]				)      -> Optional[int]:




										'''simple docstring'''



										_UpperCamelCase     :   List[str]      =       self.get_dummy_components()
										_UpperCamelCase     :   Optional[int]      =       self.pipeline_class(**lowerCAmelCase__				)
										pipe.to(lowerCAmelCase__				)

										_UpperCamelCase     :   int      =       10.0
										_UpperCamelCase     :   List[Any]      =       4

										_UpperCamelCase     :   List[str]      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Union[str, Any]      =       steps
										_UpperCamelCase     :   Union[str, Any]      =       scale
										_UpperCamelCase     :   List[Any]      =       pipe(**lowerCAmelCase__				)[0]

										_UpperCamelCase     :   Dict      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   List[str]      =       steps
										_UpperCamelCase     :   Union[str, Any]      =       scale
										_UpperCamelCase     :   Union[str, Any]      =       pipe(**lowerCAmelCase__,					control_guidance_start=0.1,					control_guidance_end=0.2				)[0]

										_UpperCamelCase     :   int      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Any      =       steps
										_UpperCamelCase     :   Optional[Any]      =       scale
										_UpperCamelCase     :   Optional[int]      =       pipe(**lowerCAmelCase__,					control_guidance_start=[0.1, 0.3],					control_guidance_end=[0.2, 0.7]				)[0]

										_UpperCamelCase     :   Tuple      =       self.get_dummy_inputs(lowerCAmelCase__				)
										_UpperCamelCase     :   Tuple      =       steps
										_UpperCamelCase     :   int      =       scale
										_UpperCamelCase     :   Optional[Any]      =       pipe(**lowerCAmelCase__,					control_guidance_start=0.4,					control_guidance_end=[0.5, 0.8]				)[0]

										# make sure that all outputs are different
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3
										assert np.sum(np.abs(output_a - output_a				)				) > 1e-3






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




										'''simple docstring'''



										return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3				)






				@unittest.skipIf(
				    torch_device != '''cuda''' or not is_xformers_available(),					reason='''XFormers attention is only available with CUDA and `xformers` installed''',					)
				def 							snake_case      (					self						:       str				)      -> Union[str, Any]:




										'''simple docstring'''



										self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3				)






				def 							snake_case      (					self						:       List[str]				)      -> Tuple:




										'''simple docstring'''



										self._test_inference_batch_single_identical(expected_max_diff=2e-3				)






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




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       self.get_dummy_components()
										_UpperCamelCase     :   Union[str, Any]      =       self.pipeline_class(**lowerCAmelCase__				)
										pipe.to(lowerCAmelCase__				)
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)
										with tempfile.TemporaryDirectory() as tmpdir:
																try:
																						# save_pretrained is not implemented for Multi-ControlNet
																						pipe.save_pretrained(lowerCAmelCase__				)
																except NotImplementedError:
																						pass




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






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




										'''simple docstring'''



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






				def 							snake_case      (					self						:       Any				)      -> int:




										'''simple docstring'''



										_UpperCamelCase     :   Optional[int]      =       ControlNetModel.from_pretrained('''lllyasviel/sd-controlnet-canny'''				)

										_UpperCamelCase     :   int      =       StableDiffusionControlNetInpaintPipeline.from_pretrained(
										    '''runwayml/stable-diffusion-inpainting''',					safety_checker=lowerCAmelCase__,					controlnet=lowerCAmelCase__				)
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

										_UpperCamelCase     :   str      =       torch.Generator(device='''cpu'''				).manual_seed(0				)
										_UpperCamelCase     :   Optional[int]      =       load_image(
										    '''https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[str]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
										    '''/stable_diffusion_inpaint/input_bench_mask.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   int      =       '''pitch black hole'''

										_UpperCamelCase     :   List[Any]      =       load_image(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'''				).resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[Any]      =       pipe(
										    lowerCAmelCase__,					image=lowerCAmelCase__,					mask_image=lowerCAmelCase__,					control_image=lowerCAmelCase__,					generator=lowerCAmelCase__,					output_type='''np''',					num_inference_steps=3,					)

										_UpperCamelCase     :   Union[str, Any]      =       output.images[0]

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

										_UpperCamelCase     :   Union[str, Any]      =       load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/inpaint.npy'''				)

										assert np.abs(expected_image - image				).max() < 9e-2






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




										'''simple docstring'''



										_UpperCamelCase     :   Tuple      =       ControlNetModel.from_pretrained('''lllyasviel/control_v11p_sd15_inpaint'''				)

										_UpperCamelCase     :   Tuple      =       StableDiffusionControlNetInpaintPipeline.from_pretrained(
										    '''runwayml/stable-diffusion-v1-5''',					safety_checker=lowerCAmelCase__,					controlnet=lowerCAmelCase__				)
										_UpperCamelCase     :   int      =       DDIMScheduler.from_config(pipe.scheduler.config				)
										pipe.enable_model_cpu_offload()
										pipe.set_progress_bar_config(disable=lowerCAmelCase__				)

										_UpperCamelCase     :   Any      =       torch.Generator(device='''cpu'''				).manual_seed(3_3				)

										_UpperCamelCase     :   Union[str, Any]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png'''				)
										_UpperCamelCase     :   Optional[int]      =       init_image.resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   List[Any]      =       load_image(
										    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png'''				)
										_UpperCamelCase     :   Dict      =       mask_image.resize((5_1_2, 5_1_2)				)

										_UpperCamelCase     :   Tuple      =       '''a handsome man with ray-ban sunglasses'''

										def make_inpaint_condition(lowerCAmelCase__						:       int,					lowerCAmelCase__						:       Optional[Any]				):
																_UpperCamelCase     :   Union[str, Any]      =       np.array(image.convert('''RGB'''				)				).astype(np.floataa				) / 255.0
																_UpperCamelCase     :   Optional[int]      =       np.array(image_mask.convert('''L'''				)				).astype(np.floataa				) / 255.0

																assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
																_UpperCamelCase     :   Union[str, Any]      =       -1.0  # set as masked pixel
																_UpperCamelCase     :   Union[str, Any]      =       np.expand_dims(lowerCAmelCase__,					0				).transpose(0,					3,					1,					2				)
																_UpperCamelCase     :   List[Any]      =       torch.from_numpy(lowerCAmelCase__				)
																return image

										_UpperCamelCase     :   Any      =       make_inpaint_condition(lowerCAmelCase__,					lowerCAmelCase__				)

										_UpperCamelCase     :   Optional[int]      =       pipe(
										    lowerCAmelCase__,					image=lowerCAmelCase__,					mask_image=lowerCAmelCase__,					control_image=lowerCAmelCase__,					guidance_scale=9.0,					eta=1.0,					generator=lowerCAmelCase__,					num_inference_steps=2_0,					output_type='''np''',					)
										_UpperCamelCase     :   Union[str, Any]      =       output.images[0]

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

										_UpperCamelCase     :   List[str]      =       load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/boy_ray_ban.npy'''				)

										assert np.abs(expected_image - image				).max() < 9e-2



