




"""simple docstring"""




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				:     int					=				logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCAmelCase				:     Any					=				"""
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
        >>> from diffusers.utils import load_image
        >>> import torch

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

        >>> prompt = \"A red cartoon frog, 4k\"
        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)

        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16
        ... )
        >>> pipe.to(\"cuda\")

        >>> init_image = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/frog.png\"
        ... )

        >>> image = pipe(
        ...     image=init_image,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ...     strength=0.2,
        ... ).images

        >>> image[0].save(\"red_frog.png\")
        ```
"""



def        a__					(							snake_case__			,					snake_case__			,					snake_case__=8							)		->   Union[str, Any]:
			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



def        a__					(							snake_case__			,					snake_case__=5_12			,					snake_case__=5_12							)		->   str:
			lowerCamelCase      =   pil_image.resize((w, h)			,					resample=Image.BICUBIC			,					reducing_gap=1							)
			lowerCamelCase      =   np.array(pil_image.convert("""RGB"""							)							)
			lowerCamelCase      =   arr.astype(np.floataa							) / 127.5 - 1
			lowerCamelCase      =   np.transpose(snake_case__			,					[2, 0, 1]							)
			lowerCamelCase      =   torch.from_numpy(snake_case__							).unsqueeze(0							)
			return image






class        __magic_name__				(			UpperCAmelCase__							):






				'''simple docstring'''





				def __init__(			self						,					_a						,					_a						,					_a						,					):





							"""simple docstring"""
							super().__init__()

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





				def   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a					):





							"""simple docstring"""
							# get the original timestep using init_timestep
							lowerCamelCase      =   min(int(num_inference_steps * strength					)						,					_a					)

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

							return timesteps, num_inference_steps - t_start





				def   _lowerCAmelCase							(			self						,					_a						,					_a						,					_a						,					_a						,					_a						,					_a						,					_a=None					):





							"""simple docstring"""
							if not isinstance(_a						,					(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(_a					)}'					)

							lowerCamelCase      =   image.to(device=_a						,					dtype=_a					)

							lowerCamelCase      =   batch_size * num_images_per_prompt

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

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

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

										lowerCamelCase      =   self.movq.config.scaling_factor * init_latents

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

							lowerCamelCase      =   init_latents.shape
							lowerCamelCase      =   randn_tensor(_a						,					generator=_a						,					device=_a						,					dtype=_a					)

							# get latents
							lowerCamelCase      =   self.scheduler.add_noise(_a						,					_a						,					_a					)

							lowerCamelCase      =   init_latents

							return latents





				def   _lowerCAmelCase							(			self						,					_a=0					):





							"""simple docstring"""
							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(_a						,					_a					)





				def   _lowerCAmelCase							(			self						,					_a=0					):





							"""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."""					)

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

							if self.device.type != "cpu":
										self.to("""cpu"""						,					silence_dtype_warnings=_a					)
										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(_a						,					_a						,					prev_module_hook=_a					)

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





				@property
				# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							if not hasattr(self.unet						,					"""_hf_hook"""					):
										return self.device
							for module in self.unet.modules():
										if (
										    hasattr(_a						,					"""_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(_a					)
				def __call__(			self						,					_a						,					_a						,					_a						,					_a = 512						,					_a = 512						,					_a = 100						,					_a = 4.0						,					_a = 0.3						,					_a = 1						,					_a = None						,					_a = "pil"						,					_a = True						,					):





							"""simple docstring"""
							lowerCamelCase      =   self._execution_device

							lowerCamelCase      =   guidance_scale > 1.0

							if isinstance(_a						,					_a					):
										lowerCamelCase      =   torch.cat(_a						,					dim=0					)
							lowerCamelCase      =   image_embeds.shape[0]
							if isinstance(_a						,					_a					):
										lowerCamelCase      =   torch.cat(_a						,					dim=0					)

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

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

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

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

							lowerCamelCase      =   self.movq.encode(_a					)["""latents"""]
							lowerCamelCase      =   latents.repeat_interleave(_a						,					dim=0					)
							self.scheduler.set_timesteps(_a						,					device=_a					)
							lowerCamelCase ,  lowerCamelCase      =   self.get_timesteps(_a						,					_a						,					_a					)
							lowerCamelCase      =   timesteps[:1].repeat(batch_size * num_images_per_prompt					)
							lowerCamelCase ,  lowerCamelCase      =   downscale_height_and_width(_a						,					_a						,					self.movq_scale_factor					)
							lowerCamelCase      =   self.prepare_latents(
							    _a						,					_a						,					_a						,					_a						,					image_embeds.dtype						,					_a						,					_a					)
							for i, t in enumerate(self.progress_bar(_a					)					):
										# 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=_a						,					timestep=_a						,					encoder_hidden_states=_a						,					added_cond_kwargs=_a						,					return_dict=_a						,					)[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(
										    _a						,					_a						,					_a						,					generator=_a						,					)[0]

							# post-processing
							lowerCamelCase      =   self.movq.decode(_a						,					force_not_quantize=_a					)["""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(_a					)

							if not return_dict:
										return (image,)

							return ImagePipelineOutput(images=_a					)









"""simple docstring"""




import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class        __magic_name__				(			UpperCAmelCase__		,   unittest.TestCase							):






				'''simple docstring'''
				__UpperCamelCase         =		DiTPipeline
				__UpperCamelCase         =		CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
				__UpperCamelCase         =		PipelineTesterMixin.required_optional_params - {
				    "latents",
				    "num_images_per_prompt",
				    "callback",
				    "callback_steps",
				}
				__UpperCamelCase         =		CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
				__UpperCamelCase         =		False





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							torch.manual_seed(0					)
							lowerCamelCase      =   TransformeraDModel(
							    sample_size=16						,					num_layers=2						,					patch_size=4						,					attention_head_dim=8						,					num_attention_heads=2						,					in_channels=4						,					out_channels=8						,					attention_bias=_a						,					activation_fn="""gelu-approximate"""						,					num_embeds_ada_norm=1_000						,					norm_type="""ada_norm_zero"""						,					norm_elementwise_affine=_a						,					)
							lowerCamelCase      =   AutoencoderKL()
							lowerCamelCase      =   DDIMScheduler()
							lowerCamelCase      =   {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
							return components





				def   _lowerCAmelCase							(			self						,					_a						,					_a=0					):





							"""simple docstring"""
							if str(_a					).startswith("""mps"""					):
										lowerCamelCase      =   torch.manual_seed(_a					)
							else:
										lowerCamelCase      =   torch.Generator(device=_a					).manual_seed(_a					)
							lowerCamelCase      =   {
							    """class_labels""": [1],
							    """generator""": generator,
							    """num_inference_steps""": 2,
							    """output_type""": """numpy""",
							}
							return inputs





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   """cpu"""

							lowerCamelCase      =   self.get_dummy_components()
							lowerCamelCase      =   self.pipeline_class(**_a					)
							pipe.to(_a					)
							pipe.set_progress_bar_config(disable=_a					)

							lowerCamelCase      =   self.get_dummy_inputs(_a					)
							lowerCamelCase      =   pipe(**_a					).images
							lowerCamelCase      =   image[0, -3:, -3:, -1]

							self.assertEqual(image.shape						,					(1, 16, 16, 3)					)
							lowerCamelCase      =   np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457]					)
							lowerCamelCase      =   np.abs(image_slice.flatten() - expected_slice					).max()
							self.assertLessEqual(_a						,					1e-3					)





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							self._test_inference_batch_single_identical(relax_max_difference=_a						,					expected_max_diff=1e-3					)





				@unittest.skipIf(
				    torch_device != """cuda""" or not is_xformers_available()						,					reason="""XFormers attention is only available with CUDA and `xformers` installed"""						,					)
				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3					)






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






				'''simple docstring'''





				def   _lowerCAmelCase							(			self					):





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





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   torch.manual_seed(0					)

							lowerCamelCase      =   DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256"""					)
							pipe.to("""cuda"""					)

							lowerCamelCase      =   ["""vase""", """umbrella""", """white shark""", """white wolf"""]
							lowerCamelCase      =   pipe.get_label_ids(_a					)

							lowerCamelCase      =   pipe(_a						,					generator=_a						,					num_inference_steps=40						,					output_type="""np"""					).images

							for word, image in zip(_a						,					_a					):
										lowerCamelCase      =   load_numpy(
										    f'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy'					)
										assert np.abs((expected_image - image).max()					) < 1e-2





				def   _lowerCAmelCase							(			self					):





							"""simple docstring"""
							lowerCamelCase      =   DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512"""					)
							lowerCamelCase      =   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config					)
							pipe.to("""cuda"""					)

							lowerCamelCase      =   ["""vase""", """umbrella"""]
							lowerCamelCase      =   pipe.get_label_ids(_a					)

							lowerCamelCase      =   torch.manual_seed(0					)
							lowerCamelCase      =   pipe(_a						,					generator=_a						,					num_inference_steps=25						,					output_type="""np"""					).images

							for word, image in zip(_a						,					_a					):
										lowerCamelCase      =   load_numpy(
										    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
										    f'/dit/{word}_512.npy'					)

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



