



import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()

class 			__snake_case   ( SCREAMING_SNAKE_CASE      ,SCREAMING_SNAKE_CASE      ,unittest.TestCase):







							'''simple docstring'''






							UpperCamelCase__					:   List[str]       =       StableDiffusionXLPipeline
							UpperCamelCase__					:   int       =       TEXT_TO_IMAGE_PARAMS
							UpperCamelCase__					:   int       =       TEXT_TO_IMAGE_BATCH_PARAMS
							UpperCamelCase__					:   int       =       TEXT_TO_IMAGE_IMAGE_PARAMS
							UpperCamelCase__					:   Any       =       TEXT_TO_IMAGE_IMAGE_PARAMS


							def _a   (				self		):
											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""")	,	attention_head_dim=(2, 4)	,	use_linear_projection=a_	,	addition_embed_type="""text_time"""	,	addition_time_embed_dim=8	,	transformer_layers_per_block=(1, 2)	,	projection_class_embeddings_input_dim=80	,	cross_attention_dim=64	,	)
											a__					   =		EulerDiscreteScheduler(
											    beta_start=0.00_085	,	beta_end=0.012	,	steps_offset=1	,	beta_schedule="""scaled_linear"""	,	timestep_spacing="""leading"""	,	)
											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	,	sample_size=128	,	)
											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=1_000	,	hidden_act="""gelu"""	,	projection_dim=32	,	)
											a__					   =		CLIPTextModel(a_		)
											a__					   =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""	,	local_files_only=a_		)

											a__					   =		CLIPTextModelWithProjection(a_		)
											a__					   =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""	,	local_files_only=a_		)

											a__					   =		{
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vae""": vae,
											    """text_encoder""": text_encoder,
											    """tokenizer""": tokenizer,
											    """text_encoder_2""": text_encoder_a,
											    """tokenizer_2""": tokenizer_a,
											    # "safety_checker": None,
											    # "feature_extractor": None,
											}
											return components


							def _a   (				self	,	a_	,	a_=0		):
											if str(a_		).startswith("""mps"""		):
															a__					   =		torch.manual_seed(a_		)
											else:
															a__					   =		torch.Generator(device=a_		).manual_seed(a_		)
											a__					   =		{
											    """prompt""": """A painting of a squirrel eating a burger""",
											    """generator""": generator,
											    """num_inference_steps""": 2,
											    """guidance_scale""": 5.0,
											    """output_type""": """numpy""",
											}
											return inputs


							def _a   (				self		):
											a__					   =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
											a__					   =		self.get_dummy_components()
											a__					   =		StableDiffusionXLPipeline(**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.5_873, 0.6_128, 0.4_797, 0.5_122, 0.5_674, 0.4_639, 0.5_227, 0.5_149, 0.4_747]		)

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


							def _a   (				self		):
											a__					   =		self.get_dummy_components()
											a__					   =		StableDiffusionXLPipeline(**a_		)
											a__					   =		sd_pipe.to(a_		)
											a__					   =		sd_pipe.to(a_		)
											sd_pipe.set_progress_bar_config(disable=a_		)

											# forward without prompt embeds
											a__					   =		self.get_dummy_inputs(a_		)
											a__					   =		3 * ["""this is a negative prompt"""]
											a__					   =		negative_prompt
											a__					   =		3 * [inputs["""prompt"""]]

											a__					   =		sd_pipe(**a_		)
											a__					   =		output.images[0, -3:, -3:, -1]

											# forward with prompt embeds
											a__					   =		self.get_dummy_inputs(a_		)
											a__					   =		3 * ["""this is a negative prompt"""]
											a__					   =		3 * [inputs.pop("""prompt"""		)]

											(
											    (
											    a__
											)   ,      (
											    a__
											)   ,      (
											    a__
											)   ,      (
											    a__
											)   ,      
											)					   =		sd_pipe.encode_prompt(a_	,	negative_prompt=a_		)

											a__					   =		sd_pipe(
											    **a_	,	prompt_embeds=a_	,	negative_prompt_embeds=a_	,	pooled_prompt_embeds=a_	,	negative_pooled_prompt_embeds=a_	,	)
											a__					   =		output.images[0, -3:, -3:, -1]

											# make sure that it's equal
											assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()		).max() < 1E-4


							def _a   (				self		):
											super().test_attention_slicing_forward_pass(expected_max_diff=3E-3		)







							def _a   (				self		):
											super().test_inference_batch_single_identical(expected_max_diff=3E-3		)




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







							'''simple docstring'''






							def _a   (				self		):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()


							def _a   (				self	,	a_	,	a_="cpu"	,	a_=torch.floataa	,	a_=0		):
											a__					   =		torch.Generator(device=a_		).manual_seed(a_		)
											a__					   =		np.random.RandomState(a_		).standard_normal((1, 4, 64, 64)		)
											a__					   =		torch.from_numpy(a_		).to(device=a_	,	dtype=a_		)
											a__					   =		{
											    """prompt""": """a photograph of an astronaut riding a horse""",
											    """latents""": latents,
											    """generator""": generator,
											    """num_inference_steps""": 3,
											    """guidance_scale""": 7.5,
											    """output_type""": """numpy""",
											}
											return inputs







							def _a   (				self		):
											a__					   =		DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""		)
											pipe.to(a_		)
											pipe.set_progress_bar_config(disable=a_		)

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

											assert image.shape == (1, 512, 512, 3)
											a__					   =		np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]		)
											assert np.abs(image_slice - expected_slice		).max() < 7E-3




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


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

