



"""simple docstring"""
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

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


A:   List[str]								=		logging.get_logger(__name__)  # pylint: disable=invalid-name

A:   List[str]								=		"\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n"



@dataclass
class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):
   __lowerCAmelCase  :   Union[PIL.Image.Image, np.ndarray]



class       SCREAMING_SNAKE_CASE__  (					UpperCAmelCase__ ):

   def __init__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     )  ->      Optional[Any]:





    '''simple docstring'''




    super().__init__()

    self.register_modules(
        prior=_SCREAMING_SNAKE_CASE      ,     image_encoder=_SCREAMING_SNAKE_CASE      ,     image_processor=_SCREAMING_SNAKE_CASE      ,     scheduler=_SCREAMING_SNAKE_CASE      ,     renderer=_SCREAMING_SNAKE_CASE      ,     )

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)  ->      int:





    '''simple docstring'''




    if latents is None:
     UpperCAmelCase	:					Union[str, Any]	=	randn_tensor(_SCREAMING_SNAKE_CASE      ,     generator=_SCREAMING_SNAKE_CASE      ,     device=_SCREAMING_SNAKE_CASE      ,     dtype=_SCREAMING_SNAKE_CASE						)
    else:
     if latents.shape != shape:
      raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"						)
     UpperCAmelCase	:					List[str]	=	latents.to(_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Any	=	latents * scheduler.init_noise_sigma
    return latents

   def 	SCREAMING_SNAKE_CASE     (   self      ,     _SCREAMING_SNAKE_CASE=0						)  ->      List[str]:





    '''simple docstring'''




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

    UpperCAmelCase	:					List[str]	=	torch.device(F"cuda:{gpu_id}"						)

    UpperCAmelCase	:					Optional[Any]	=	[self.image_encoder, self.prior]
    for cpu_offloaded_model in models:
     if cpu_offloaded_model is not None:
      cpu_offload(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

   @property
   def 	SCREAMING_SNAKE_CASE     (   self						)  ->      List[Any]:





    '''simple docstring'''




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





    '''simple docstring'''




    if isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) and isinstance(image[0]      ,     torch.Tensor						):
     UpperCAmelCase	:					Dict	=	torch.cat(_SCREAMING_SNAKE_CASE      ,     axis=0						) if image[0].ndim == 4 else torch.stack(_SCREAMING_SNAKE_CASE      ,     axis=0						)

    if not isinstance(_SCREAMING_SNAKE_CASE      ,     torch.Tensor						):
     UpperCAmelCase	:					Any	=	self.image_processor(_SCREAMING_SNAKE_CASE      ,     return_tensors="""pt"""						).pixel_values[0].unsqueeze(0						)

    UpperCAmelCase	:					Optional[Any]	=	image.to(dtype=self.image_encoder.dtype      ,     device=_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					str	=	self.image_encoder(_SCREAMING_SNAKE_CASE						)["""last_hidden_state"""]
    UpperCAmelCase	:					int	=	image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

    UpperCAmelCase	:					Optional[Any]	=	image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE      ,     dim=0						)

    if do_classifier_free_guidance:
     UpperCAmelCase	:					Tuple	=	torch.zeros_like(_SCREAMING_SNAKE_CASE						)

     # 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
     UpperCAmelCase	:					str	=	torch.cat([negative_image_embeds, image_embeds]						)

    return image_embeds




   @torch.no_grad()
   @replace_example_docstring(_SCREAMING_SNAKE_CASE						)
   def __call__(   self      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE = 1      ,     _SCREAMING_SNAKE_CASE = 25      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = None      ,     _SCREAMING_SNAKE_CASE = 4.0      ,     _SCREAMING_SNAKE_CASE = 64      ,     _SCREAMING_SNAKE_CASE = "pil"      ,     _SCREAMING_SNAKE_CASE = True      ,     )  ->      Optional[Any]:





    '''simple docstring'''




    if isinstance(_SCREAMING_SNAKE_CASE      ,     PIL.Image.Image						):
     UpperCAmelCase	:					List[str]	=	1
    elif isinstance(_SCREAMING_SNAKE_CASE      ,     torch.Tensor						):
     UpperCAmelCase	:					str	=	image.shape[0]
    elif isinstance(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						) and isinstance(image[0]      ,     (torch.Tensor, PIL.Image.Image)						):
     UpperCAmelCase	:					Optional[int]	=	len(_SCREAMING_SNAKE_CASE						)
    else:
     raise ValueError(
         F"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_SCREAMING_SNAKE_CASE						)}"						)

    UpperCAmelCase	:					str	=	self._execution_device

    UpperCAmelCase	:					List[Any]	=	batch_size * num_images_per_prompt

    UpperCAmelCase	:					List[Any]	=	guidance_scale > 1.0
    UpperCAmelCase	:					Dict	=	self._encode_image(_SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

    # prior

    self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE      ,     device=_SCREAMING_SNAKE_CASE						)
    UpperCAmelCase	:					str	=	self.scheduler.timesteps

    UpperCAmelCase	:					Optional[int]	=	self.prior.config.num_embeddings
    UpperCAmelCase	:					int	=	self.prior.config.embedding_dim

    UpperCAmelCase	:					Tuple	=	self.prepare_latents(
        (batch_size, num_embeddings * embedding_dim)      ,     image_embeds.dtype      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE      ,     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
    UpperCAmelCase	:					List[Any]	=	latents.reshape(latents.shape[0]      ,     _SCREAMING_SNAKE_CASE      ,     _SCREAMING_SNAKE_CASE						)

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

     UpperCAmelCase	:					List[str]	=	self.prior(
         _SCREAMING_SNAKE_CASE      ,     timestep=_SCREAMING_SNAKE_CASE      ,     proj_embedding=_SCREAMING_SNAKE_CASE      ,     ).predicted_image_embedding

     # remove the variance
     UpperCAmelCase	,		UpperCAmelCase	:					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:
      UpperCAmelCase	,		UpperCAmelCase	:					Dict	=	noise_pred.chunk(2						)
      UpperCAmelCase	:					Optional[Any]	=	noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

     UpperCAmelCase	:					Optional[Any]	=	self.scheduler.step(
         _SCREAMING_SNAKE_CASE      ,     timestep=_SCREAMING_SNAKE_CASE      ,     sample=_SCREAMING_SNAKE_CASE      ,     ).prev_sample

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

    UpperCAmelCase	:					Optional[Any]	=	[]
    for i, latent in enumerate(_SCREAMING_SNAKE_CASE						):
     print()
     UpperCAmelCase	:					int	=	self.renderer.decode(
         latent[None, :]      ,     _SCREAMING_SNAKE_CASE      ,     size=_SCREAMING_SNAKE_CASE      ,     ray_batch_size=4096      ,     n_coarse_samples=64      ,     n_fine_samples=128      ,     )

     images.append(_SCREAMING_SNAKE_CASE						)

    UpperCAmelCase	:					Any	=	torch.stack(_SCREAMING_SNAKE_CASE						)

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

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

    if output_type == "pil":
     UpperCAmelCase	:					Tuple	=	[self.numpy_to_pil(_SCREAMING_SNAKE_CASE						) 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=_SCREAMING_SNAKE_CASE						)




import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

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,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class 	UpperCAmelCase_					(					UpperCamelCase		, UpperCamelCase		, UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      Tuple     		=		StableUnCLIPPipeline
   __A :      Optional[int]     		=		TEXT_TO_IMAGE_PARAMS
   __A :      str     		=		TEXT_TO_IMAGE_BATCH_PARAMS
   __A :      int     		=		TEXT_TO_IMAGE_IMAGE_PARAMS
   __A :      Tuple     		=		TEXT_TO_IMAGE_IMAGE_PARAMS

   # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
   __A :      Union[str, Any]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				32
     lowerCamelCase :					Dict    =				embedder_hidden_size

     # prior components

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

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTextModelWithProjection(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=__A						,				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 )
     lowerCamelCase :					List[Any]    =				PriorTransformer(
         num_attention_heads=2						,				attention_head_dim=12						,				embedding_dim=__A						,				num_layers=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Dict    =				DDPMScheduler(
         variance_type="fixed_small_log"						,				prediction_type="sample"						,				num_train_timesteps=1000						,				clip_sample=__A						,				clip_sample_range=5.0						,				beta_schedule="squaredcos_cap_v2"						,				)

     # regular denoising components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				StableUnCLIPImageNormalizer(embedding_dim=__A )
     lowerCamelCase :					Tuple    =				DDPMScheduler(beta_schedule="squaredcos_cap_v2" )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					str    =				CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				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 )
     lowerCamelCase :					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=__A						,				layers_per_block=1						,				upcast_attention=__A						,				use_linear_projection=__A						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					int    =				DDIMScheduler(
         beta_schedule="scaled_linear"						,				beta_start=0.00085						,				beta_end=0.012						,				prediction_type="v_prediction"						,				set_alpha_to_one=__A						,				steps_offset=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[Any]    =				AutoencoderKL()

     lowerCamelCase :					Optional[int]    =				{
         # prior components
         "prior_tokenizer": prior_tokenizer,
         "prior_text_encoder": prior_text_encoder,
         "prior": prior,
         "prior_scheduler": prior_scheduler,
         # image noising components
         "image_normalizer": image_normalizer,
         "image_noising_scheduler": image_noising_scheduler,
         # regular denoising components
         "tokenizer": tokenizer,
         "text_encoder": text_encoder,
         "unet": unet,
         "scheduler": scheduler,
         "vae": vae,
     }

     return components






   def _snake_case    (		self						,				__A						,				__A=0 ):






     """simple docstring"""





     if str(__A ).startswith("mps" ):
       lowerCamelCase :					Optional[int]    =				torch.manual_seed(__A )
     else:
       lowerCamelCase :					Optional[Any]    =				torch.Generator(device=__A ).manual_seed(__A )
     lowerCamelCase :					Tuple    =				{
         "prompt": "A painting of a squirrel eating a burger",
         "generator": generator,
         "num_inference_steps": 2,
         "prior_num_inference_steps": 2,
         "output_type": "numpy",
     }
     return inputs






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				torch_device in ["cpu", "mps"]

     self._test_inference_batch_single_identical(test_max_difference=__A )



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

   '''simple docstring'''




   def _snake_case    (		self ):






     """simple docstring"""





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






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" )

     lowerCamelCase :					str    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     # 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()

     lowerCamelCase :					List[Any]    =				torch.Generator(device="cpu" ).manual_seed(0 )
     lowerCamelCase :					Dict    =				pipe("anime turle"						,				generator=__A						,				output_type="np" )

     lowerCamelCase :					Dict    =				output.images[0]

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

     assert_mean_pixel_difference(__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





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

     lowerCamelCase :					int    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     lowerCamelCase :					Union[str, Any]    =				pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					Any    =				pipe(
         "anime turtle"						,				prior_num_inference_steps=2						,				num_inference_steps=2						,				output_type="np"						,				)

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



