



"""simple docstring"""
import gc
import random
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    floats_tensor,
    load_image,
    load_numpy,
    require_torch_gpu,
    skip_mps,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class     a		(     UpperCAmelCase__		,					UpperCAmelCase__		,					UpperCAmelCase__		,					unittest.TestCase				):
  UpperCamelCase		: List[str]     =    StableUnCLIPImgaImgPipeline
  UpperCamelCase		: Dict     =    TEXT_GUIDED_IMAGE_VARIATION_PARAMS
  UpperCamelCase		: Dict     =    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  UpperCamelCase		: List[str]     =    frozenset(
      []				)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
  UpperCamelCase		: Optional[Any]     =    frozenset([]				)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Dict   	=32
     SCREAMING_SNAKE_CASE_:       Tuple   	=embedder_hidden_size

     # image encoding components

     SCREAMING_SNAKE_CASE_:       Optional[int]   	=CLIPImageProcessor(crop_size=32				,						size=32						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       List[str]   	=CLIPVisionModelWithProjection(
         CLIPVisionConfig(
             hidden_size=lowerCamelCase_				,						projection_dim=lowerCamelCase_				,						num_hidden_layers=5				,						num_attention_heads=4				,						image_size=32				,						intermediate_size=37				,						patch_size=1				,						)						)

     # regular denoising components

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       List[str]   	=StableUnCLIPImageNormalizer(embedding_dim=lowerCamelCase_						)
     SCREAMING_SNAKE_CASE_:       str   	=DDPMScheduler(beta_schedule="""squaredcos_cap_v2"""						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       Optional[int]   	=CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       List[str]   	=CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0				,						eos_token_id=2				,						hidden_size=lowerCamelCase_				,						projection_dim=32				,						intermediate_size=37				,						layer_norm_eps=1E-05				,						num_attention_heads=4				,						num_hidden_layers=5				,						pad_token_id=1				,						vocab_size=1000				,						)						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       Any   	=UNetaDConditionModel(
         sample_size=32				,						in_channels=4				,						out_channels=4				,						down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")				,						up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")				,						block_out_channels=(32, 64)				,						attention_head_dim=(2, 4)				,						class_embed_type="""projection"""				,						projection_class_embeddings_input_dim=embedder_projection_dim * 2				,						cross_attention_dim=lowerCamelCase_				,						layers_per_block=1				,						upcast_attention=lowerCamelCase_				,						use_linear_projection=lowerCamelCase_				,						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       Optional[int]   	=DDIMScheduler(
         beta_schedule="""scaled_linear"""				,						beta_start=0.0_0_0_8_5				,						beta_end=0.0_1_2				,						prediction_type="""v_prediction"""				,						set_alpha_to_one=lowerCamelCase_				,						steps_offset=1				,						)

     torch.manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       Any   	=AutoencoderKL()

     SCREAMING_SNAKE_CASE_:       str   	={
         # image encoding components
         """feature_extractor""": feature_extractor,
         """image_encoder""": image_encoder.eval(),
         # image noising components
         """image_normalizer""": image_normalizer.eval(),
         """image_noising_scheduler""": image_noising_scheduler,
         # regular denoising components
         """tokenizer""": tokenizer,
         """text_encoder""": text_encoder.eval(),
         """unet""": unet.eval(),
         """scheduler""": scheduler,
         """vae""": vae.eval(),
     }

     return components



  def 		lowerCamelCase__				(  self       :    Tuple				,						lowerCAmelCase       :    str				,						lowerCAmelCase       :    Optional[int]=0				,						lowerCAmelCase       :    Any=True						)   ->    str:


     '''simple docstring'''




     if str(lowerCamelCase_						).startswith("""mps"""						):
        SCREAMING_SNAKE_CASE_:       List[str]   	=torch.manual_seed(lowerCamelCase_						)
     else:
        SCREAMING_SNAKE_CASE_:       List[str]   	=torch.Generator(device=lowerCamelCase_						).manual_seed(lowerCamelCase_						)

     SCREAMING_SNAKE_CASE_:       Any   	=floats_tensor((1, 3, 32, 32)				,						rng=random.Random(lowerCamelCase_						)						).to(lowerCamelCase_						)

     if pil_image:
        SCREAMING_SNAKE_CASE_:       int   	=input_image * 0.5 + 0.5
        SCREAMING_SNAKE_CASE_:       Tuple   	=input_image.clamp(0				,						1						)
        SCREAMING_SNAKE_CASE_:       List[str]   	=input_image.cpu().permute(0				,						2				,						3				,						1						).float().numpy()
        SCREAMING_SNAKE_CASE_:       Tuple   	=DiffusionPipeline.numpy_to_pil(lowerCamelCase_						)[0]

     return {
         "prompt": "An anime racoon running a marathon",
         "image": input_image,
         "generator": generator,
         "num_inference_steps": 2,
         "output_type": "np",
     }



  @skip_mps
  def 		lowerCamelCase__				(  self       :    Tuple						)   ->    Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       str   	="""cpu"""  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE_:       Tuple   	=self.get_dummy_components()
     SCREAMING_SNAKE_CASE_:       List[str]   	=StableUnCLIPImgaImgPipeline(**lowerCamelCase_						)
     SCREAMING_SNAKE_CASE_:       Any   	=sd_pipe.to(lowerCamelCase_						)
     sd_pipe.set_progress_bar_config(disable=lowerCamelCase_						)

     SCREAMING_SNAKE_CASE_:       List[str]   	=self.get_dummy_inputs(lowerCamelCase_						)
     inputs.update({"""image_embeds""": None}						)
     SCREAMING_SNAKE_CASE_:       Tuple   	=sd_pipe(**lowerCamelCase_						).images
     SCREAMING_SNAKE_CASE_:       Optional[int]   	=image[0, -3:, -3:, -1]

     assert image.shape == (1, 32, 32, 3)
     SCREAMING_SNAKE_CASE_:       Any   	=np.array([0.3_8_7_2, 0.7_2_2_4, 0.5_6_0_1, 0.4_7_4_1, 0.6_8_7_2, 0.5_8_1_4, 0.4_6_3_6, 0.3_8_6_7, 0.5_0_7_8]						)

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



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Dict   	=torch_device in ["""cpu""", """mps"""]

     self._test_attention_slicing_forward_pass(test_max_difference=lowerCamelCase_						)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Optional[int]   	=torch_device in ["""cpu""", """mps"""]

     self._test_inference_batch_single_identical(test_max_difference=lowerCamelCase_						)





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


     '''simple docstring'''




     self._test_xformers_attention_forwardGenerator_pass(test_max_difference=lowerCamelCase_						)







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



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


     '''simple docstring'''




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



  def 		lowerCamelCase__				(  self       :    int						)   ->    List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       List[str]   	=load_image(
         """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"""						)

     SCREAMING_SNAKE_CASE_:       str   	=load_numpy(
         """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy"""						)

     SCREAMING_SNAKE_CASE_:       str   	=StableUnCLIPImgaImgPipeline.from_pretrained(
         """fusing/stable-unclip-2-1-l-img2img"""				,						torch_dtype=torch.floataa						)
     pipe.to(lowerCamelCase_						)
     pipe.set_progress_bar_config(disable=lowerCamelCase_						)
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE_:       Union[str, Any]   	=torch.Generator(device="""cpu"""						).manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       int   	=pipe(lowerCamelCase_				,						"""anime turle"""				,						generator=lowerCamelCase_				,						output_type="""np"""						)

     SCREAMING_SNAKE_CASE_:       List[Any]   	=output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(lowerCamelCase_				,						lowerCamelCase_						)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Any   	=load_image(
         """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"""						)

     SCREAMING_SNAKE_CASE_:       Tuple   	=load_numpy(
         """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy"""						)

     SCREAMING_SNAKE_CASE_:       int   	=StableUnCLIPImgaImgPipeline.from_pretrained(
         """fusing/stable-unclip-2-1-h-img2img"""				,						torch_dtype=torch.floataa						)
     pipe.to(lowerCamelCase_						)
     pipe.set_progress_bar_config(disable=lowerCamelCase_						)
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE_:       Optional[Any]   	=torch.Generator(device="""cpu"""						).manual_seed(0						)
     SCREAMING_SNAKE_CASE_:       Optional[Any]   	=pipe(lowerCamelCase_				,						"""anime turle"""				,						generator=lowerCamelCase_				,						output_type="""np"""						)

     SCREAMING_SNAKE_CASE_:       List[Any]   	=output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(lowerCamelCase_				,						lowerCamelCase_						)





  def 		lowerCamelCase__				(  self       :    Tuple						)   ->    Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_:       Dict   	=load_image(
         """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png"""						)

     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

     SCREAMING_SNAKE_CASE_:       Tuple   	=StableUnCLIPImgaImgPipeline.from_pretrained(
         """fusing/stable-unclip-2-1-h-img2img"""				,						torch_dtype=torch.floataa						)
     SCREAMING_SNAKE_CASE_:       int   	=pipe.to(lowerCamelCase_						)
     pipe.set_progress_bar_config(disable=lowerCamelCase_						)
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE_:       Optional[Any]   	=pipe(
         lowerCamelCase_				,						"""anime turtle"""				,						num_inference_steps=2				,						output_type="""np"""				,						)

     SCREAMING_SNAKE_CASE_:       List[str]   	=torch.cuda.max_memory_allocated()
     # make sure that less than 7 GB is allocated
     assert mem_bytes < 7 * 10**9








# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate



@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class 	_lowercase							(   lowerCAmelCase	):





	"""simple docstring"""
	__A							=							42
	__A							=							None






def     a(      A       :    Optional[Any] ,     A       :    Any=0.999 ,     A       :    Dict="cosine" ,     )		->       Optional[int]:
					"""simple docstring"""





					if alpha_transform_type == "cosine":

										def alpha_bar_fn(A       :    Optional[int]       ):
															return math.cos((t + 0.008) / 1.008 * math.pi / 2       ) ** 2

					elif alpha_transform_type == "exp":

										def alpha_bar_fn(A       :    Any       ):
															return math.exp(t * -12.0       )

					else:
										raise ValueError(f'''Unsupported alpha_tranform_type: {alpha_transform_type}'''       )

					a					     =   []
					for i in range(A       ):
										a					     =   i / num_diffusion_timesteps
										a					     =   (i + 1) / num_diffusion_timesteps
										betas.append(min(1 - alpha_bar_fn(A       ) / alpha_bar_fn(A       ) ,     A       )       )
					return torch.tensor(A ,     dtype=torch.floataa       )







class 	_lowercase							(   lowerCAmelCase,      lowerCAmelCase	):





	"""simple docstring"""
	__A							=							1




	@register_to_config
	def __init__(self		,       lowerCamelCase_ = 1000		,       lowerCamelCase_ = 0.0001		,       lowerCamelCase_ = 0.02		,       lowerCamelCase_ = "linear"		,       lowerCamelCase_ = None		,       lowerCamelCase_ = True		,       lowerCamelCase_ = True		,       lowerCamelCase_ = 0		,       lowerCamelCase_ = "epsilon"		,       lowerCamelCase_ = 1.0		,       **lowerCamelCase_		,       ):
						"""simple docstring"""

						if kwargs.get("set_alpha_to_one"		,       lowerCamelCase_		) is not None:
											a					     =   (
											    "The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
											)
											deprecate("set_alpha_to_one"		,       "1.0.0"		,       lowerCamelCase_		,       standard_warn=lowerCamelCase_		)
											a					     =   kwargs["set_alpha_to_one"]
						if trained_betas is not None:
											a					     =   torch.tensor(lowerCamelCase_		,       dtype=torch.floataa		)
						elif beta_schedule == "linear":
											a					     =   torch.linspace(lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       dtype=torch.floataa		)
						elif beta_schedule == "scaled_linear":
											# this schedule is very specific to the latent diffusion model.
											a					     =   (
											    torch.linspace(beta_start**0.5		,       beta_end**0.5		,       lowerCamelCase_		,       dtype=torch.floataa		) ** 2
											)
						elif beta_schedule == "squaredcos_cap_v2":
											# Glide cosine schedule
											a					     =   betas_for_alpha_bar(lowerCamelCase_		)
						else:
											raise NotImplementedError(F'''{beta_schedule} does is not implemented for {self.__class__}'''		)

						a					     =   1.0 - self.betas
						a					     =   torch.cumprod(self.alphas		,       dim=0		)

						# At every step in inverted ddim, we are looking into the next alphas_cumprod
						# For the final step, there is no next alphas_cumprod, and the index is out of bounds
						# `set_alpha_to_zero` decides whether we set this parameter simply to zero
						# in this case, self.step() just output the predicted noise
						# or whether we use the final alpha of the "non-previous" one.
						a					     =   torch.tensor(0.0		) if set_alpha_to_zero else self.alphas_cumprod[-1]

						# standard deviation of the initial noise distribution
						a					     =   1.0

						# setable values
						a					     =   None
						a					     =   torch.from_numpy(np.arange(0		,       lowerCamelCase_		).copy().astype(np.intaa		)		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_ = None		):
						"""simple docstring"""

						return sample




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_ = None		):
						"""simple docstring"""

						if num_inference_steps > self.config.num_train_timesteps:
											raise ValueError(
											    F'''`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:'''
											    F''' {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle'''
											    F''' maximal {self.config.num_train_timesteps} timesteps.'''		)

						a					     =   num_inference_steps
						a					     =   self.config.num_train_timesteps // self.num_inference_steps
						# creates integer timesteps by multiplying by ratio
						# casting to int to avoid issues when num_inference_step is power of 3
						a					     =   (np.arange(0		,       lowerCamelCase_		) * step_ratio).round().copy().astype(np.intaa		)
						a					     =   torch.from_numpy(lowerCamelCase_		).to(lowerCamelCase_		)
						self.timesteps += self.config.steps_offset




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_ = 0.0		,       lowerCamelCase_ = False		,       lowerCamelCase_ = None		,       lowerCamelCase_ = True		,       ):
						"""simple docstring"""

						a					     =   timestep + self.config.num_train_timesteps // self.num_inference_steps

						# 2. compute alphas, betas
						# change original implementation to exactly match noise levels for analogous forward process
						a					     =   self.alphas_cumprod[timestep]
						a					     =   (
						    self.alphas_cumprod[prev_timestep]
						    if prev_timestep < self.config.num_train_timesteps
						    else self.final_alpha_cumprod
						)

						a					     =   1 - alpha_prod_t

						# 3. compute predicted original sample from predicted noise also called
						# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						if self.config.prediction_type == "epsilon":
											a					     =   (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
											a					     =   model_output
						elif self.config.prediction_type == "sample":
											a					     =   model_output
											a					     =   (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
						elif self.config.prediction_type == "v_prediction":
											a					     =   (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
											a					     =   (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
						else:
											raise ValueError(
											    F'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or'''
											    " `v_prediction`"		)

						# 4. Clip or threshold "predicted x_0"
						if self.config.clip_sample:
											a					     =   pred_original_sample.clamp(
											    -self.config.clip_sample_range		,       self.config.clip_sample_range		)

						# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						a					     =   (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon

						# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
						a					     =   alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction

						if not return_dict:
											return (prev_sample, pred_original_sample)
						return DDIMSchedulerOutput(prev_sample=lowerCamelCase_		,       pred_original_sample=lowerCamelCase_		)




	def __len__(self		):
						"""simple docstring"""

						return self.config.num_train_timesteps
