import functools
import math

import flax.linen as nn
import jax
import jax.numpy as jnp







def 	UpperCAmelCase       (		lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_ = 4_0_9_6       )	->	int:
     a  :    Dict				=						key.shape[-3:]
     a  :    Tuple				=						value.shape[-1]
     a  :    int				=						min(lowerCAmelCase_						,      lowerCAmelCase_       )
     a  :    Optional[int]				=						query / jnp.sqrt(lowerCAmelCase_       )

     @functools.partial(jax.checkpoint						,      prevent_cse=lowerCAmelCase_       )
     def summarize_chunk(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_       ):
          a  :    Dict				=						jnp.einsum('''...qhd,...khd->...qhk'''						,      lowerCAmelCase_						,      lowerCAmelCase_						,      precision=lowerCAmelCase_       )

          a  :    Tuple				=						jnp.max(lowerCAmelCase_						,      axis=-1						,      keepdims=lowerCAmelCase_       )
          a  :    Optional[int]				=						jax.lax.stop_gradient(lowerCAmelCase_       )
          a  :    int				=						jnp.exp(attn_weights - max_score       )

          a  :    Optional[Any]				=						jnp.einsum('''...vhf,...qhv->...qhf'''						,      lowerCAmelCase_						,      lowerCAmelCase_						,      precision=lowerCAmelCase_       )
          a  :    Union[str, Any]				=						jnp.einsum('''...qhk->...qh'''						,      lowerCAmelCase_       )

          return (exp_values, exp_weights.sum(axis=-1       ), max_score)

     def chunk_scanner(lowerCAmelCase_       ):
          # julienne key array
          a  :    Optional[Any]				=						jax.lax.dynamic_slice(
              operand=lowerCAmelCase_						,      start_indices=[0] * (key.ndim - 3) + [chunk_idx, 0, 0]						,      slice_sizes=list(key.shape[:-3]       ) + [key_chunk_size, num_heads, k_features]						,      )

          # julienne value array
          a  :    Optional[int]				=						jax.lax.dynamic_slice(
              operand=lowerCAmelCase_						,      start_indices=[0] * (value.ndim - 3) + [chunk_idx, 0, 0]						,      slice_sizes=list(value.shape[:-3]       ) + [key_chunk_size, num_heads, v_features]						,      )

          return summarize_chunk(lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_       )

     a  :    Optional[Any]				=						jax.lax.map(f=lowerCAmelCase_						,      xs=jnp.arange(0						,      lowerCAmelCase_						,      lowerCAmelCase_       )       )

     a  :    List[Any]				=						jnp.max(lowerCAmelCase_						,      axis=0						,      keepdims=lowerCAmelCase_       )
     a  :    Optional[int]				=						jnp.exp(chunk_max - global_max       )

     chunk_values *= jnp.expand_dims(lowerCAmelCase_						,      axis=-1       )
     chunk_weights *= max_diffs

     a  :    Any				=						chunk_values.sum(axis=0       )
     a  :    Optional[int]				=						jnp.expand_dims(lowerCAmelCase_						,      -1       ).sum(axis=0       )

     return all_values / all_weights







def 	UpperCAmelCase       (		lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_						,      lowerCAmelCase_=jax.lax.Precision.HIGHEST						,      lowerCAmelCase_ = 1_0_2_4						,      lowerCAmelCase_ = 4_0_9_6       )	->	Dict:
     a  :    str				=						query.shape[-3:]

     def chunk_scanner(lowerCAmelCase_						,      lowerCAmelCase_       ):
          # julienne query array
          a  :    Optional[int]				=						jax.lax.dynamic_slice(
              operand=lowerCAmelCase_						,      start_indices=([0] * (query.ndim - 3)) + [chunk_idx, 0, 0]						,      slice_sizes=list(query.shape[:-3]       ) + [min(lowerCAmelCase_						,      lowerCAmelCase_       ), num_heads, q_features]						,      )

          return (
              chunk_idx + query_chunk_size,  # unused ignore it
              _query_chunk_attention(
                  query=lowerCAmelCase_						,      key=lowerCAmelCase_						,      value=lowerCAmelCase_						,      precision=lowerCAmelCase_						,      key_chunk_size=lowerCAmelCase_       ),
          )

     a  :    Any				=						jax.lax.scan(
         f=lowerCAmelCase_						,      init=0						,      xs=lowerCAmelCase_						,      length=math.ceil(num_q / query_chunk_size       )       )

     return jnp.concatenate(lowerCAmelCase_						,      axis=-3       )  # fuse the chunked result back






