from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


_lowerCamelCase    :      Dict	 =						logging.get_logger(__name__)  # pylint: disable=invalid-name

_lowerCamelCase    :      List[Any]	 =						'''
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)["depth"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline("depth-estimation")

        >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to("cuda")

        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-controlnet-depth", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to("cuda")

        >>> img = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        ...     "/kandinsky/cat.png"
        ... ).resize((768, 768))


        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to("cuda")

        >>> prompt = "A robot, 4k photo"
        >>> negative_prior_prompt = "lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature"

        >>> generator = torch.Generator(device="cuda").manual_seed(43)

        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)

        >>> images = pipe(
        ...     image=img,
        ...     strength=0.5,
        ...     image_embeds=img_emb.image_embeds,
        ...     negative_image_embeds=negative_emb.image_embeds,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save("robot_cat.png")
        ```
'''





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[Any]					,       UpperCAmelCase__   :							int					,       UpperCAmelCase__   :							Dict=8     ):
					SCREAMING_SNAKE_CASE				=				height // scale_factor**2
					if height % scale_factor**2 != 0:
										new_height += 1
					SCREAMING_SNAKE_CASE				=				width // scale_factor**2
					if width % scale_factor**2 != 0:
										new_width += 1
					return new_height * scale_factor, new_width * scale_factor





def 		__lowerCamelCase							(UpperCAmelCase__   :							List[Any]					,       UpperCAmelCase__   :							Any=5_1_2					,       UpperCAmelCase__   :							Union[str, Any]=5_1_2     ):
					SCREAMING_SNAKE_CASE				=				pil_image.resize((w, h)					,       resample=Image.BICUBIC					,       reducing_gap=1     )
					SCREAMING_SNAKE_CASE				=				np.array(pil_image.convert("RGB"     )     )
					SCREAMING_SNAKE_CASE				=				arr.astype(np.floataa     ) / 127.5 - 1
					SCREAMING_SNAKE_CASE				=				np.transpose(UpperCAmelCase__					,       [2, 0, 1]     )
					SCREAMING_SNAKE_CASE				=				torch.from_numpy(UpperCAmelCase__     ).unsqueeze(0     )
					return image


