






import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     List[str]			,						lowerCAmelCase							:     int			,						lowerCAmelCase							:     Optional[int]=1.0)			->			str:

    """simple docstring"""







    super().__init__()

    _snake_case      :					List[Any]					=   cut_size
    _snake_case      :					List[Any]					=   cut_power


   def        UpperCamelCase_					(   self							:     List[str]			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     Any)			->			List[Any]:

    """simple docstring"""







    _snake_case      :					Optional[int]					=   pixel_values.shape[2:4]
    _snake_case      :					Optional[Any]					=   min(lowerCAmelCase			,						lowerCAmelCase)
    _snake_case      :					Optional[Any]					=   min(lowerCAmelCase			,						lowerCAmelCase			,						self.cut_size)
    _snake_case      :					Optional[int]					=   []
    for _ in range(lowerCAmelCase):
     _snake_case      :					Any					=   int(torch.rand([]) ** self.cut_power * (max_size - min_size) + min_size)
     _snake_case      :					Union[str, Any]					=   torch.randint(0			,						sideX - size + 1			,						())
     _snake_case      :					List[str]					=   torch.randint(0			,						sideY - size + 1			,						())
     _snake_case      :					List[str]					=   pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
     cutouts.append(F.adaptive_avg_poolad(lowerCAmelCase			,						self.cut_size))
    return torch.cat(lowerCAmelCase)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		List[Any]			,    SCREAMING_SNAKE_CASE__    :		int			)					->       Optional[int]:
 _snake_case      :					Dict					=   F.normalize(SCREAMING_SNAKE_CASE__			,    dim=-1			)
 _snake_case      :					Union[str, Any]					=   F.normalize(SCREAMING_SNAKE_CASE__			,    dim=-1			)
 return (x - y).norm(dim=-1			).div(2			).arcsin().pow(2			).mul(2			)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		List[str]			,    SCREAMING_SNAKE_CASE__    :		List[Any]			)					->       List[Any]:
 for param in model.parameters():
  _snake_case      :					Dict					=   value







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   def __init__(   self							:     str			,						lowerCAmelCase							:     AutoencoderKL			,						lowerCAmelCase							:     CLIPTextModel			,						lowerCAmelCase							:     CLIPModel			,						lowerCAmelCase							:     CLIPTokenizer			,						lowerCAmelCase							:     UNetaDConditionModel			,						lowerCAmelCase							:     Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler]			,						lowerCAmelCase							:     CLIPImageProcessor			,						)			->			str:

    """simple docstring"""







    super().__init__()
    self.register_modules(
        vae=lowerCAmelCase			,						text_encoder=lowerCAmelCase			,						clip_model=lowerCAmelCase			,						tokenizer=lowerCAmelCase			,						unet=lowerCAmelCase			,						scheduler=lowerCAmelCase			,						feature_extractor=lowerCAmelCase			,						)

    _snake_case      :					Dict					=   transforms.Normalize(mean=feature_extractor.image_mean			,						std=feature_extractor.image_std)
    _snake_case      :					List[str]					=   (
        feature_extractor.size
        if isinstance(feature_extractor.size			,						lowerCAmelCase)
        else feature_extractor.size["""shortest_edge"""]
    )
    _snake_case      :					Union[str, Any]					=   MakeCutouts(self.cut_out_size)

    set_requires_grad(self.text_encoder			,						lowerCAmelCase)
    set_requires_grad(self.clip_model			,						lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     int			,						lowerCAmelCase							:     Optional[Union[str, int]] = "auto")			->			List[Any]:

    """simple docstring"""







    if slice_size == "auto":
     # half the attention head size is usually a good trade-off between
     # speed and memory
     _snake_case      :					List[str]					=   self.unet.config.attention_head_dim // 2
    self.unet.set_attention_slice(lowerCAmelCase)

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

    """simple docstring"""







    self.enable_attention_slicing(lowerCAmelCase)

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

    """simple docstring"""







    set_requires_grad(self.vae			,						lowerCAmelCase)

   def        UpperCamelCase_					(   self							:     str)			->			Dict:

    """simple docstring"""







    set_requires_grad(self.vae			,						lowerCAmelCase)

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

    """simple docstring"""







    set_requires_grad(self.unet			,						lowerCAmelCase)

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

    """simple docstring"""







    set_requires_grad(self.unet			,						lowerCAmelCase)

   @torch.enable_grad()
   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     List[str]			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     List[Any]			,						lowerCAmelCase							:     List[str]			,						lowerCAmelCase							:     Optional[Any]			,						lowerCAmelCase							:     List[str]			,						lowerCAmelCase							:     str			,						lowerCAmelCase							:     Dict=True			,						)			->			List[str]:

    """simple docstring"""







    _snake_case      :					Tuple					=   latents.detach().requires_grad_()

    _snake_case      :					Tuple					=   self.scheduler.scale_model_input(lowerCAmelCase			,						lowerCAmelCase)

    # predict the noise residual
    _snake_case      :					Dict					=   self.unet(lowerCAmelCase			,						lowerCAmelCase			,						encoder_hidden_states=lowerCAmelCase).sample

    if isinstance(self.scheduler			,						(PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)):
     _snake_case      :					Optional[int]					=   self.scheduler.alphas_cumprod[timestep]
     _snake_case      :					int					=   1 - alpha_prod_t
     # compute predicted original sample from predicted noise also called
     # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
     _snake_case      :					str					=   (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

     _snake_case      :					List[str]					=   torch.sqrt(lowerCAmelCase)
     _snake_case      :					List[Any]					=   pred_original_sample * (fac) + latents * (1 - fac)
    elif isinstance(self.scheduler			,						lowerCAmelCase):
     _snake_case      :					str					=   self.scheduler.sigmas[index]
     _snake_case      :					Optional[Any]					=   latents - sigma * noise_pred
    else:
     raise ValueError(F'''scheduler type {type(self.scheduler)} not supported''')

    _snake_case      :					Tuple					=   1 / self.vae.config.scaling_factor * sample
    _snake_case      :					Union[str, Any]					=   self.vae.decode(lowerCAmelCase).sample
    _snake_case      :					Optional[Any]					=   (image / 2 + 0.5).clamp(0			,						1)

    if use_cutouts:
     _snake_case      :					Optional[int]					=   self.make_cutouts(lowerCAmelCase			,						lowerCAmelCase)
    else:
     _snake_case      :					List[Any]					=   transforms.Resize(self.cut_out_size)(lowerCAmelCase)
    _snake_case      :					Union[str, Any]					=   self.normalize(lowerCAmelCase).to(latents.dtype)

    _snake_case      :					Tuple					=   self.clip_model.get_image_features(lowerCAmelCase)
    _snake_case      :					Optional[Any]					=   image_embeddings_clip / image_embeddings_clip.norm(p=2			,						dim=-1			,						keepdim=lowerCAmelCase)

    if use_cutouts:
     _snake_case      :					int					=   spherical_dist_loss(lowerCAmelCase			,						lowerCAmelCase)
     _snake_case      :					str					=   dists.view([num_cutouts, sample.shape[0], -1])
     _snake_case      :					Union[str, Any]					=   dists.sum(2).mean(0).sum() * clip_guidance_scale
    else:
     _snake_case      :					Dict					=   spherical_dist_loss(lowerCAmelCase			,						lowerCAmelCase).mean() * clip_guidance_scale

    _snake_case      :					List[Any]					=   -torch.autograd.grad(lowerCAmelCase			,						lowerCAmelCase)[0]

    if isinstance(self.scheduler			,						lowerCAmelCase):
     _snake_case      :					str					=   latents.detach() + grads * (sigma**2)
     _snake_case      :					Optional[Any]					=   noise_pred_original
    else:
     _snake_case      :					Optional[Any]					=   noise_pred_original - torch.sqrt(lowerCAmelCase) * grads
    return noise_pred, latents


   @torch.no_grad()
   def __call__(   self							:     Optional[int]			,						lowerCAmelCase							:     Union[str, List[str]]			,						lowerCAmelCase							:     Optional[int] = 512			,						lowerCAmelCase							:     Optional[int] = 512			,						lowerCAmelCase							:     Optional[int] = 50			,						lowerCAmelCase							:     Optional[float] = 7.5			,						lowerCAmelCase							:     Optional[int] = 1			,						lowerCAmelCase							:     float = 0.0			,						lowerCAmelCase							:     Optional[float] = 100			,						lowerCAmelCase							:     Optional[Union[str, List[str]]] = None			,						lowerCAmelCase							:     Optional[int] = 4			,						lowerCAmelCase							:     Optional[bool] = True			,						lowerCAmelCase							:     Optional[torch.Generator] = None			,						lowerCAmelCase							:     Optional[torch.FloatTensor] = None			,						lowerCAmelCase							:     Optional[str] = "pil"			,						lowerCAmelCase							:     bool = True			,						)			->			Optional[Any]:

    """simple docstring"""







    if isinstance(lowerCAmelCase			,						lowerCAmelCase):
     _snake_case      :					str					=   1
    elif isinstance(lowerCAmelCase			,						lowerCAmelCase):
     _snake_case      :					List[str]					=   len(lowerCAmelCase)
    else:
     raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase)}''')

    if height % 8 != 0 or width % 8 != 0:
     raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''')

    # get prompt text embeddings
    _snake_case      :					Dict					=   self.tokenizer(
        lowerCAmelCase			,						padding="""max_length"""			,						max_length=self.tokenizer.model_max_length			,						truncation=lowerCAmelCase			,						return_tensors="""pt"""			,						)
    _snake_case      :					Optional[Any]					=   self.text_encoder(text_input.input_ids.to(self.device))[0]
    # duplicate text embeddings for each generation per prompt
    _snake_case      :					List[Any]					=   text_embeddings.repeat_interleave(lowerCAmelCase			,						dim=0)

    if clip_guidance_scale > 0:
     if clip_prompt is not None:
      _snake_case      :					Optional[Any]					=   self.tokenizer(
          lowerCAmelCase			,						padding="""max_length"""			,						max_length=self.tokenizer.model_max_length			,						truncation=lowerCAmelCase			,						return_tensors="""pt"""			,						).input_ids.to(self.device)
     else:
      _snake_case      :					Optional[Any]					=   text_input.input_ids.to(self.device)
     _snake_case      :					Optional[int]					=   self.clip_model.get_text_features(lowerCAmelCase)
     _snake_case      :					Any					=   text_embeddings_clip / text_embeddings_clip.norm(p=2			,						dim=-1			,						keepdim=lowerCAmelCase)
     # duplicate text embeddings clip for each generation per prompt
     _snake_case      :					Tuple					=   text_embeddings_clip.repeat_interleave(lowerCAmelCase			,						dim=0)

    # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
    # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
    # corresponds to doing no classifier free guidance.
    _snake_case      :					str					=   guidance_scale > 1.0
    # get unconditional embeddings for classifier free guidance
    if do_classifier_free_guidance:
     _snake_case      :					int					=   text_input.input_ids.shape[-1]
     _snake_case      :					str					=   self.tokenizer([""""""]			,						padding="""max_length"""			,						max_length=lowerCAmelCase			,						return_tensors="""pt""")
     _snake_case      :					List[str]					=   self.text_encoder(uncond_input.input_ids.to(self.device))[0]
     # duplicate unconditional embeddings for each generation per prompt
     _snake_case      :					List[Any]					=   uncond_embeddings.repeat_interleave(lowerCAmelCase			,						dim=0)

     # For classifier free guidance, we need to do two forward passes.
     # Here we concatenate the unconditional and text embeddings into a single batch
     # to avoid doing two forward passes
     _snake_case      :					Dict					=   torch.cat([uncond_embeddings, text_embeddings])

    # get the initial random noise unless the user supplied it

    # Unlike in other pipelines, latents need to be generated in the target device
    # for 1-to-1 results reproducibility with the CompVis implementation.
    # However this currently doesn't work in `mps`.
    _snake_case      :					Optional[Any]					=   (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
    _snake_case      :					Dict					=   text_embeddings.dtype
    if latents is None:
     if self.device.type == "mps":
      # randn does not work reproducibly on mps
      _snake_case      :					int					=   torch.randn(lowerCAmelCase			,						generator=lowerCAmelCase			,						device="""cpu"""			,						dtype=lowerCAmelCase).to(
          self.device)
     else:
      _snake_case      :					Tuple					=   torch.randn(lowerCAmelCase			,						generator=lowerCAmelCase			,						device=self.device			,						dtype=lowerCAmelCase)
    else:
     if latents.shape != latents_shape:
      raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''')
     _snake_case      :					int					=   latents.to(self.device)

    # set timesteps
    _snake_case      :					Optional[Any]					=   """offset""" in set(inspect.signature(self.scheduler.set_timesteps).parameters.keys())
    _snake_case      :					Any					=   {}
    if accepts_offset:
     _snake_case      :					Any					=   1

    self.scheduler.set_timesteps(lowerCAmelCase			,						**lowerCAmelCase)

    # Some schedulers like PNDM have timesteps as arrays
    # It's more optimized to move all timesteps to correct device beforehand
    _snake_case      :					Tuple					=   self.scheduler.timesteps.to(self.device)

    # scale the initial noise by the standard deviation required by the scheduler
    _snake_case      :					Optional[Any]					=   latents * self.scheduler.init_noise_sigma

    # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
    # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
    # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
    # and should be between [0, 1]
    _snake_case      :					Tuple					=   """eta""" in set(inspect.signature(self.scheduler.step).parameters.keys())
    _snake_case      :					Any					=   {}
    if accepts_eta:
     _snake_case      :					Union[str, Any]					=   eta

    # check if the scheduler accepts generator
    _snake_case      :					str					=   """generator""" in set(inspect.signature(self.scheduler.step).parameters.keys())
    if accepts_generator:
     _snake_case      :					str					=   generator

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

     # predict the noise residual
     _snake_case      :					List[str]					=   self.unet(lowerCAmelCase			,						lowerCAmelCase			,						encoder_hidden_states=lowerCAmelCase).sample

     # perform classifier free guidance
     if do_classifier_free_guidance:
      _snake_case      :					Union[str, Any]					=   noise_pred.chunk(2)
      _snake_case      :					Tuple					=   noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

     # perform clip guidance
     if clip_guidance_scale > 0:
      _snake_case      :					Union[str, Any]					=   (
          text_embeddings.chunk(2)[1] if do_classifier_free_guidance else text_embeddings
      )
      _snake_case      :					List[Any]					=   self.cond_fn(
          lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						)

     # compute the previous noisy sample x_t -> x_t-1
     _snake_case      :					List[Any]					=   self.scheduler.step(lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						**lowerCAmelCase).prev_sample

    # scale and decode the image latents with vae
    _snake_case      :					Union[str, Any]					=   1 / self.vae.config.scaling_factor * latents
    _snake_case      :					Union[str, Any]					=   self.vae.decode(lowerCAmelCase).sample

    _snake_case      :					Optional[Any]					=   (image / 2 + 0.5).clamp(0			,						1)
    _snake_case      :					Optional[Any]					=   image.cpu().permute(0			,						2			,						3			,						1).numpy()

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

    if not return_dict:
     return (image, None)

    return StableDiffusionPipelineOutput(images=lowerCAmelCase			,						nsfw_content_detected=lowerCAmelCase)





import unittest

import numpy as np
import torch

from diffusers import DDPMPipeline, DDPMScheduler, UNetaDModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow, torch_device


enable_full_determinism()







class 						snake_case  (		unittest.TestCase					):



   '''simple docstring'''






   @property
   def        UpperCamelCase_					(   self							:     Union[str, Any])			->			int:

    """simple docstring"""







    torch.manual_seed(0)
    _snake_case      :					Any					=   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        UpperCamelCase_					(   self							:     List[Any])			->			Optional[Any]:

    """simple docstring"""







    _snake_case      :					List[str]					=   """cpu"""
    _snake_case      :					Union[str, Any]					=   self.dummy_uncond_unet
    _snake_case      :					Union[str, Any]					=   DDPMScheduler()

    _snake_case      :					Dict					=   DDPMPipeline(unet=lowerCAmelCase			,						scheduler=lowerCAmelCase)
    ddpm.to(lowerCAmelCase)
    ddpm.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Optional[Any]					=   torch.Generator(device=lowerCAmelCase).manual_seed(0)
    _snake_case      :					Optional[int]					=   ddpm(generator=lowerCAmelCase			,						num_inference_steps=2			,						output_type="""numpy""").images

    _snake_case      :					Optional[int]					=   torch.Generator(device=lowerCAmelCase).manual_seed(0)
    _snake_case      :					Union[str, Any]					=   ddpm(generator=lowerCAmelCase			,						num_inference_steps=2			,						output_type="""numpy"""			,						return_dict=lowerCAmelCase)[0]

    _snake_case      :					Any					=   image[0, -3:, -3:, -1]
    _snake_case      :					str					=   image_from_tuple[0, -3:, -3:, -1]

    assert image.shape == (1, 32, 32, 3)
    _snake_case      :					Optional[int]					=   np.array(
        [9.956E-01, 5.785E-01, 4.675E-01, 9.930E-01, 0.0, 1.000, 1.199E-03, 2.648E-04, 5.101E-04])

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


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

    """simple docstring"""







    _snake_case      :					int					=   self.dummy_uncond_unet
    _snake_case      :					int					=   DDPMScheduler(prediction_type="""sample""")

    _snake_case      :					Union[str, Any]					=   DDPMPipeline(unet=lowerCAmelCase			,						scheduler=lowerCAmelCase)
    ddpm.to(lowerCAmelCase)
    ddpm.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Tuple					=   torch.manual_seed(0)
    _snake_case      :					Union[str, Any]					=   ddpm(generator=lowerCAmelCase			,						num_inference_steps=2			,						output_type="""numpy""").images

    _snake_case      :					Any					=   torch.manual_seed(0)
    _snake_case      :					Dict					=   ddpm(generator=lowerCAmelCase			,						num_inference_steps=2			,						output_type="""numpy""")[0]

    _snake_case      :					str					=   image[0, -3:, -3:, -1]
    _snake_case      :					List[Any]					=   image_eps[0, -3:, -3:, -1]

    assert image.shape == (1, 32, 32, 3)
    _snake_case      :					Any					=   1E-2 if torch_device != """mps""" else 3E-2
    assert np.abs(image_slice.flatten() - image_eps_slice.flatten()).max() < tolerance







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



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Dict)			->			Optional[Any]:

    """simple docstring"""







    _snake_case      :					Dict					=   """google/ddpm-cifar10-32"""

    _snake_case      :					List[Any]					=   UNetaDModel.from_pretrained(lowerCAmelCase)
    _snake_case      :					Optional[Any]					=   DDPMScheduler.from_pretrained(lowerCAmelCase)

    _snake_case      :					Dict					=   DDPMPipeline(unet=lowerCAmelCase			,						scheduler=lowerCAmelCase)
    ddpm.to(lowerCAmelCase)
    ddpm.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Optional[Any]					=   torch.manual_seed(0)
    _snake_case      :					Any					=   ddpm(generator=lowerCAmelCase			,						output_type="""numpy""").images

    _snake_case      :					Optional[Any]					=   image[0, -3:, -3:, -1]

    assert image.shape == (1, 32, 32, 3)
    _snake_case      :					Union[str, Any]					=   np.array([0.4_200, 0.3_588, 0.1_939, 0.3_847, 0.3_382, 0.2_647, 0.4_155, 0.3_582, 0.3_385])
    assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
