


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 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''
     UpperCAmelCase_         =  42




class 						UpperCAmelCase__   (      A_		):



     '''simple docstring'''




     def __init__( self       :       str	,      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   lowerCAmelCase_   ( self       :       Union[str, Any]	,      UpperCamelCase       :       Optional[Any]	,      UpperCamelCase       :       str	,      UpperCamelCase       :       Optional[Any]	,      UpperCamelCase       :       Union[str, Any]	,      UpperCamelCase       :       Any	,      UpperCamelCase       :       Dict		):





            """simple docstring"""



            if latents is None:
                   _lowercase					:				int           =			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					:				Optional[int]           =			latents.to(UpperCamelCase		)

            _lowercase					:				str           =			latents * scheduler.init_noise_sigma
            return latents




     def   lowerCAmelCase_   ( self       :       Optional[Any]	,      UpperCamelCase       :       List[str]=0		):





            """simple docstring"""



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

            _lowercase					:				Union[str, Any]           =			torch.device(F'cuda:{gpu_id}'		)

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




     def   lowerCAmelCase_   ( self       :       Optional[Any]	,      UpperCamelCase       :       Tuple=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					:				List[Any]           =			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					:				Any           =			None
            for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
                   _lowercase       ,	_lowercase					:				Tuple           =			cpu_offload_with_hook(UpperCamelCase	,      UpperCamelCase	,      prev_module_hook=UpperCamelCase		)

            if self.safety_checker is not None:
                   _lowercase       ,	_lowercase					:				Dict           =			cpu_offload_with_hook(self.safety_checker	,      UpperCamelCase	,      prev_module_hook=UpperCamelCase		)

            # We'll offload the last model manually.
            _lowercase					:				str           =			hook




     @property
     def   lowerCAmelCase_   ( self       :       Dict		):





            """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   lowerCAmelCase_   ( self       :       Union[str, Any]	,      UpperCamelCase       :       Dict	,      UpperCamelCase       :       Union[str, Any]	,      UpperCamelCase       :       Dict	,      UpperCamelCase       :       Tuple	,      ):





            """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					:				Dict           =			0
            # get prompt text embeddings
            _lowercase					:				Optional[int]           =			self.tokenizer(
                UpperCamelCase	,      padding='''max_length'''	,      max_length=self.tokenizer.model_max_length	,      truncation=UpperCamelCase	,      return_tensors='''pt'''	,      )
            _lowercase					:				int           =			text_inputs.input_ids
            _lowercase					:				Union[str, Any]           =			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					:				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}'		)

            _lowercase					:				str           =			self.text_encoder(text_input_ids.to(UpperCamelCase		)		)
            _lowercase					:				str           =			text_encoder_output.text_embeds

            _lowercase					:				Dict           =			prompt_embeds.repeat_interleave(UpperCamelCase	,      dim=0		)
            # in Shap-E it normalize the prompt_embeds and then later rescale it
            _lowercase					:				int           =			prompt_embeds / torch.linalg.norm(UpperCamelCase	,      dim=-1	,      keepdim=UpperCamelCase		)

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

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

            return prompt_embeds




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

            _lowercase					:				Optional[Any]           =			self._execution_device

            _lowercase					:				List[Any]           =			batch_size * num_images_per_prompt

            _lowercase					:				List[str]           =			guidance_scale > 1.0
            _lowercase					:				List[str]           =			self._encode_prompt(UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase		)

            # prior

            self.scheduler.set_timesteps(UpperCamelCase	,      device=UpperCamelCase		)
            _lowercase					:				Any           =			self.scheduler.timesteps

            _lowercase					:				int           =			self.prior.config.num_embeddings
            _lowercase					:				Any           =			self.prior.config.embedding_dim

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

                   _lowercase					:				Any           =			self.prior(
                       UpperCamelCase	,      timestep=UpperCamelCase	,      proj_embedding=UpperCamelCase	,      ).predicted_image_embedding

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

                   _lowercase					:				Union[str, Any]           =			self.scheduler.step(
                       UpperCamelCase	,      timestep=UpperCamelCase	,      sample=UpperCamelCase	,      ).prev_sample

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

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

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

            if output_type == "pil":
                   _lowercase					:				List[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		)



import os
from pathlib import Path
from typing import Dict, List

import fire
import torch

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.utils.logging import get_logger


UpperCamelCase__				       =			get_logger(__name__)

def   UpperCamelCase__   (    UpperCAmelCase_    ,     UpperCAmelCase_			)						->							List[str]:




       '''simple docstring'''






       if text.startswith(UpperCAmelCase_			):
              return text[len(UpperCAmelCase_			) :]
       return text  # or whatever

def   UpperCamelCase__   (    UpperCAmelCase_			)						->							Optional[int]:




       '''simple docstring'''






       return {remove_prefix(UpperCAmelCase_    ,     '''model.'''			): v for k, v in sd.items()}

def   UpperCamelCase__   (    UpperCAmelCase_			)						->							Any:




       '''simple docstring'''






       _lowercase					:				Optional[int]           =			{}
       for k in state_dicts[0].keys():
              _lowercase					:				Tuple           =			[sd[k] for sd in state_dicts]
              _lowercase					:				Union[str, Any]           =			sum(UpperCAmelCase_			) / len(UpperCAmelCase_			)
              assert isinstance(UpperCAmelCase_    ,     torch.Tensor			)
              _lowercase					:				Union[str, Any]           =			new_t
       return new_sd

def   UpperCamelCase__   (    UpperCAmelCase_    ,     UpperCAmelCase_    ,     UpperCAmelCase_			)						->							None:




       '''simple docstring'''






       _lowercase					:				List[str]           =			AutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_			)
       if os.path.isfile(UpperCAmelCase_			):
              _lowercase					:				Optional[Any]           =			[pl_ckpt_path]
       else:
              assert os.path.isdir(UpperCAmelCase_			)
              _lowercase					:				List[str]           =			list(Path(UpperCAmelCase_			).glob('''*.ckpt'''			)			)
              assert ckpt_files, F'could not find any ckpt files inside the {pl_ckpt_path} directory'

       if len(UpperCAmelCase_			) > 1:
              logger.info(F'averaging the weights of {ckpt_files}'			)

       _lowercase					:				List[Any]           =			[sanitize(torch.load(UpperCAmelCase_    ,     map_location='''cpu'''			)['''state_dict''']			) for x in ckpt_files]
       _lowercase					:				Optional[Any]           =			average_state_dicts(UpperCAmelCase_			)

       _lowercase       ,	_lowercase					:				str           =			hf_model.load_state_dict(UpperCAmelCase_    ,     strict=UpperCAmelCase_			)
       assert not missing, F'missing keys: {missing}'
       hf_model.save_pretrained(UpperCAmelCase_			)
       try:
              _lowercase					:				Union[str, Any]           =			AutoTokenizer.from_pretrained(UpperCAmelCase_			)
              tok.save_pretrained(UpperCAmelCase_			)
       except Exception:
              pass
              # dont copy tokenizer if cant


if __name__ == "__main__":
   fire.Fire(convert_pl_to_hf)