class   lowercase			(   a   ):




							def __init__(  self      :    str		,							_UpperCamelCase      :    UNetaDConditionModel		,							_UpperCamelCase      :    DDPMScheduler		,							_UpperCamelCase      :    VQModel		,							)    -> Optional[Any]:



												'''simple docstring'''

												super().__init__()

												self.register_modules(
												    unet=_UpperCamelCase		,							scheduler=_UpperCamelCase		,							movq=_UpperCamelCase		,							)
												SCREAMING_SNAKE_CASE				=				2 ** (len(self.movq.config.block_out_channels					) - 1)




							def 		__snake_case(  self      :    str		,							_UpperCamelCase      :    List[str]		,							_UpperCamelCase      :    Union[str, Any]		,							_UpperCamelCase      :    List[str]					)    -> Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				min(int(num_inference_steps * strength					)		,							_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				max(num_inference_steps - init_timestep		,							0					)
												SCREAMING_SNAKE_CASE				=				self.scheduler.timesteps[t_start:]

												return timesteps, num_inference_steps - t_start




							def 		__snake_case(  self      :    Union[str, Any]		,							_UpperCamelCase      :    Optional[Any]		,							_UpperCamelCase      :    str		,							_UpperCamelCase      :    Any		,							_UpperCamelCase      :    int		,							_UpperCamelCase      :    Union[str, Any]		,							_UpperCamelCase      :    Optional[int]		,							_UpperCamelCase      :    Union[str, Any]=None					)    -> Tuple:



												'''simple docstring'''

												if not isinstance(_UpperCamelCase		,							(torch.Tensor, PIL.Image.Image, list)					):
																	raise ValueError(
																	    F"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_UpperCamelCase					)}"					)

												SCREAMING_SNAKE_CASE				=				image.to(device=_UpperCamelCase		,							dtype=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				batch_size * num_images_per_prompt

												if image.shape[1] == 4:
																	SCREAMING_SNAKE_CASE				=				image

												else:
																	if isinstance(_UpperCamelCase		,							_UpperCamelCase					) and len(_UpperCamelCase					) != batch_size:
																						raise ValueError(
																						    F"You have passed a list of generators of length {len(_UpperCamelCase					)}, but requested an effective batch"
																						    F" size of {batch_size}. Make sure the batch size matches the length of the generators."					)

																	elif isinstance(_UpperCamelCase		,							_UpperCamelCase					):
																						SCREAMING_SNAKE_CASE				=				[
																						    self.movq.encode(image[i : i + 1]					).latent_dist.sample(generator[i]					) for i in range(_UpperCamelCase					)
																						]
																						SCREAMING_SNAKE_CASE				=				torch.cat(_UpperCamelCase		,							dim=0					)
																	else:
																						SCREAMING_SNAKE_CASE				=				self.movq.encode(_UpperCamelCase					).latent_dist.sample(_UpperCamelCase					)

																	SCREAMING_SNAKE_CASE				=				self.movq.config.scaling_factor * init_latents

												SCREAMING_SNAKE_CASE				=				torch.cat([init_latents]		,							dim=0					)

												SCREAMING_SNAKE_CASE				=				init_latents.shape
												SCREAMING_SNAKE_CASE				=				randn_tensor(_UpperCamelCase		,							generator=_UpperCamelCase		,							device=_UpperCamelCase		,							dtype=_UpperCamelCase					)

												# get latents
												SCREAMING_SNAKE_CASE				=				self.scheduler.add_noise(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				init_latents

												return latents




							def 		__snake_case(  self      :    List[str]		,							_UpperCamelCase      :    str=0					)    -> Dict:



												'''simple docstring'''

												if is_accelerate_available():
																	from accelerate import cpu_offload
												else:
																	raise ImportError("Please install accelerate via `pip install accelerate`"					)

												SCREAMING_SNAKE_CASE				=				torch.device(F"cuda:{gpu_id}"					)

												SCREAMING_SNAKE_CASE				=				[
												    self.unet,
												    self.movq,
												]
												for cpu_offloaded_model in models:
																	if cpu_offloaded_model is not None:
																						cpu_offload(_UpperCamelCase		,							_UpperCamelCase					)




							def 		__snake_case(  self      :    Tuple		,							_UpperCamelCase      :    Optional[Any]=0					)    -> Union[str, Any]:



												'''simple docstring'''

												if is_accelerate_available() and is_accelerate_version(">="		,							"0.17.0.dev0"					):
																	from accelerate import cpu_offload_with_hook
												else:
																	raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."					)

												SCREAMING_SNAKE_CASE				=				torch.device(F"cuda:{gpu_id}"					)

												if self.device.type != "cpu":
																	self.to("cpu"		,							silence_dtype_warnings=_UpperCamelCase					)
																	torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

												SCREAMING_SNAKE_CASE				=				None
												for cpu_offloaded_model in [self.unet, self.movq]:
																	SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				cpu_offload_with_hook(_UpperCamelCase		,							_UpperCamelCase		,							prev_module_hook=_UpperCamelCase					)

												# We'll offload the last model manually.
												SCREAMING_SNAKE_CASE				=				hook




							@property
							# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
							def 		__snake_case(  self      :    Any					)    -> List[Any]:



												'''simple docstring'''

												if not hasattr(self.unet		,							"_hf_hook"					):
																	return self.device
												for module in self.unet.modules():
																	if (
																	    hasattr(_UpperCamelCase		,							"_hf_hook"					)
																	    and hasattr(module._hf_hook		,							"execution_device"					)
																	    and module._hf_hook.execution_device is not None
																	):
																						return torch.device(module._hf_hook.execution_device					)
												return self.device





							@torch.no_grad()
							@replace_example_docstring(_UpperCamelCase					)
							def __call__(  self      :    Union[str, Any]		,							_UpperCamelCase      :    Union[torch.FloatTensor, List[torch.FloatTensor]]		,							_UpperCamelCase      :    Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]		,							_UpperCamelCase      :    Union[torch.FloatTensor, List[torch.FloatTensor]]		,							_UpperCamelCase      :    torch.FloatTensor		,							_UpperCamelCase      :    int = 512		,							_UpperCamelCase      :    int = 512		,							_UpperCamelCase      :    int = 100		,							_UpperCamelCase      :    float = 4.0		,							_UpperCamelCase      :    float = 0.3		,							_UpperCamelCase      :    int = 1		,							_UpperCamelCase      :    Optional[Union[torch.Generator, List[torch.Generator]]] = None		,							_UpperCamelCase      :    Optional[str] = "pil"		,							_UpperCamelCase      :    bool = True		,							)    -> Any:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				self._execution_device

												SCREAMING_SNAKE_CASE				=				guidance_scale > 1.0

												if isinstance(_UpperCamelCase		,							_UpperCamelCase					):
																	SCREAMING_SNAKE_CASE				=				torch.cat(_UpperCamelCase		,							dim=0					)
												if isinstance(_UpperCamelCase		,							_UpperCamelCase					):
																	SCREAMING_SNAKE_CASE				=				torch.cat(_UpperCamelCase		,							dim=0					)
												if isinstance(_UpperCamelCase		,							_UpperCamelCase					):
																	SCREAMING_SNAKE_CASE				=				torch.cat(_UpperCamelCase		,							dim=0					)

												SCREAMING_SNAKE_CASE				=				image_embeds.shape[0]

												if do_classifier_free_guidance:
																	SCREAMING_SNAKE_CASE				=				image_embeds.repeat_interleave(_UpperCamelCase		,							dim=0					)
																	SCREAMING_SNAKE_CASE				=				negative_image_embeds.repeat_interleave(_UpperCamelCase		,							dim=0					)
																	SCREAMING_SNAKE_CASE				=				hint.repeat_interleave(_UpperCamelCase		,							dim=0					)

												SCREAMING_SNAKE_CASE				=				torch.cat([negative_image_embeds, image_embeds]		,							dim=0					).to(dtype=self.unet.dtype		,							device=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				torch.cat([hint, hint]		,							dim=0					).to(dtype=self.unet.dtype		,							device=_UpperCamelCase					)

												if not isinstance(_UpperCamelCase		,							_UpperCamelCase					):
																	SCREAMING_SNAKE_CASE				=				[image]
												if not all(isinstance(_UpperCamelCase		,							(PIL.Image.Image, torch.Tensor)					) for i in image					):
																	raise ValueError(
																	    F"Input is in incorrect format: {[type(_UpperCamelCase					) for i in image]}. Currently, we only support  PIL image and pytorch tensor"					)

												SCREAMING_SNAKE_CASE				=				torch.cat([prepare_image(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase					) for i in image]		,							dim=0					)
												SCREAMING_SNAKE_CASE				=				image.to(dtype=image_embeds.dtype		,							device=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.movq.encode(_UpperCamelCase					)["latents"]
												SCREAMING_SNAKE_CASE				=				latents.repeat_interleave(_UpperCamelCase		,							dim=0					)
												self.scheduler.set_timesteps(_UpperCamelCase		,							device=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				self.get_timesteps(_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				timesteps[:1].repeat(batch_size * num_images_per_prompt					)
												SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				downscale_height_and_width(_UpperCamelCase		,							_UpperCamelCase		,							self.movq_scale_factor					)
												SCREAMING_SNAKE_CASE				=				self.prepare_latents(
												    _UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							image_embeds.dtype		,							_UpperCamelCase		,							_UpperCamelCase					)
												for i, t in enumerate(self.progress_bar(_UpperCamelCase					)					):
																	# expand the latents if we are doing classifier free guidance
																	SCREAMING_SNAKE_CASE				=				torch.cat([latents] * 2					) if do_classifier_free_guidance else latents

																	SCREAMING_SNAKE_CASE				=				{"image_embeds": image_embeds, "hint": hint}
																	SCREAMING_SNAKE_CASE				=				self.unet(
																	    sample=_UpperCamelCase		,							timestep=_UpperCamelCase		,							encoder_hidden_states=_UpperCamelCase		,							added_cond_kwargs=_UpperCamelCase		,							return_dict=_UpperCamelCase		,							)[0]

																	if do_classifier_free_guidance:
																						SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				noise_pred.split(latents.shape[1]		,							dim=1					)
																						SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				noise_pred.chunk(2					)
																						SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				variance_pred.chunk(2					)
																						SCREAMING_SNAKE_CASE				=				noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																						SCREAMING_SNAKE_CASE				=				torch.cat([noise_pred, variance_pred_text]		,							dim=1					)

																	if not (
																	    hasattr(self.scheduler.config		,							"variance_type"					)
																	    and self.scheduler.config.variance_type in ["learned", "learned_range"]
																	):
																						SCREAMING_SNAKE_CASE	,      SCREAMING_SNAKE_CASE				=				noise_pred.split(latents.shape[1]		,							dim=1					)

																	# compute the previous noisy sample x_t -> x_t-1

																	SCREAMING_SNAKE_CASE				=				self.scheduler.step(
																	    _UpperCamelCase		,							_UpperCamelCase		,							_UpperCamelCase		,							generator=_UpperCamelCase		,							)[0]

												# post-processing
												SCREAMING_SNAKE_CASE				=				self.movq.decode(_UpperCamelCase		,							force_not_quantize=_UpperCamelCase					)["sample"]

												if output_type not in ["pt", "np", "pil"]:
																	raise ValueError(F"Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}"					)

												if output_type in ["np", "pil"]:
																	SCREAMING_SNAKE_CASE				=				image * 0.5 + 0.5
																	SCREAMING_SNAKE_CASE				=				image.clamp(0		,							1					)
																	SCREAMING_SNAKE_CASE				=				image.cpu().permute(0		,							2		,							3		,							1					).float().numpy()

												if output_type == "pil":
																	SCREAMING_SNAKE_CASE				=				self.numpy_to_pil(_UpperCamelCase					)

												if not return_dict:
																	return (image,)

												return ImagePipelineOutput(images=_UpperCamelCase					)





import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMParallelScheduler,
    DDPMParallelScheduler,
    StableDiffusionParadigmsPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    require_torch_gpu,
)

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


enable_full_determinism()


class   lowercase			(   a ,				a ,				unittest.TestCase   ):
							lowercase__  :				Optional[Any]									=							StableDiffusionParadigmsPipeline
							lowercase__  :				Optional[Any]									=							TEXT_TO_IMAGE_PARAMS
							lowercase__  :				Union[str, Any]									=							TEXT_TO_IMAGE_BATCH_PARAMS
							lowercase__  :				int									=							TEXT_TO_IMAGE_IMAGE_PARAMS
							lowercase__  :				List[Any]									=							TEXT_TO_IMAGE_IMAGE_PARAMS




							def 		__snake_case(  self      :    Tuple					)    -> List[Any]:



												'''simple docstring'''

												torch.manual_seed(0					)
												SCREAMING_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		,							)
												SCREAMING_SNAKE_CASE				=				DDIMParallelScheduler(
												    beta_start=0.0_0_0_8_5		,							beta_end=0.0_1_2		,							beta_schedule="scaled_linear"		,							clip_sample=_UpperCamelCase		,							set_alpha_to_one=_UpperCamelCase		,							)
												torch.manual_seed(0					)
												SCREAMING_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=128		,							)
												torch.manual_seed(0					)
												SCREAMING_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=1_000		,							hidden_act="gelu"		,							projection_dim=512		,							)
												SCREAMING_SNAKE_CASE				=				CLIPTextModel(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

												SCREAMING_SNAKE_CASE				=				{
												    "unet": unet,
												    "scheduler": scheduler,
												    "vae": vae,
												    "text_encoder": text_encoder,
												    "tokenizer": tokenizer,
												    "safety_checker": None,
												    "feature_extractor": None,
												}
												return components




							def 		__snake_case(  self      :    Any		,							_UpperCamelCase      :    List[str]		,							_UpperCamelCase      :    Any=0					)    -> Optional[int]:



												'''simple docstring'''

												if str(_UpperCamelCase					).startswith("mps"					):
																	SCREAMING_SNAKE_CASE				=				torch.manual_seed(_UpperCamelCase					)
												else:
																	SCREAMING_SNAKE_CASE				=				torch.Generator(device=_UpperCamelCase					).manual_seed(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				{
												    "prompt": "a photograph of an astronaut riding a horse",
												    "generator": generator,
												    "num_inference_steps": 10,
												    "guidance_scale": 6.0,
												    "output_type": "numpy",
												    "parallel": 3,
												    "debug": True,
												}
												return inputs




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]
												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.4_7_7_3, 0.5_4_1_7, 0.4_7_2_3, 0.4_9_2_5, 0.5_6_3_1, 0.4_7_5_2, 0.5_2_4_0, 0.4_9_3_5, 0.5_0_2_3]					)

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




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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				DDPMParallelScheduler()
												torch.manual_seed(0					)
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]
												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.3_5_7_3, 0.4_4_2_0, 0.4_9_6_0, 0.4_7_9_9, 0.3_7_9_6, 0.3_8_7_9, 0.4_8_1_9, 0.4_3_6_5, 0.4_4_6_8]					)

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




							def 		__snake_case(  self      :    Tuple					)    -> int:



												'''simple docstring'''

												super().test_inference_batch_consistent(batch_sizes=[1, 2]					)




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



												'''simple docstring'''

												super().test_inference_batch_single_identical(batch_size=2		,							expected_max_diff=3e-3					)





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



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"cpu"  # ensure determinism for the device-dependent torch.Generator
												SCREAMING_SNAKE_CASE				=				self.get_dummy_components()
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline(**_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				sd_pipe.to(_UpperCamelCase					)
												sd_pipe.set_progress_bar_config(disable=_UpperCamelCase					)

												SCREAMING_SNAKE_CASE				=				self.get_dummy_inputs(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				"french fries"
												SCREAMING_SNAKE_CASE				=				sd_pipe(**_UpperCamelCase		,							negative_prompt=_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				output.images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1]

												assert image.shape == (1, 64, 64, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.4_7_7_1, 0.5_4_2_0, 0.4_6_8_3, 0.4_9_1_8, 0.5_6_3_6, 0.4_7_2_5, 0.5_2_3_0, 0.4_9_2_3, 0.5_0_1_5]					)

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



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




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



												'''simple docstring'''

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




							def 		__snake_case(  self      :    Optional[Any]		,							_UpperCamelCase      :    int=0					)    -> Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				torch.Generator(device=_UpperCamelCase					).manual_seed(_UpperCamelCase					)
												SCREAMING_SNAKE_CASE				=				{
												    "prompt": "a photograph of an astronaut riding a horse",
												    "generator": generator,
												    "num_inference_steps": 10,
												    "guidance_scale": 7.5,
												    "output_type": "numpy",
												    "parallel": 3,
												    "debug": True,
												}
												return inputs





							def 		__snake_case(  self      :    Dict					)    -> str:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE				=				"stabilityai/stable-diffusion-2-base"
												SCREAMING_SNAKE_CASE				=				DDIMParallelScheduler.from_pretrained(_UpperCamelCase		,							subfolder="scheduler"					)
												SCREAMING_SNAKE_CASE				=				StableDiffusionParadigmsPipeline.from_pretrained(_UpperCamelCase		,							scheduler=_UpperCamelCase		,							safety_checker=_UpperCamelCase					)
												pipe.to(_UpperCamelCase					)
												pipe.set_progress_bar_config(disable=_UpperCamelCase					)
												pipe.enable_attention_slicing()

												SCREAMING_SNAKE_CASE				=				self.get_inputs()
												SCREAMING_SNAKE_CASE				=				pipe(**_UpperCamelCase					).images
												SCREAMING_SNAKE_CASE				=				image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 512, 512, 3)

												SCREAMING_SNAKE_CASE				=				np.array([0.9_6_2_2, 0.9_6_0_2, 0.9_7_4_8, 0.9_5_9_1, 0.9_6_3_0, 0.9_6_9_1, 0.9_6_6_1, 0.9_6_3_1, 0.9_7_4_1]					)

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




