






"""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											=     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  lowercase_     (_UpperCAmelCase  ):
      A__						:		Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]







class  lowercase_     (_UpperCAmelCase  ):






      def __init__(     self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  )						->List[Any]:







        '''simple docstring'''


        super().__init__()

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






      def       lowerCamelCase__     (     self  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_  ,  a_						)						->int:







        '''simple docstring'''


        if latents is None:
          _a					      =						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					      =						latents.to(a_						)

        _a					      =						latents * scheduler.init_noise_sigma
        return latents






      def       lowerCamelCase__     (     self  ,  a_=0						)						->List[str]:







        '''simple docstring'''


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

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

        _a					      =						[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  ,  a_=0						)						->List[Any]:







        '''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					      =						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					      =						None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
          _a      ,						_a					      =						cpu_offload_with_hook(a_  ,  a_  ,  prev_module_hook=a_						)

        if self.safety_checker is not None:
          _a      ,						_a					      =						cpu_offload_with_hook(self.safety_checker  ,  a_  ,  prev_module_hook=a_						)

        # We'll offload the last model manually.
        _a					      =						hook






      @property
      def       lowerCamelCase__     (     self						)						->List[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(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  ,  a_  ,  a_  ,  a_  ,  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					      =						0
        # get prompt text embeddings
        _a					      =						self.tokenizer(
            a_  ,  padding="max_length"  ,  max_length=self.tokenizer.model_max_length  ,  truncation=a_  ,  return_tensors="pt"  ,  )
        _a					      =						text_inputs.input_ids
        _a					      =						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					      =						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					      =						self.text_encoder(text_input_ids.to(a_						)						)
        _a					      =						text_encoder_output.text_embeds

        _a					      =						prompt_embeds.repeat_interleave(a_  ,  dim=0						)
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        _a					      =						prompt_embeds / torch.linalg.norm(a_  ,  dim=-1  ,  keepdim=a_						)

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

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

        return prompt_embeds






      @torch.no_grad()
      @replace_example_docstring(a_						)
      def __call__(     self  ,  a_  ,  a_ = 1  ,  a_ = 2_5  ,  a_ = None  ,  a_ = None  ,  a_ = 4.0  ,  a_ = 6_4  ,  a_ = "pil"  ,  a_ = True  ,  )						->Tuple:







        '''simple docstring'''


        if isinstance(a_  ,  a_						):
          _a					      =						1
        elif isinstance(a_  ,  a_						):
          _a					      =						len(a_						)
        else:
          raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(a_						)}'''						)

        _a					      =						self._execution_device

        _a					      =						batch_size * num_images_per_prompt

        _a					      =						guidance_scale > 1.0
        _a					      =						self._encode_prompt(a_  ,  a_  ,  a_  ,  a_						)

        # prior

        self.scheduler.set_timesteps(a_  ,  device=a_						)
        _a					      =						self.scheduler.timesteps

        _a					      =						self.prior.config.num_embeddings
        _a					      =						self.prior.config.embedding_dim

        _a					      =						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					      =						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					      =						torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
          _a					      =						self.scheduler.scale_model_input(a_  ,  a_						)

          _a					      =						self.prior(
              a_  ,  timestep=a_  ,  proj_embedding=a_  ,  ).predicted_image_embedding

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

          _a					      =						self.scheduler.step(
              a_  ,  timestep=a_  ,  sample=a_  ,  ).prev_sample

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

        _a					      =						[]
        for i, latent in enumerate(a_						):
          _a					      =						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					      =						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					      =						images.cpu().numpy()

        if output_type == "pil":
          _a					      =						[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 argparse

import torch

from transformers import ImageGPTConfig, ImageGPTForCausalLM, load_tf_weights_in_imagegpt
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging


logging.set_verbosity_info()






def 							lowerCAmelCase			(   UpperCamelCase_:				Dict  ,			UpperCamelCase_:				Dict  ,			UpperCamelCase_:				Any       )							->				Tuple:







  '''simple docstring'''







  _a					      =						{"small": (512, 8, 24), "medium": (1024, 8, 36), "large": (1536, 16, 48)}
  _a      ,						_a      ,						_a					      =						MODELS[model_size]  # set model hyperparameters
  _a					      =						ImageGPTConfig(n_embd=UpperCamelCase_  ,			n_layer=UpperCamelCase_  ,			n_head=UpperCamelCase_       )
  _a					      =						ImageGPTForCausalLM(UpperCamelCase_       )

  # Load weights from numpy
  load_tf_weights_in_imagegpt(UpperCamelCase_  ,			UpperCamelCase_  ,			UpperCamelCase_       )

  # Save pytorch-model
  _a					      =						pytorch_dump_folder_path + "/" + WEIGHTS_NAME
  _a					      =						pytorch_dump_folder_path + "/" + CONFIG_NAME
  print(f'''Save PyTorch model to {pytorch_weights_dump_path}'''       )
  torch.save(model.state_dict()  ,			UpperCamelCase_       )
  print(f'''Save configuration file to {pytorch_config_dump_path}'''       )
  with open(UpperCamelCase_  ,			"w"  ,			encoding="utf-8"       ) as f:
    f.write(config.to_json_string()       )


if __name__ == "__main__":
     UpperCamelCase											=     argparse.ArgumentParser()
     # Required parameters
     parser.add_argument(
         """--imagegpt_checkpoint_path""",
         default=None,
         type=str,
         required=True,
         help="""Path to the TensorFlow checkpoint path.""",
     )
     parser.add_argument(
         """--model_size""",
         default=None,
         type=str,
         required=True,
         help="""Size of the model (can be either 'small', 'medium' or 'large').""",
     )
     parser.add_argument(
         """--pytorch_dump_folder_path""", default=None, type=str, required=True, help="""Path to the output PyTorch model."""
     )
     UpperCamelCase											=     parser.parse_args()
     convert_imagegpt_checkpoint_to_pytorch(
         args.imagegpt_checkpoint_path, args.model_size, args.pytorch_dump_folder_path
     )


