
'''simple docstring'''





import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

SCREAMING_SNAKE_CASE   :		Optional[Any]					 =       '\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = "a shark"\n\n        >>> images = pipe(\n        ...     prompt,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")\n        ```\n'






@dataclass
class 					__lowercase		(					_UpperCAmelCase       ):
					__magic_name__						:							Union[str, Any]     	=	42






class 					__lowercase		(					_UpperCAmelCase       ):


					def __init__(	self       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       )		->							Optional[int]:





									'''simple docstring'''
									super().__init__()

									self.register_modules(
									    prior=a__       ,       text_encoder=a__       ,       tokenizer=a__       ,       scheduler=a__       ,       renderer=a__       ,       )


					def        lowerCAmelCase_    (	self       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__       ,       a__						)		->							Tuple:





									'''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        lowerCAmelCase_    (	self       ,       a__=0						)		->							int:





									'''simple docstring'''






									if is_accelerate_available():
													from accelerate import cpu_offload
									else:
													raise ImportError('''Please install accelerate via `pip install accelerate`'''						)

									A_       	=  torch.device(F"cuda:{gpu_id}"						)

									A_       	=  [self.text_encoder, self.prior]
									for cpu_offloaded_model in models:
													if cpu_offloaded_model is not None:
																	cpu_offload(a__       ,       a__						)


					def        lowerCAmelCase_    (	self       ,       a__=0						)		->							int:





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

									A_       	=  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)

									A_       	=  None
									for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
													A_	,					A_       	=  cpu_offload_with_hook(a__       ,       a__       ,       prev_module_hook=a__						)

									if self.safety_checker is not None:
													A_	,					A_       	=  cpu_offload_with_hook(self.safety_checker       ,       a__       ,       prev_module_hook=a__						)

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


					@property
					def        lowerCAmelCase_    (	self						)		->							Optional[int]:





									'''simple docstring'''






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





									'''simple docstring'''
									len(a__						) if isinstance(a__       ,       a__						) else 1

									# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
									A_       	=  0
									# get prompt text embeddings
									A_       	=  self.tokenizer(
									    a__       ,       padding='''max_length'''       ,       max_length=self.tokenizer.model_max_length       ,       truncation=a__       ,       return_tensors='''pt'''       ,       )
									A_       	=  text_inputs.input_ids
									A_       	=  self.tokenizer(a__       ,       padding='''longest'''       ,       return_tensors='''pt'''						).input_ids

									if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(a__       ,       a__						):
													A_       	=  self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]						)
													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_       	=  self.text_encoder(text_input_ids.to(a__						)						)
									A_       	=  text_encoder_output.text_embeds

									A_       	=  prompt_embeds.repeat_interleave(a__       ,       dim=0						)
									# in Shap-E it normalize the prompt_embeds and then later rescale it
									A_       	=  prompt_embeds / torch.linalg.norm(a__       ,       dim=-1       ,       keepdim=a__						)

									if do_classifier_free_guidance:
													A_       	=  torch.zeros_like(a__						)

													# 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([negative_prompt_embeds, prompt_embeds]						)

									# Rescale the features to have unit variance
									A_       	=  math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds

									return prompt_embeds


					@torch.no_grad()
					@replace_example_docstring(a__						)
					def __call__(	self       ,       a__       ,       a__ = 1       ,       a__ = 2_5       ,       a__ = None       ,       a__ = None       ,       a__ = 4.0       ,       a__ = 6_4       ,       a__ = "pil"       ,       a__ = True       ,       )		->							int:





									'''simple docstring'''






									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__						)}"						)

									A_       	=  self._execution_device

									A_       	=  batch_size * num_images_per_prompt

									A_       	=  guidance_scale > 1.0
									A_       	=  self._encode_prompt(a__       ,       a__       ,       a__       ,       a__						)

									# prior

									self.scheduler.set_timesteps(a__       ,       device=a__						)
									A_       	=  self.scheduler.timesteps

									A_       	=  self.prior.config.num_embeddings
									A_       	=  self.prior.config.embedding_dim

									A_       	=  self.prepare_latents(
									    (batch_size, num_embeddings * embedding_dim)       ,       prompt_embeds.dtype       ,       a__       ,       a__       ,       a__       ,       self.scheduler       ,       )

									# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
									A_       	=  latents.reshape(latents.shape[0]       ,       a__       ,       a__						)

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

													A_       	=  self.prior(
													    a__       ,       timestep=a__       ,       proj_embedding=a__       ,       ).predicted_image_embedding

													# remove the variance
													A_	,					A_       	=  noise_pred.split(
													    scaled_model_input.shape[2]       ,       dim=2						)  # batch_size, num_embeddings, embedding_dim

													if do_classifier_free_guidance is not None:
																	A_	,					A_       	=  noise_pred.chunk(2						)
																	A_       	=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

													A_       	=  self.scheduler.step(
													    a__       ,       timestep=a__       ,       sample=a__       ,       ).prev_sample

									if output_type == "latent":
													return ShapEPipelineOutput(images=a__						)

									A_       	=  []
									for i, latent in enumerate(a__						):
													A_       	=  self.renderer.decode(
													    latent[None, :]       ,       a__       ,       size=a__       ,       ray_batch_size=4_0_9_6       ,       n_coarse_samples=6_4       ,       n_fine_samples=1_2_8       ,       )
													images.append(a__						)

									A_       	=  torch.stack(a__						)

									if output_type not in ["np", "pil"]:
													raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"						)

									A_       	=  images.cpu().numpy()

									if output_type == "pil":
													A_       	=  [self.numpy_to_pil(a__						) for image in images]

									# Offload last model to CPU
									if hasattr(self       ,       '''final_offload_hook'''						) and self.final_offload_hook is not None:
													self.final_offload_hook.offload()

									if not return_dict:
													return (images,)

									return ShapEPipelineOutput(images=a__						)

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 					__lowercase		(					A							,       A							,       A							,       unittest.TestCase       ):
					__magic_name__						:							List[str]     	=	StableDiffusionModelEditingPipeline
					__magic_name__						:							List[str]     	=	TEXT_TO_IMAGE_PARAMS
					__magic_name__						:							Any     	=	TEXT_TO_IMAGE_BATCH_PARAMS
					__magic_name__						:							Optional[Any]     	=	TEXT_TO_IMAGE_IMAGE_PARAMS
					__magic_name__						:							Tuple     	=	TEXT_TO_IMAGE_IMAGE_PARAMS


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





									'''simple docstring'''
									torch.manual_seed(0						)
									A_       	=  UNetaDConditionModel(
									    block_out_channels=(3_2, 6_4)       ,       layers_per_block=2       ,       sample_size=3_2       ,       in_channels=4       ,       out_channels=4       ,       down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')       ,       up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')       ,       cross_attention_dim=3_2       ,       )
									A_       	=  DDIMScheduler()
									torch.manual_seed(0						)
									A_       	=  AutoencoderKL(
									    block_out_channels=[3_2, 6_4]       ,       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=3_2       ,       intermediate_size=3_7       ,       layer_norm_eps=1E-05       ,       num_attention_heads=4       ,       num_hidden_layers=5       ,       pad_token_id=1       ,       vocab_size=1_0_0_0       ,       )
									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        lowerCAmelCase_    (	self       ,       a__       ,       a__=0						)		->							List[Any]:





									'''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        lowerCAmelCase_    (	self						)		->							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_       	=  sd_pipe(**a__						).images
									A_       	=  image[0, -3:, -3:, -1]
									assert image.shape == (1, 6_4, 6_4, 3)

									A_       	=  np.array([0.47_55, 0.51_32, 0.49_76, 0.39_04, 0.35_54, 0.47_65, 0.51_39, 0.51_58, 0.48_89]						)

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


					def        lowerCAmelCase_    (	self						)		->							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, 6_4, 6_4, 3)

									A_       	=  np.array([0.49_92, 0.51_01, 0.50_04, 0.39_49, 0.36_04, 0.47_35, 0.52_16, 0.52_04, 0.49_13]						)

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


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





									'''simple docstring'''
									A_       	=  '''cpu'''  # ensure determinism for the device-dependent torch.Generator
									A_       	=  self.get_dummy_components()
									A_       	=  EulerAncestralDiscreteScheduler(
									    beta_start=0.0_00_85       ,       beta_end=0.0_12       ,       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, 6_4, 6_4, 3)

									A_       	=  np.array([0.47_47, 0.53_72, 0.47_79, 0.49_82, 0.55_43, 0.48_16, 0.52_38, 0.49_04, 0.50_27]						)

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


					def        lowerCAmelCase_    (	self						)		->							int:





									'''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        lowerCAmelCase_    (	self						)		->							List[str]:





									'''simple docstring'''
									super().test_inference_batch_single_identical(expected_max_diff=5E-3						)


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





									'''simple docstring'''
									super().test_attention_slicing_forward_pass(expected_max_diff=5E-3						)






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


					def        lowerCAmelCase_    (	self						)		->							List[Any]:





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


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





									'''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_1_2, 5_1_2, 3)

									A_       	=  np.array(
									    [0.6_74_94_96, 0.6_38_64_53, 0.51_44_32_67, 0.66_09_49_05, 0.61_92_12_15, 0.5_49_13_32, 0.5_74_44_17, 0.58_07_51_06, 0.5_17_46_58]						)

									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_1_2, 5_1_2, 3)

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


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





									'''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 * 1_0**9