__UpperCAmelCase     					=  '\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 A__     (			A			):



 """simple docstring"""







 _lowercase  :       Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]





class A__     (			A			):



 """simple docstring"""







 def __init__(		self			:						Dict  ,    A_			:						PriorTransformer  ,    A_			:						CLIPTextModelWithProjection  ,    A_			:						CLIPTokenizer  ,    A_			:						HeunDiscreteScheduler  ,    A_			:						ShapERenderer  ,    ):






      '''simple docstring'''




      super().__init__()

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

 def  __magic_name__							(		self			:						Tuple  ,    A_			:						List[Any]  ,    A_			:						Optional[Any]  ,    A_			:						int  ,    A_			:						Optional[Any]  ,    A_			:						str  ,    A_			:						Dict							):






      '''simple docstring'''




      if latents is None:
           _lowerCAmelCase :       int	   =     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}'''							)
           _lowerCAmelCase :       Union[str, Any]	   =     latents.to(A_							)

      _lowerCAmelCase :       Union[str, Any]	   =     latents * scheduler.init_noise_sigma
      return latents

 def  __magic_name__							(		self			:						Any  ,    A_			:						List[Any]=0							):






      '''simple docstring'''




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

      _lowerCAmelCase :       int	   =     torch.device(F'''cuda:{gpu_id}'''							)

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

 def  __magic_name__							(		self			:						List[str]  ,    A_			:						List[str]=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 :       Optional[int]	   =     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 :       Union[str, Any]	   =     None
      for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
           _lowerCAmelCase   ,      _lowerCAmelCase :       Optional[int]	   =     cpu_offload_with_hook(A_  ,    A_  ,    prev_module_hook=A_							)

      if self.safety_checker is not None:
           _lowerCAmelCase   ,      _lowerCAmelCase :       Optional[Any]	   =     cpu_offload_with_hook(self.safety_checker  ,    A_  ,    prev_module_hook=A_							)

      # We'll offload the last model manually.
      _lowerCAmelCase :       Any	   =     hook

 @property
 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''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  __magic_name__							(		self			:						str  ,    A_			:						List[str]  ,    A_			:						Optional[int]  ,    A_			:						List[str]  ,    A_			:						str  ,    ):






      '''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
      _lowerCAmelCase :       Dict	   =     0
      # get prompt text embeddings
      _lowerCAmelCase :       Any	   =     self.tokenizer(
          A_  ,    padding="max_length"  ,    max_length=self.tokenizer.model_max_length  ,    truncation=A_  ,    return_tensors="pt"  ,    )
      _lowerCAmelCase :       List[Any]	   =     text_inputs.input_ids
      _lowerCAmelCase :       Any	   =     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_							):
           _lowerCAmelCase :       Any	   =     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}'''							)

      _lowerCAmelCase :       Any	   =     self.text_encoder(text_input_ids.to(A_							)							)
      _lowerCAmelCase :       Union[str, Any]	   =     text_encoder_output.text_embeds

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

      if do_classifier_free_guidance:
           _lowerCAmelCase :       Union[str, Any]	   =     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
           _lowerCAmelCase :       Union[str, Any]	   =     torch.cat([negative_prompt_embeds, prompt_embeds]							)

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

      return prompt_embeds


 @torch.no_grad()
 @replace_example_docstring(A_							)
 def __call__(		self			:						Tuple  ,    A_			:						str  ,    A_			:						int = 1  ,    A_			:						int = 2_5  ,    A_			:						Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,    A_			:						Optional[torch.FloatTensor] = None  ,    A_			:						float = 4.0  ,    A_			:						int = 6_4  ,    A_			:						Optional[str] = "pil"  ,    A_			:						bool = True  ,    ):






      '''simple docstring'''




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

      _lowerCAmelCase :       int	   =     self._execution_device

      _lowerCAmelCase :       int	   =     batch_size * num_images_per_prompt

      _lowerCAmelCase :       List[Any]	   =     guidance_scale > 1.0
      _lowerCAmelCase :       Tuple	   =     self._encode_prompt(A_  ,    A_  ,    A_  ,    A_							)

      # prior

      self.scheduler.set_timesteps(A_  ,    device=A_							)
      _lowerCAmelCase :       List[str]	   =     self.scheduler.timesteps

      _lowerCAmelCase :       Dict	   =     self.prior.config.num_embeddings
      _lowerCAmelCase :       int	   =     self.prior.config.embedding_dim

      _lowerCAmelCase :       Optional[Any]	   =     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
      _lowerCAmelCase :       int	   =     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
           _lowerCAmelCase :       Any	   =     torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
           _lowerCAmelCase :       Optional[int]	   =     self.scheduler.scale_model_input(A_  ,    A_							)

           _lowerCAmelCase :       Optional[int]	   =     self.prior(
               A_  ,    timestep=A_  ,    proj_embedding=A_  ,    ).predicted_image_embedding

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

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

           _lowerCAmelCase :       str	   =     self.scheduler.step(
               A_  ,    timestep=A_  ,    sample=A_  ,    ).prev_sample

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

      _lowerCAmelCase :       Optional[Any]	   =     []
      for i, latent in enumerate(A_							):
           _lowerCAmelCase :       Optional[int]	   =     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_							)

      _lowerCAmelCase :       Any	   =     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}'''							)

      _lowerCAmelCase :       List[Any]	   =     images.cpu().numpy()

      if output_type == "pil":
           _lowerCAmelCase :       Optional[Any]	   =     [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_							)






