


"""simple docstring"""


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    EulerAncestralDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionModelEditingPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

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


enable_full_determinism()
@skip_mps
class snake_case   (	_UpperCamelCase  ,					_UpperCamelCase  ,					_UpperCamelCase  ,					unittest.TestCase):
		__UpperCamelCase							     =      StableDiffusionModelEditingPipeline
		__UpperCamelCase							     =      TEXT_TO_IMAGE_PARAMS
		__UpperCamelCase							     =      TEXT_TO_IMAGE_BATCH_PARAMS
		__UpperCamelCase							     =      TEXT_TO_IMAGE_IMAGE_PARAMS
		__UpperCamelCase							     =      TEXT_TO_IMAGE_IMAGE_PARAMS







		def 			a_			(       self   :							Tuple		)							->    Any:





						'''simple docstring'''







						torch.manual_seed(0		)
						_A       	=      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     , )
						_A       	=      DDIMScheduler()
						torch.manual_seed(0		)
						_A       	=      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     , )
						torch.manual_seed(0		)
						_A       	=      CLIPTextConfig(
						    bos_token_id=0     , eos_token_id=2     , hidden_size=32     , intermediate_size=37     , layer_norm_eps=1E-0_5     , num_attention_heads=4     , num_hidden_layers=5     , pad_token_id=1     , vocab_size=10_00     , )
						_A       	=      CLIPTextModel(a__		)
						_A       	=      CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"		)

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







		def 			a_			(       self   :							Union[str, Any]     , a__   :							Optional[int]     , a__   :							Dict=0		)							->    List[str]:





						'''simple docstring'''







						_A       	=      torch.manual_seed(a__		)
						_A       	=      {
						    "prompt": "A field of roses",
						    "generator": generator,
						    # Setting height and width to None to prevent OOMs on CPU.
						    "height": None,
						    "width": None,
						    "num_inference_steps": 2,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs







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





						'''simple docstring'''







						_A       	=      "cpu"  # ensure determinism for the device-dependent torch.Generator
						_A       	=      self.get_dummy_components()
						_A       	=      StableDiffusionModelEditingPipeline(**a__		)
						_A       	=      sd_pipe.to(a__		)
						sd_pipe.set_progress_bar_config(disable=a__		)

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

						_A       	=      np.array([0.4_7_5_5, 0.5_1_3_2, 0.4_9_7_6, 0.3_9_0_4, 0.3_5_5_4, 0.4_7_6_5, 0.5_1_3_9, 0.5_1_5_8, 0.4_8_8_9]		)

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







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





						'''simple docstring'''







						_A       	=      "cpu"  # ensure determinism for the device-dependent torch.Generator
						_A       	=      self.get_dummy_components()
						_A       	=      StableDiffusionModelEditingPipeline(**a__		)
						_A       	=      sd_pipe.to(a__		)
						sd_pipe.set_progress_bar_config(disable=a__		)

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

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

						_A       	=      np.array([0.4_9_9_2, 0.5_1_0_1, 0.5_0_0_4, 0.3_9_4_9, 0.3_6_0_4, 0.4_7_3_5, 0.5_2_1_6, 0.5_2_0_4, 0.4_9_1_3]		)

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







		def 			a_			(       self   :							int		)							->    Any:





						'''simple docstring'''







						_A       	=      "cpu"  # ensure determinism for the device-dependent torch.Generator
						_A       	=      self.get_dummy_components()
						_A       	=      EulerAncestralDiscreteScheduler(
						    beta_start=0.0_0_0_8_5     , beta_end=0.0_1_2     , beta_schedule="scaled_linear"		)
						_A       	=      StableDiffusionModelEditingPipeline(**a__		)
						_A       	=      sd_pipe.to(a__		)
						sd_pipe.set_progress_bar_config(disable=a__		)

						_A       	=      self.get_dummy_inputs(a__		)
						_A       	=      sd_pipe(**a__		).images
						_A       	=      image[0, -3:, -3:, -1]

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

						_A       	=      np.array([0.4_7_4_7, 0.5_3_7_2, 0.4_7_7_9, 0.4_9_8_2, 0.5_5_4_3, 0.4_8_1_6, 0.5_2_3_8, 0.4_9_0_4, 0.5_0_2_7]		)

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







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





						'''simple docstring'''







						_A       	=      "cpu"  # ensure determinism for the device-dependent torch.Generator
						_A       	=      self.get_dummy_components()
						_A       	=      PNDMScheduler()
						_A       	=      StableDiffusionModelEditingPipeline(**a__		)
						_A       	=      sd_pipe.to(a__		)
						sd_pipe.set_progress_bar_config(disable=a__		)

						_A       	=      self.get_dummy_inputs(a__		)
						# the pipeline does not expect pndm so test if it raises error.
						with self.assertRaises(a__		):
										_A       	=      sd_pipe(**a__		).images







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





						'''simple docstring'''







						super().test_inference_batch_single_identical(expected_max_diff=5E-3		)







		def 			a_			(       self   :							Optional[Any]		)							->    Any:





						'''simple docstring'''







						super().test_attention_slicing_forward_pass(expected_max_diff=5E-3		)





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







		def 			a_			(       self   :							List[str]		)							->    Dict:





						'''simple docstring'''







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







		def 			a_			(       self   :							Optional[Any]     , a__   :							Any=0		)							->    List[Any]:





						'''simple docstring'''







						_A       	=      torch.manual_seed(a__		)
						_A       	=      {
						    "prompt": "A field of roses",
						    "generator": generator,
						    "num_inference_steps": 3,
						    "guidance_scale": 7.5,
						    "output_type": "numpy",
						}
						return inputs







		def 			a_			(       self   :							Tuple		)							->    Dict:





						'''simple docstring'''







						_A       	=      "CompVis/stable-diffusion-v1-4"
						_A       	=      StableDiffusionModelEditingPipeline.from_pretrained(a__     , safety_checker=a__		)
						pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)
						pipe.enable_attention_slicing()

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

						assert image.shape == (1, 5_12, 5_12, 3)

						_A       	=      np.array(
						    [0.6_7_4_9_4_9_6, 0.6_3_8_6_4_5_3, 0.5_1_4_4_3_2_6_7, 0.6_6_0_9_4_9_0_5, 0.6_1_9_2_1_2_1_5, 0.5_4_9_1_3_3_2, 0.5_7_4_4_4_1_7, 0.5_8_0_7_5_1_0_6, 0.5_1_7_4_6_5_8]		)

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

						# make sure image changes after editing
						pipe.edit_model("A pack of roses"     , "A pack of blue roses"		)

						_A       	=      pipe(**a__		).images
						_A       	=      image[0, -3:, -3:, -1].flatten()

						assert image.shape == (1, 5_12, 5_12, 3)

						assert np.abs(expected_slice - image_slice		).max() > 1E-1







		def 			a_			(       self   :							List[str]		)							->    str:





						'''simple docstring'''







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

						_A       	=      "CompVis/stable-diffusion-v1-4"
						_A       	=      DDIMScheduler.from_pretrained(a__     , subfolder="scheduler"		)
						_A       	=      StableDiffusionModelEditingPipeline.from_pretrained(
						    a__     , scheduler=a__     , safety_checker=a__		)
						_A       	=      pipe.to(a__		)
						pipe.set_progress_bar_config(disable=a__		)
						pipe.enable_attention_slicing(1		)
						pipe.enable_sequential_cpu_offload()

						_A       	=      self.get_inputs()
						_A       	=      pipe(**a__		)

						_A       	=      torch.cuda.max_memory_allocated()
						# make sure that less than 4.4 GB is allocated
						assert mem_bytes < 4.4 * 10**9



