






"""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


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

_UpperCamelCase				:    str     =						'\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       ):
    __magic_name__         =     42






class 						snake_case  (  UpperCAmelCase       ):





    def __init__(							self	:					Optional[int]				,		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 				lowerCamelCase__      (							self	:					int				,		A	:					List[str]				,		A	:					Union[str, Any]				,		A	:					str				,		A	:					Union[str, Any]				,		A	:					Any				,		A	:					List[Any]			):


      '''simple docstring'''




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

      a     :			Any				=   latents * scheduler.init_noise_sigma
      return latents





    def 				lowerCamelCase__      (							self	:					List[Any]				,		A	:					Optional[int]=0			):


      '''simple docstring'''




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

      a     :			Any				=   torch.device(F'''cuda:{gpu_id}'''			)

      a     :			Optional[int]				=   [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	:					Optional[Any]				,		A	:					int=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.'			)

      a     :			str				=   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     :			Any				=   None
      for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
        a,     a     :			Optional[Any]				=   cpu_offload_with_hook(A				,		A				,		prev_module_hook=A			)

      if self.safety_checker is not None:
        a,     a     :			Any				=   cpu_offload_with_hook(self.safety_checker				,		A				,		prev_module_hook=A			)

      # We'll offload the last model manually.
      a     :			List[str]				=   hook





    @property
    def 				lowerCamelCase__      (							self	:					List[str]			):


      '''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	:					int				,		A	:					List[Any]				,		A	:					Tuple				,		A	:					Optional[int]				,		A	:					int				,		):


      '''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     :			Optional[int]				=   0
      # get prompt text embeddings
      a     :			List[Any]				=   self.tokenizer(
          A				,		padding='max_length'				,		max_length=self.tokenizer.model_max_length				,		truncation=A				,		return_tensors='pt'				,		)
      a     :			Optional[Any]				=   text_inputs.input_ids
      a     :			Dict				=   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     :			Dict				=   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     :			Tuple				=   self.text_encoder(text_input_ids.to(A			)			)
      a     :			int				=   text_encoder_output.text_embeds

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

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

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

      return prompt_embeds





    @torch.no_grad()
    @replace_example_docstring(A			)
    def __call__(							self	:					Optional[int]				,		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			):
        a     :			Tuple				=   1
      elif isinstance(A				,		A			):
        a     :			str				=   len(A			)
      else:
        raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A			)}'''			)

      a     :			Optional[int]				=   self._execution_device

      a     :			Union[str, Any]				=   batch_size * num_images_per_prompt

      a     :			int				=   guidance_scale > 1.0
      a     :			List[str]				=   self._encode_prompt(A				,		A				,		A				,		A			)

      # prior

      self.scheduler.set_timesteps(A				,		device=A			)
      a     :			List[Any]				=   self.scheduler.timesteps

      a     :			int				=   self.prior.config.num_embeddings
      a     :			Union[str, Any]				=   self.prior.config.embedding_dim

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

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

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

        a     :			int				=   self.scheduler.step(
            A				,		timestep=A				,		sample=A				,		).prev_sample

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

      a     :			List[Any]				=   []
      for i, latent in enumerate(A			):
        a     :			List[Any]				=   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     :			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}'''			)

      a     :			Optional[Any]				=   images.cpu().numpy()

      if output_type == "pil":
        a     :			Union[str, 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			)












"""simple docstring"""


import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


_UpperCamelCase				:    Optional[int]     =						logging.get_logger(__name__)






class 						snake_case  (  UpperCAmelCase       ):
    __magic_name__         =     '''speech-encoder-decoder'''
    __magic_name__         =     True





    def __init__(							self	:					Optional[Any]				,		**A	:					List[Any]			):


      '''simple docstring'''




      super().__init__(**A			)
      if "encoder" not in kwargs or "decoder" not in kwargs:
        raise ValueError(
            F'''A configuraton of type {self.model_type} cannot be instantiated because not both `encoder` and'''
            F''' `decoder` sub-configurations are passed, but only {kwargs}'''			)

      a     :			Optional[int]				=   kwargs.pop('encoder'			)
      a     :			Any				=   encoder_config.pop('model_type'			)
      a     :			Optional[Any]				=   kwargs.pop('decoder'			)
      a     :			str				=   decoder_config.pop('model_type'			)

      a     :			Tuple				=   AutoConfig.for_model(A				,		**A			)
      a     :			Dict				=   AutoConfig.for_model(A				,		**A			)
      a     :			Optional[Any]				=   True





    @classmethod
    def 				lowerCamelCase__      (							cls	:					List[Any]				,		A	:					PretrainedConfig				,		A	:					PretrainedConfig				,		**A	:					str			):


      '''simple docstring'''




      logger.info('Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'			)
      a     :			Any				=   True
      a     :			List[str]				=   True

      return cls(encoder=encoder_config.to_dict()				,		decoder=decoder_config.to_dict()				,		**A			)





    def 				lowerCamelCase__      (							self	:					Optional[int]			):


      '''simple docstring'''




      a     :			List[Any]				=   copy.deepcopy(self.__dict__			)
      a     :			int				=   self.encoder.to_dict()
      a     :			Optional[int]				=   self.decoder.to_dict()
      a     :			Any				=   self.__class__.model_type
      return output