class 							_SCREAMING_SNAKE_CASE(   nn.Module	):
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int 			=   8
   UpperCamelCase_				:						int 			=   64
   UpperCamelCase_				:						float 			=   0.0
   UpperCamelCase_				:						bool 			=   False
   UpperCamelCase_				:						jnp.dtype 			=   jnp.floataa
   def _lowercase(    self    )	->Any:
        a  :    Union[str, Any]				=						self.dim_head * self.heads
        a  :    Dict				=						self.dim_head**-0.5

        # Weights were exported with old names {to_q, to_k, to_v, to_out}
        a  :    Optional[int]				=						nn.Dense(lowerCAmelCase_							,     use_bias=lowerCAmelCase_							,     dtype=self.dtype							,     name='''to_q'''    )
        a  :    Tuple				=						nn.Dense(lowerCAmelCase_							,     use_bias=lowerCAmelCase_							,     dtype=self.dtype							,     name='''to_k'''    )
        a  :    str				=						nn.Dense(lowerCAmelCase_							,     use_bias=lowerCAmelCase_							,     dtype=self.dtype							,     name='''to_v'''    )

        a  :    Any				=						nn.Dense(self.query_dim							,     dtype=self.dtype							,     name='''to_out_0'''    )
        a  :    List[Any]				=						nn.Dropout(rate=self.dropout    )
   def _lowercase(    self							,     lowerCAmelCase_    )	->Tuple:
        a  :    Tuple				=						tensor.shape
        a  :    List[str]				=						self.heads
        a  :    Any				=						tensor.reshape(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     dim // head_size    )
        a  :    Tuple				=						jnp.transpose(lowerCAmelCase_							,     (0, 2, 1, 3)    )
        a  :    List[Any]				=						tensor.reshape(batch_size * head_size							,     lowerCAmelCase_							,     dim // head_size    )
        return tensor
   def _lowercase(    self							,     lowerCAmelCase_    )	->Dict:
        a  :    Any				=						tensor.shape
        a  :    List[Any]				=						self.heads
        a  :    Optional[Any]				=						tensor.reshape(batch_size // head_size							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        a  :    int				=						jnp.transpose(lowerCAmelCase_							,     (0, 2, 1, 3)    )
        a  :    Union[str, Any]				=						tensor.reshape(batch_size // head_size							,     lowerCAmelCase_							,     dim * head_size    )
        return tensor


   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_=None							,     lowerCAmelCase_=True    )	->Tuple:
        a  :    str				=						hidden_states if context is None else context

        a  :    Optional[Any]				=						self.query(lowerCAmelCase_    )
        a  :    Dict				=						self.key(lowerCAmelCase_    )
        a  :    List[str]				=						self.value(lowerCAmelCase_    )

        a  :    str				=						self.reshape_heads_to_batch_dim(lowerCAmelCase_    )
        a  :    Optional[Any]				=						self.reshape_heads_to_batch_dim(lowerCAmelCase_    )
        a  :    List[str]				=						self.reshape_heads_to_batch_dim(lowerCAmelCase_    )

        if self.use_memory_efficient_attention:
             a  :    Tuple				=						query_states.transpose(1							,     0							,     2    )
             a  :    Union[str, Any]				=						key_states.transpose(1							,     0							,     2    )
             a  :    List[str]				=						value_states.transpose(1							,     0							,     2    )

             # this if statement create a chunk size for each layer of the unet
             # the chunk size is equal to the query_length dimension of the deepest layer of the unet

             a  :    Optional[Any]				=						query_states.shape[-3]
             if flatten_latent_dim % 64 == 0:
                  a  :    str				=						int(flatten_latent_dim / 64    )
             elif flatten_latent_dim % 16 == 0:
                  a  :    str				=						int(flatten_latent_dim / 16    )
             elif flatten_latent_dim % 4 == 0:
                  a  :    Optional[Any]				=						int(flatten_latent_dim / 4    )
             else:
                  a  :    Tuple				=						int(lowerCAmelCase_    )

             a  :    Union[str, Any]				=						jax_memory_efficient_attention(
                 lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     query_chunk_size=lowerCAmelCase_							,     key_chunk_size=40_96 * 4    )

             a  :    List[str]				=						hidden_states.transpose(1							,     0							,     2    )
        else:
             # compute attentions
             a  :    Union[str, Any]				=						jnp.einsum('''b i d, b j d->b i j'''							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             a  :    List[Any]				=						attention_scores * self.scale
             a  :    List[str]				=						nn.softmax(lowerCAmelCase_							,     axis=2    )

             # attend to values
             a  :    List[str]				=						jnp.einsum('''b i j, b j d -> b i d'''							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        a  :    List[Any]				=						self.reshape_batch_dim_to_heads(lowerCAmelCase_    )
        a  :    List[Any]				=						self.proj_attn(lowerCAmelCase_    )
        return self.dropout_layer(lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )






class 							_SCREAMING_SNAKE_CASE(   nn.Module	):
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int
   UpperCamelCase_				:						float 			=   0.0
   UpperCamelCase_				:						bool 			=   False
   UpperCamelCase_				:						jnp.dtype 			=   jnp.floataa
   UpperCamelCase_				:						bool 			=   False
   def _lowercase(    self    )	->Union[str, Any]:
        # self attention (or cross_attention if only_cross_attention is True)
        a  :    List[Any]				=						FlaxAttention(
            self.dim							,     self.n_heads							,     self.d_head							,     self.dropout							,     self.use_memory_efficient_attention							,     dtype=self.dtype    )
        # cross attention
        a  :    str				=						FlaxAttention(
            self.dim							,     self.n_heads							,     self.d_head							,     self.dropout							,     self.use_memory_efficient_attention							,     dtype=self.dtype    )
        a  :    List[Any]				=						FlaxFeedForward(dim=self.dim							,     dropout=self.dropout							,     dtype=self.dtype    )
        a  :    int				=						nn.LayerNorm(epsilon=1e-5							,     dtype=self.dtype    )
        a  :    Optional[Any]				=						nn.LayerNorm(epsilon=1e-5							,     dtype=self.dtype    )
        a  :    int				=						nn.LayerNorm(epsilon=1e-5							,     dtype=self.dtype    )
        a  :    str				=						nn.Dropout(rate=self.dropout    )


   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_=True    )	->Dict:
        # self attention
        a  :    int				=						hidden_states
        if self.only_cross_attention:
             a  :    Optional[Any]				=						self.attna(self.norma(lowerCAmelCase_    )							,     lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )
        else:
             a  :    str				=						self.attna(self.norma(lowerCAmelCase_    )							,     deterministic=lowerCAmelCase_    )
        a  :    List[str]				=						hidden_states + residual

        # cross attention
        a  :    int				=						hidden_states
        a  :    Union[str, Any]				=						self.attna(self.norma(lowerCAmelCase_    )							,     lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )
        a  :    Dict				=						hidden_states + residual

        # feed forward
        a  :    int				=						hidden_states
        a  :    Tuple				=						self.ff(self.norma(lowerCAmelCase_    )							,     deterministic=lowerCAmelCase_    )
        a  :    Tuple				=						hidden_states + residual

        return self.dropout_layer(lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )






class 							_SCREAMING_SNAKE_CASE(   nn.Module	):
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int
   UpperCamelCase_				:						int 			=   1
   UpperCamelCase_				:						float 			=   0.0
   UpperCamelCase_				:						bool 			=   False
   UpperCamelCase_				:						bool 			=   False
   UpperCamelCase_				:						jnp.dtype 			=   jnp.floataa
   UpperCamelCase_				:						bool 			=   False
   def _lowercase(    self    )	->Tuple:
        a  :    str				=						nn.GroupNorm(num_groups=32							,     epsilon=1e-5    )

        a  :    Union[str, Any]				=						self.n_heads * self.d_head
        if self.use_linear_projection:
             a  :    str				=						nn.Dense(lowerCAmelCase_							,     dtype=self.dtype    )
        else:
             a  :    List[Any]				=						nn.Conv(
                 lowerCAmelCase_							,     kernel_size=(1, 1)							,     strides=(1, 1)							,     padding='''VALID'''							,     dtype=self.dtype							,     )

        a  :    Optional[int]				=						[
            FlaxBasicTransformerBlock(
                lowerCAmelCase_							,     self.n_heads							,     self.d_head							,     dropout=self.dropout							,     only_cross_attention=self.only_cross_attention							,     dtype=self.dtype							,     use_memory_efficient_attention=self.use_memory_efficient_attention							,     )
            for _ in range(self.depth    )
        ]

        if self.use_linear_projection:
             a  :    Any				=						nn.Dense(lowerCAmelCase_							,     dtype=self.dtype    )
        else:
             a  :    Optional[int]				=						nn.Conv(
                 lowerCAmelCase_							,     kernel_size=(1, 1)							,     strides=(1, 1)							,     padding='''VALID'''							,     dtype=self.dtype							,     )

        a  :    Tuple				=						nn.Dropout(rate=self.dropout    )


   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_=True    )	->List[str]:
        a  :    Optional[Any]				=						hidden_states.shape
        a  :    Dict				=						hidden_states
        a  :    int				=						self.norm(lowerCAmelCase_    )
        if self.use_linear_projection:
             a  :    Tuple				=						hidden_states.reshape(lowerCAmelCase_							,     height * width							,     lowerCAmelCase_    )
             a  :    List[Any]				=						self.proj_in(lowerCAmelCase_    )
        else:
             a  :    Tuple				=						self.proj_in(lowerCAmelCase_    )
             a  :    int				=						hidden_states.reshape(lowerCAmelCase_							,     height * width							,     lowerCAmelCase_    )

        for transformer_block in self.transformer_blocks:
             a  :    List[str]				=						transformer_block(lowerCAmelCase_							,     lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )

        if self.use_linear_projection:
             a  :    List[str]				=						self.proj_out(lowerCAmelCase_    )
             a  :    List[str]				=						hidden_states.reshape(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
        else:
             a  :    Dict				=						hidden_states.reshape(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )
             a  :    int				=						self.proj_out(lowerCAmelCase_    )

        a  :    List[str]				=						hidden_states + residual
        return self.dropout_layer(lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )






class 							_SCREAMING_SNAKE_CASE(   nn.Module	):
   UpperCamelCase_				:						int
   UpperCamelCase_				:						float 			=   0.0
   UpperCamelCase_				:						jnp.dtype 			=   jnp.floataa
   def _lowercase(    self    )	->Union[str, Any]:
        # The second linear layer needs to be called
        # net_2 for now to match the index of the Sequential layer
        a  :    Tuple				=						FlaxGEGLU(self.dim							,     self.dropout							,     self.dtype    )
        a  :    Optional[Any]				=						nn.Dense(self.dim							,     dtype=self.dtype    )


   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_=True    )	->List[Any]:
        a  :    Union[str, Any]				=						self.net_a(lowerCAmelCase_							,     deterministic=lowerCAmelCase_    )
        a  :    Tuple				=						self.net_a(lowerCAmelCase_    )
        return hidden_states






class 							_SCREAMING_SNAKE_CASE(   nn.Module	):
   UpperCamelCase_				:						int
   UpperCamelCase_				:						float 			=   0.0
   UpperCamelCase_				:						jnp.dtype 			=   jnp.floataa
   def _lowercase(    self    )	->List[str]:
        a  :    int				=						self.dim * 4
        a  :    int				=						nn.Dense(inner_dim * 2							,     dtype=self.dtype    )
        a  :    int				=						nn.Dropout(rate=self.dropout    )


   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_=True    )	->Dict:
        a  :    Union[str, Any]				=						self.proj(lowerCAmelCase_    )
        a  :    int				=						jnp.split(lowerCAmelCase_							,     2							,     axis=2    )
        return self.dropout_layer(hidden_linear * nn.gelu(lowerCAmelCase_    )							,     deterministic=lowerCAmelCase_    )
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							   =      """
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = \"a shark\"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"shark_3d.gif\")
        ```
"""






@dataclass
class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   UpperCamelCase_				:						Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class 							_SCREAMING_SNAKE_CASE(   snake_case__	):
   def __init__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->int:
        super().__init__()

        self.register_modules(
            prior=lowerCAmelCase_							,     text_encoder=lowerCAmelCase_							,     tokenizer=lowerCAmelCase_							,     scheduler=lowerCAmelCase_							,     renderer=lowerCAmelCase_							,     )
   def _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )	->str:
        if latents is None:
             a  :    List[str]				=						randn_tensor(lowerCAmelCase_							,     generator=lowerCAmelCase_							,     device=lowerCAmelCase_							,     dtype=lowerCAmelCase_    )
        else:
             if latents.shape != shape:
                  raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""    )
             a  :    str				=						latents.to(lowerCAmelCase_    )

        a  :    Tuple				=						latents * scheduler.init_noise_sigma
        return latents
   def _lowercase(    self							,     lowerCAmelCase_=0    )	->List[Any]:
        if is_accelerate_available():
             from accelerate import cpu_offload
        else:
             raise ImportError('''Please install accelerate via `pip install accelerate`'''    )

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

        a  :    Union[str, Any]				=						[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                  cpu_offload(lowerCAmelCase_							,     lowerCAmelCase_    )
   def _lowercase(    self							,     lowerCAmelCase_=0    )	->str:
        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  :    Union[str, Any]				=						torch.device(F"""cuda:{gpu_id}"""    )

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

        a  :    Dict				=						None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
             a			,							a  :    str				=						cpu_offload_with_hook(lowerCAmelCase_							,     lowerCAmelCase_							,     prev_module_hook=lowerCAmelCase_    )

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

        # We'll offload the last model manually.
        a  :    Any				=						hook
   @property
   def _lowercase(    self    )	->Any:
        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(lowerCAmelCase_							,     '''_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 _lowercase(    self							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     )	->Optional[Any]:
        len(lowerCAmelCase_    ) if isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        a  :    Dict				=						0
        # get prompt text embeddings
        a  :    Any				=						self.tokenizer(
            lowerCAmelCase_							,     padding='''max_length'''							,     max_length=self.tokenizer.model_max_length							,     truncation=lowerCAmelCase_							,     return_tensors='''pt'''							,     )
        a  :    List[str]				=						text_inputs.input_ids
        a  :    Union[str, Any]				=						self.tokenizer(lowerCAmelCase_							,     padding='''longest'''							,     return_tensors='''pt'''    ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Union[str, 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}"""    )

        a  :    Optional[int]				=						self.text_encoder(text_input_ids.to(lowerCAmelCase_    )    )
        a  :    Optional[Any]				=						text_encoder_output.text_embeds

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

        if do_classifier_free_guidance:
             a  :    Optional[int]				=						torch.zeros_like(lowerCAmelCase_    )

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

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

        return prompt_embeds


   @torch.no_grad()
   @replace_example_docstring(lowerCAmelCase_    )
   def __call__(    self							,     lowerCAmelCase_							,     lowerCAmelCase_ = 1							,     lowerCAmelCase_ = 25							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = None							,     lowerCAmelCase_ = 4.0							,     lowerCAmelCase_ = 64							,     lowerCAmelCase_ = "pil"							,     lowerCAmelCase_ = True							,     )	->Dict:

        if isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Tuple				=						1
        elif isinstance(lowerCAmelCase_							,     lowerCAmelCase_    ):
             a  :    Dict				=						len(lowerCAmelCase_    )
        else:
             raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_    )}"""    )

        a  :    Union[str, Any]				=						self._execution_device

        a  :    List[str]				=						batch_size * num_images_per_prompt

        a  :    Optional[int]				=						guidance_scale > 1.0
        a  :    Union[str, Any]				=						self._encode_prompt(lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_							,     lowerCAmelCase_    )

        # prior

        self.scheduler.set_timesteps(lowerCAmelCase_							,     device=lowerCAmelCase_    )
        a  :    str				=						self.scheduler.timesteps

        a  :    Any				=						self.prior.config.num_embeddings
        a  :    Dict				=						self.prior.config.embedding_dim

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

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

             a  :    Union[str, Any]				=						self.prior(
                 lowerCAmelCase_							,     timestep=lowerCAmelCase_							,     proj_embedding=lowerCAmelCase_							,     ).predicted_image_embedding

             # remove the variance
             a			,							a  :    str				=						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  :    Tuple				=						noise_pred.chunk(2    )
                  a  :    Tuple				=						noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

             a  :    List[Any]				=						self.scheduler.step(
                 lowerCAmelCase_							,     timestep=lowerCAmelCase_							,     sample=lowerCAmelCase_							,     ).prev_sample

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

        a  :    int				=						[]
        for i, latent in enumerate(lowerCAmelCase_    ):
             a  :    Dict				=						self.renderer.decode(
                 latent[None, :]							,     lowerCAmelCase_							,     size=lowerCAmelCase_							,     ray_batch_size=40_96							,     n_coarse_samples=64							,     n_fine_samples=1_28							,     )
             images.append(lowerCAmelCase_    )

        a  :    Optional[Any]				=						torch.stack(lowerCAmelCase_    )

        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  :    Any				=						images.cpu().numpy()

        if output_type == "pil":
             a  :    Dict				=						[self.numpy_to_pil(lowerCAmelCase_    ) 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=lowerCAmelCase_    )