"""simple docstring"""


import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


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






def   a__			(					self  ,      __lowercase  ,      __lowercase  ,      __lowercase  ,      __lowercase )						->						Tuple:
				_A       	=      image.to(device=__lowercase )
				_A       	=      image  # take image as image_embeddings
				_A       	=      image_embeddings.unsqueeze(1 )

				# duplicate image embeddings for each generation per prompt, using mps friendly method
				_A	,		_A	,		_A       	=      image_embeddings.shape
				_A       	=      image_embeddings.repeat(1  ,      __lowercase  ,      1 )
				_A       	=      image_embeddings.view(bs_embed * num_images_per_prompt  ,      __lowercase  ,      -1 )

				if do_classifier_free_guidance:
								_A       	=      torch.zeros_like(__lowercase )

								# 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
								_A       	=      torch.cat([uncond_embeddings, image_embeddings] )

				return image_embeddings




class snake_case   (	_UpperCamelCase):







		def __init__(       self   :							Dict     , a__   :							PriorTransformer     , a__   :							CLIPTokenizer     , a__   :							CLIPTextModelWithProjection     , a__   :							UnCLIPScheduler     , a__   :							Optional[dict] = None     , )							->    Optional[Any]:





						'''simple docstring'''







						super().__init__()

						_A       	=      {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

						_A       	=      decoder_pipe_kwargs.get("torch_dtype"     , a__		) or prior.dtype

						_A       	=      StableDiffusionImageVariationPipeline.from_pretrained(
						    "lambdalabs/sd-image-variations-diffusers"     , **a__		)

						# replace `_encode_image` method
						_A       	=      types.MethodType(_encode_image     , self.decoder_pipe		)

						self.register_modules(
						    prior=a__     , tokenizer=a__     , text_encoder=a__     , prior_scheduler=a__     , )







		def 			a_			(       self   :							Optional[Any]     , a__   :							str     , a__   :							Optional[Any]     , a__   :							int     , a__   :							Optional[int]     , a__   :							Optional[Union[CLIPTextModelOutput, Tuple]] = None     , a__   :							Optional[torch.Tensor] = None     , )							->    Optional[Any]:





						'''simple docstring'''







						if text_model_output is None:
										_A       	=      len(a__		) if isinstance(a__     , a__		) else 1
										# get prompt text embeddings
										_A       	=      self.tokenizer(
										    a__     , padding="max_length"     , max_length=self.tokenizer.model_max_length     , return_tensors="pt"     , )
										_A       	=      text_inputs.input_ids
										_A       	=      text_inputs.attention_mask.bool().to(a__		)

										if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
														_A       	=      self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]		)
														logger.warning(
														    "The following part of your input was truncated because CLIP can only handle sequences up to"
														    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""		)
														_A       	=      text_input_ids[:, : self.tokenizer.model_max_length]

										_A       	=      self.text_encoder(text_input_ids.to(a__		)		)

										_A       	=      text_encoder_output.text_embeds
										_A       	=      text_encoder_output.last_hidden_state

						else:
										_A       	=      text_model_output[0].shape[0]
										_A	,		_A       	=      text_model_output[0], text_model_output[1]
										_A       	=      text_attention_mask

						_A       	=      text_embeddings.repeat_interleave(a__     , dim=0		)
						_A       	=      text_encoder_hidden_states.repeat_interleave(a__     , dim=0		)
						_A       	=      text_mask.repeat_interleave(a__     , dim=0		)

						if do_classifier_free_guidance:
										_A       	=      [""] * batch_size

										_A       	=      self.tokenizer(
										    a__     , padding="max_length"     , max_length=self.tokenizer.model_max_length     , truncation=a__     , return_tensors="pt"     , )
										_A       	=      uncond_input.attention_mask.bool().to(a__		)
										_A       	=      self.text_encoder(uncond_input.input_ids.to(a__		)		)

										_A       	=      uncond_embeddings_text_encoder_output.text_embeds
										_A       	=      uncond_embeddings_text_encoder_output.last_hidden_state

										# duplicate unconditional embeddings for each generation per prompt, using mps friendly method

										_A       	=      uncond_embeddings.shape[1]
										_A       	=      uncond_embeddings.repeat(1     , a__		)
										_A       	=      uncond_embeddings.view(batch_size * num_images_per_prompt     , a__		)

										_A       	=      uncond_text_encoder_hidden_states.shape[1]
										_A       	=      uncond_text_encoder_hidden_states.repeat(1     , a__     , 1		)
										_A       	=      uncond_text_encoder_hidden_states.view(
										    batch_size * num_images_per_prompt     , a__     , -1		)
										_A       	=      uncond_text_mask.repeat_interleave(a__     , dim=0		)

										# done duplicates

										# 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
										_A       	=      torch.cat([uncond_embeddings, text_embeddings]		)
										_A       	=      torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]		)

										_A       	=      torch.cat([uncond_text_mask, text_mask]		)

						return text_embeddings, text_encoder_hidden_states, text_mask







		@property
		def 			a_			(       self   :							int		)							->    Tuple:





						'''simple docstring'''







						if self.device != torch.device("meta"		) or not hasattr(self.prior     , "_hf_hook"		):
										return self.device
						for module in self.prior.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







		def 			a_			(       self   :							str     , a__   :							int     , a__   :							str     , a__   :							List[str]     , a__   :							Dict     , a__   :							Optional[Any]     , a__   :							Dict		)							->    int:





						'''simple docstring'''







						if latents is None:
										_A       	=      randn_tensor(a__     , generator=a__     , device=a__     , dtype=a__		)
						else:
										if latents.shape != shape:
														raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""		)
										_A       	=      latents.to(a__		)

						_A       	=      latents * scheduler.init_noise_sigma
						return latents







		def 			a_			(       self   :							List[str]     , a__   :							Optional[Union[str, torch.device]] = None		)							->    Any:





						'''simple docstring'''







						self.decoder_pipe.to(a__		)
						super().to(a__		)







		@torch.no_grad()
		def __call__(       self   :							List[Any]     , a__   :							Optional[Union[str, List[str]]] = None     , a__   :							Optional[int] = None     , a__   :							Optional[int] = None     , a__   :							int = 1     , a__   :							int = 25     , a__   :							Optional[torch.Generator] = None     , a__   :							Optional[torch.FloatTensor] = None     , a__   :							Optional[Union[CLIPTextModelOutput, Tuple]] = None     , a__   :							Optional[torch.Tensor] = None     , a__   :							float = 4.0     , a__   :							float = 8.0     , a__   :							int = 50     , a__   :							Optional[int] = 1     , a__   :							float = 0.0     , a__   :							Optional[str] = "pil"     , a__   :							bool = True     , )							->    str:





						'''simple docstring'''







						if prompt is not None:
										if isinstance(a__     , a__		):
														_A       	=      1
										elif isinstance(a__     , a__		):
														_A       	=      len(a__		)
										else:
														raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(a__		)}"""		)
						else:
										_A       	=      text_model_output[0].shape[0]

						_A       	=      self._execution_device

						_A       	=      batch_size * num_images_per_prompt

						_A       	=      prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

						_A	,		_A	,		_A       	=      self._encode_prompt(
						    a__     , a__     , a__     , a__     , a__     , a__		)

						# prior

						self.prior_scheduler.set_timesteps(a__     , device=a__		)
						_A       	=      self.prior_scheduler.timesteps

						_A       	=      self.prior.config.embedding_dim

						_A       	=      self.prepare_latents(
						    (batch_size, embedding_dim)     , text_embeddings.dtype     , a__     , a__     , a__     , self.prior_scheduler     , )

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

										_A       	=      self.prior(
										    a__     , timestep=a__     , proj_embedding=a__     , encoder_hidden_states=a__     , attention_mask=a__     , ).predicted_image_embedding

										if do_classifier_free_guidance:
														_A	,		_A       	=      predicted_image_embedding.chunk(2		)
														_A       	=      predicted_image_embedding_uncond + prior_guidance_scale * (
														    predicted_image_embedding_text - predicted_image_embedding_uncond
														)

										if i + 1 == prior_timesteps_tensor.shape[0]:
														_A       	=      None
										else:
														_A       	=      prior_timesteps_tensor[i + 1]

										_A       	=      self.prior_scheduler.step(
										    a__     , timestep=a__     , sample=a__     , generator=a__     , prev_timestep=a__     , ).prev_sample

						_A       	=      self.prior.post_process_latents(a__		)

						_A       	=      prior_latents

						_A       	=      self.decoder_pipe(
						    image=a__     , height=a__     , width=a__     , num_inference_steps=a__     , guidance_scale=a__     , generator=a__     , output_type=a__     , return_dict=a__     , num_images_per_prompt=a__     , eta=a__     , )
						return output