






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


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

a    =       '\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        __snake_case(					__UpperCamelCase      ):
 lowercase :       Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]
class        __snake_case(					__UpperCamelCase      ):



 def __init__(	self   :   Optional[Any] ,		UpperCAmelCase__   :   PriorTransformer ,		UpperCAmelCase__   :   CLIPTextModelWithProjection ,		UpperCAmelCase__   :   CLIPTokenizer ,		UpperCAmelCase__   :   HeunDiscreteScheduler ,		UpperCAmelCase__   :   ShapERenderer ,		):

    """simple docstring"""






    super().__init__()

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



 def 						UpperCAmelCase    (	self   :   Tuple ,		UpperCAmelCase__   :   Any ,		UpperCAmelCase__   :   Optional[int] ,		UpperCAmelCase__   :   Union[str, Any] ,		UpperCAmelCase__   :   str ,		UpperCAmelCase__   :   Optional[Any] ,		UpperCAmelCase__   :   Union[str, Any]	):

    """simple docstring"""






    if latents is None:
       lowercase__						:	Tuple         = randn_tensor(UpperCAmelCase__ ,		generator=UpperCAmelCase__ ,		device=UpperCAmelCase__ ,		dtype=UpperCAmelCase__	)
    else:
       if latents.shape != shape:
          raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''	)
       lowercase__						:	List[Any]         = latents.to(UpperCAmelCase__	)

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



 def 						UpperCAmelCase    (	self   :   List[str] ,		UpperCAmelCase__   :   Optional[Any]=0	):

    """simple docstring"""






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

    lowercase__						:	List[Any]         = torch.device(f'''cuda:{gpu_id}'''	)

    lowercase__						:	List[Any]         = [self.text_encoder, self.prior]
    for cpu_offloaded_model in models:
       if cpu_offloaded_model is not None:
          cpu_offload(UpperCAmelCase__ ,		UpperCAmelCase__	)



 def 						UpperCAmelCase    (	self   :   str ,		UpperCAmelCase__   :   Union[str, Any]=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."""	)

    lowercase__						:	Tuple         = torch.device(f'''cuda:{gpu_id}'''	)

    if self.device.type != "cpu":
       self.to("""cpu""" ,		silence_dtype_warnings=UpperCAmelCase__	)
       torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

    lowercase__						:	Union[str, Any]         = None
    for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
       lowercase__						:	Optional[Any]         = cpu_offload_with_hook(UpperCAmelCase__ ,		UpperCAmelCase__ ,		prev_module_hook=UpperCAmelCase__	)

    if self.safety_checker is not None:
       lowercase__						:	Optional[int]         = cpu_offload_with_hook(self.safety_checker ,		UpperCAmelCase__ ,		prev_module_hook=UpperCAmelCase__	)

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



 @property
 def 						UpperCAmelCase    (	self   :   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(UpperCAmelCase__ ,		"""_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 						UpperCAmelCase    (	self   :   str ,		UpperCAmelCase__   :   Any ,		UpperCAmelCase__   :   List[Any] ,		UpperCAmelCase__   :   Dict ,		UpperCAmelCase__   :   Optional[int] ,		):

    """simple docstring"""






    len(UpperCAmelCase__	) if isinstance(UpperCAmelCase__ ,		UpperCAmelCase__	) else 1

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

    if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCAmelCase__ ,		UpperCAmelCase__	):
       lowercase__						:	Optional[int]         = 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}'''	)

    lowercase__						:	List[str]         = self.text_encoder(text_input_ids.to(UpperCAmelCase__	)	)
    lowercase__						:	Any         = text_encoder_output.text_embeds

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

    if do_classifier_free_guidance:
       lowercase__						:	Tuple         = torch.zeros_like(UpperCAmelCase__	)

       # 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
       lowercase__						:	Dict         = torch.cat([negative_prompt_embeds, prompt_embeds]	)

    # Rescale the features to have unit variance
    lowercase__						:	Union[str, Any]         = math.sqrt(prompt_embeds.shape[1]	) * prompt_embeds

    return prompt_embeds







 @torch.no_grad()
 @replace_example_docstring(UpperCAmelCase__	)
 def __call__(	self   :   Optional[int] ,		UpperCAmelCase__   :   str ,		UpperCAmelCase__   :   int = 1 ,		UpperCAmelCase__   :   int = 25 ,		UpperCAmelCase__   :   Optional[Union[torch.Generator, List[torch.Generator]]] = None ,		UpperCAmelCase__   :   Optional[torch.FloatTensor] = None ,		UpperCAmelCase__   :   float = 4.0 ,		UpperCAmelCase__   :   int = 64 ,		UpperCAmelCase__   :   Optional[str] = "pil" ,		UpperCAmelCase__   :   bool = True ,		):

    """simple docstring"""






    if isinstance(UpperCAmelCase__ ,		UpperCAmelCase__	):
       lowercase__						:	Optional[int]         = 1
    elif isinstance(UpperCAmelCase__ ,		UpperCAmelCase__	):
       lowercase__						:	Dict         = len(UpperCAmelCase__	)
    else:
       raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase__	)}'''	)

    lowercase__						:	Tuple         = self._execution_device

    lowercase__						:	int         = batch_size * num_images_per_prompt

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

    # prior

    self.scheduler.set_timesteps(UpperCAmelCase__ ,		device=UpperCAmelCase__	)
    lowercase__						:	Tuple         = self.scheduler.timesteps

    lowercase__						:	Tuple         = self.prior.config.num_embeddings
    lowercase__						:	Union[str, Any]         = self.prior.config.embedding_dim

    lowercase__						:	List[str]         = self.prepare_latents(
        (batch_size, num_embeddings * embedding_dim) ,		prompt_embeds.dtype ,		UpperCAmelCase__ ,		UpperCAmelCase__ ,		UpperCAmelCase__ ,		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
    lowercase__						:	Union[str, Any]         = latents.reshape(latents.shape[0] ,		UpperCAmelCase__ ,		UpperCAmelCase__	)

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

       lowercase__						:	Optional[Any]         = self.prior(
           UpperCAmelCase__ ,		timestep=UpperCAmelCase__ ,		proj_embedding=UpperCAmelCase__ ,		).predicted_image_embedding

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

       if do_classifier_free_guidance is not None:
          lowercase__						:	Union[str, Any]         = noise_pred.chunk(2	)
          lowercase__						:	Optional[int]         = noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

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

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

    lowercase__						:	Tuple         = []
    for i, latent in enumerate(UpperCAmelCase__	):
       lowercase__						:	Optional[int]         = self.renderer.decode(
           latent[None, :] ,		UpperCAmelCase__ ,		size=UpperCAmelCase__ ,		ray_batch_size=4_096 ,		n_coarse_samples=64 ,		n_fine_samples=128 ,		)
       images.append(UpperCAmelCase__	)

    lowercase__						:	Optional[int]         = torch.stack(UpperCAmelCase__	)

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

    lowercase__						:	str         = images.cpu().numpy()

    if output_type == "pil":
       lowercase__						:	str         = [self.numpy_to_pil(UpperCAmelCase__	) 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=UpperCAmelCase__	)










from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


a    =       {'configuration_nat': ['NAT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'NatConfig']}


try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 a    =       [
     'NAT_PRETRAINED_MODEL_ARCHIVE_LIST',
     'NatForImageClassification',
     'NatModel',
     'NatPreTrainedModel',
     'NatBackbone',
 ]

if TYPE_CHECKING:
 from .configuration_nat import NAT_PRETRAINED_CONFIG_ARCHIVE_MAP, NatConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_nat import (
      NAT_PRETRAINED_MODEL_ARCHIVE_LIST,
      NatBackbone,
      NatForImageClassification,
      NatModel,
      NatPreTrainedModel,
  )

else:
 import sys

 a    =       _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)


