




"""simple docstring"""







from typing import List, Optional, Union

import torch

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,
)


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

a      =							'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n        >>> pipe_prior.to("cuda")\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n        >>> pipe.to("cuda")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save("cat.png")\n        ```\n'





def 							lowercase					(snake_case__   : Dict      ,       snake_case__   : str      ,       snake_case__   : Dict=8 )     ->  int:


				'''simple docstring'''






				lowerCAmelCase  =				height // scale_factor**2
				if height % scale_factor**2 != 0:
								new_height += 1
				lowerCAmelCase  =				width // scale_factor**2
				if width % scale_factor**2 != 0:
								new_width += 1
				return new_height * scale_factor, new_width * scale_factor






class       SCREAMING_SNAKE_CASE__					(					_a					):


						def __init__(							self				:			Optional[int]						,						lowerCAmelCase				:			UNetaDConditionModel						,						lowerCAmelCase				:			DDPMScheduler						,						lowerCAmelCase				:			VQModel						,						):
										super().__init__()

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


						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			List[str]						,						lowerCAmelCase				:			Union[str, Any]						,						lowerCAmelCase				:			str						,						lowerCAmelCase				:			List[Any]						,						lowerCAmelCase				:			Optional[Any]						,						lowerCAmelCase				:			Optional[Any]					):
										if latents is None:
														lowerCAmelCase  =				randn_tensor(lowerCAmelCase						,						generator=lowerCAmelCase						,						device=lowerCAmelCase						,						dtype=lowerCAmelCase					)
										else:
														if latents.shape != shape:
																		raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''					)
														lowerCAmelCase  =				latents.to(lowerCAmelCase					)

										lowerCAmelCase  =				latents * scheduler.init_noise_sigma
										return latents


						def   __lowercase (							self				:			Dict						,						lowerCAmelCase				:			Optional[int]=0					):
										if is_accelerate_available():
														from accelerate import cpu_offload
										else:
														raise ImportError("""Please install accelerate via `pip install accelerate`"""					)

										lowerCAmelCase  =				torch.device(f'''cuda:{gpu_id}'''					)

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


						def   __lowercase (							self				:			Optional[int]						,						lowerCAmelCase				:			Optional[int]=0					):
										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."""					)

										lowerCAmelCase  =				torch.device(f'''cuda:{gpu_id}'''					)

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

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

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


						@property
						# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
						def   __lowercase (							self				:			int					):
										if not hasattr(self.unet						,						"""_hf_hook"""					):
														return self.device
										for module in self.unet.modules():
														if (
														    hasattr(lowerCAmelCase						,						"""_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(lowerCAmelCase					)
						def __call__(							self				:			str						,						lowerCAmelCase				:			Union[torch.FloatTensor, List[torch.FloatTensor]]						,						lowerCAmelCase				:			Union[torch.FloatTensor, List[torch.FloatTensor]]						,						lowerCAmelCase				:			int = 512						,						lowerCAmelCase				:			int = 512						,						lowerCAmelCase				:			int = 100						,						lowerCAmelCase				:			float = 4.0						,						lowerCAmelCase				:			int = 1						,						lowerCAmelCase				:			Optional[Union[torch.Generator, List[torch.Generator]]] = None						,						lowerCAmelCase				:			Optional[torch.FloatTensor] = None						,						lowerCAmelCase				:			Optional[str] = "pil"						,						lowerCAmelCase				:			bool = True						,						):
										lowerCAmelCase  =				self._execution_device

										lowerCAmelCase  =				guidance_scale > 1.0

										if isinstance(lowerCAmelCase						,						lowerCAmelCase					):
														lowerCAmelCase  =				torch.cat(lowerCAmelCase						,						dim=0					)
										lowerCAmelCase  =				image_embeds.shape[0] * num_images_per_prompt
										if isinstance(lowerCAmelCase						,						lowerCAmelCase					):
														lowerCAmelCase  =				torch.cat(lowerCAmelCase						,						dim=0					)

										if do_classifier_free_guidance:
														lowerCAmelCase  =				image_embeds.repeat_interleave(lowerCAmelCase						,						dim=0					)
														lowerCAmelCase  =				negative_image_embeds.repeat_interleave(lowerCAmelCase						,						dim=0					)

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

										self.scheduler.set_timesteps(lowerCAmelCase						,						device=lowerCAmelCase					)
										lowerCAmelCase  =				self.scheduler.timesteps

										lowerCAmelCase  =				self.unet.config.in_channels

										lowerCAmelCase ,						lowerCAmelCase  =				downscale_height_and_width(lowerCAmelCase						,						lowerCAmelCase						,						self.movq_scale_factor					)

										# create initial latent
										lowerCAmelCase  =				self.prepare_latents(
										    (batch_size, num_channels_latents, height, width)						,						image_embeds.dtype						,						lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase						,						self.scheduler						,						)

										for i, t in enumerate(self.progress_bar(lowerCAmelCase					)					):
														# expand the latents if we are doing classifier free guidance
														lowerCAmelCase  =				torch.cat([latents] * 2					) if do_classifier_free_guidance else latents

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

														if do_classifier_free_guidance:
																		lowerCAmelCase ,						lowerCAmelCase  =				noise_pred.split(latents.shape[1]						,						dim=1					)
																		lowerCAmelCase ,						lowerCAmelCase  =				noise_pred.chunk(2					)
																		lowerCAmelCase ,						lowerCAmelCase  =				variance_pred.chunk(2					)
																		lowerCAmelCase  =				noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
																		lowerCAmelCase  =				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"]
														):
																		lowerCAmelCase ,						lowerCAmelCase  =				noise_pred.split(latents.shape[1]						,						dim=1					)

														# compute the previous noisy sample x_t -> x_t-1
														lowerCAmelCase  =				self.scheduler.step(
														    lowerCAmelCase						,						lowerCAmelCase						,						lowerCAmelCase						,						generator=lowerCAmelCase						,						)[0]
										# post-processing
										lowerCAmelCase  =				self.movq.decode(lowerCAmelCase						,						force_not_quantize=lowerCAmelCase					)["""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"]:
														lowerCAmelCase  =				image * 0.5 + 0.5
														lowerCAmelCase  =				image.clamp(0						,						1					)
														lowerCAmelCase  =				image.cpu().permute(0						,						2						,						3						,						1					).float().numpy()

										if output_type == "pil":
														lowerCAmelCase  =				self.numpy_to_pil(lowerCAmelCase					)

										if not return_dict:
														return (image,)

										return ImagePipelineOutput(images=lowerCAmelCase					)











"""simple docstring"""







import unittest

import numpy as np
import torch

from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()






class       SCREAMING_SNAKE_CASE__					(					unittest.TestCase					):


						@property
						def   __lowercase (							self				:			Any					):
										torch.manual_seed(0					)
										lowerCAmelCase  =				UNetaDModel(
										    block_out_channels=(32, 64)						,						layers_per_block=2						,						sample_size=32						,						in_channels=3						,						out_channels=3						,						down_block_types=("""DownBlock2D""", """AttnDownBlock2D""")						,						up_block_types=("""AttnUpBlock2D""", """UpBlock2D""")						,						)
										return model




						def   __lowercase (							self				:			Optional[int]					):
										lowerCAmelCase  =				self.dummy_uncond_unet
										lowerCAmelCase  =				KarrasVeScheduler()

										lowerCAmelCase  =				KarrasVePipeline(unet=lowerCAmelCase						,						scheduler=lowerCAmelCase					)
										pipe.to(lowerCAmelCase					)
										pipe.set_progress_bar_config(disable=lowerCAmelCase					)

										lowerCAmelCase  =				torch.manual_seed(0					)
										lowerCAmelCase  =				pipe(num_inference_steps=2						,						generator=lowerCAmelCase						,						output_type="""numpy"""					).images

										lowerCAmelCase  =				torch.manual_seed(0					)
										lowerCAmelCase  =				pipe(num_inference_steps=2						,						generator=lowerCAmelCase						,						output_type="""numpy"""						,						return_dict=lowerCAmelCase					)[0]

										lowerCAmelCase  =				image[0, -3:, -3:, -1]
										lowerCAmelCase  =				image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 32, 32, 3)
										lowerCAmelCase  =				np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0]					)

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






@slow
@require_torch
class       SCREAMING_SNAKE_CASE__					(					unittest.TestCase					):


						def   __lowercase (							self				:			str					):
										lowerCAmelCase  =				"""google/ncsnpp-celebahq-256"""
										lowerCAmelCase  =				UNetaDModel.from_pretrained(lowerCAmelCase					)
										lowerCAmelCase  =				KarrasVeScheduler()

										lowerCAmelCase  =				KarrasVePipeline(unet=lowerCAmelCase						,						scheduler=lowerCAmelCase					)
										pipe.to(lowerCAmelCase					)
										pipe.set_progress_bar_config(disable=lowerCAmelCase					)

										lowerCAmelCase  =				torch.manual_seed(0					)
										lowerCAmelCase  =				pipe(num_inference_steps=20						,						generator=lowerCAmelCase						,						output_type="""numpy"""					).images

										lowerCAmelCase  =				image[0, -3:, -3:, -1]
										assert image.shape == (1, 256, 256, 3)
										lowerCAmelCase  =				np.array([0.578, 0.5811, 0.5924, 0.5809, 0.587, 0.5886, 0.5861, 0.5802, 0.586]					)

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





