code: 
  
  
  
  """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
  
  
  _lowerCAmelCase       :      Union[str, Any]							=							logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  _lowerCAmelCase       :      Any							=							"\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_						(       _UpperCamelCase		):
  						__SCREAMING_SNAKE_CASE		:     Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]
  
  
  
  
  
  
  
  class 			UpperCAmelCase_						(       _UpperCamelCase		):
  
  
  
  						def __init__(  self  :			List[Any]  ,			A  :			PriorTransformer  ,			A  :			CLIPTextModelWithProjection  ,			A  :			CLIPTokenizer  ,			A  :			HeunDiscreteScheduler  ,			A  :			ShapERenderer  ,			):
  											super().__init__()
  
  											self.register_modules(
  											    prior=A  ,			text_encoder=A  ,			tokenizer=A  ,			scheduler=A  ,			renderer=A  ,			)
  
  
  
  						def 		snake_case_      (  self  :			int  ,			A  :			List[str]  ,			A  :			Tuple  ,			A  :			str  ,			A  :			Any  ,			A  :			str  ,			A  :			int		):
  											if latents is None:
  																_UpperCAmelCase    :			Dict              =					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}'		)
  																_UpperCAmelCase    :			List[Any]              =					latents.to(A		)
  
  											_UpperCAmelCase    :			int              =					latents * scheduler.init_noise_sigma
  											return latents
  
  
  
  						def 		snake_case_      (  self  :			Union[str, Any]  ,			A  :			str=0		):
  											if is_accelerate_available():
  																from accelerate import cpu_offload
  											else:
  																raise ImportError("Please install accelerate via `pip install accelerate`"		)
  
  											_UpperCAmelCase    :			int              =					torch.device(f'cuda:{gpu_id}'		)
  
  											_UpperCAmelCase    :			str              =					[self.text_encoder, self.prior]
  											for cpu_offloaded_model in models:
  																if cpu_offloaded_model is not None:
  																					cpu_offload(A  ,			A		)
  
  
  
  						def 		snake_case_      (  self  :			Tuple  ,			A  :			List[Any]=0		):
  											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."		)
  
  											_UpperCAmelCase    :			Any              =					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)
  
  											_UpperCAmelCase    :			List[Any]              =					None
  											for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
  																_UpperCAmelCase    :			Dict              =					cpu_offload_with_hook(A  ,			A  ,			prev_module_hook=A		)
  
  											if self.safety_checker is not None:
  																_UpperCAmelCase    :			Optional[int]              =					cpu_offload_with_hook(self.safety_checker  ,			A  ,			prev_module_hook=A		)
  
  											# We'll offload the last model manually.
  											_UpperCAmelCase    :			Any              =					hook
  
  
  
  						@property
  						def 		snake_case_      (  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(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 		snake_case_      (  self  :			List[Any]  ,			A  :			Tuple  ,			A  :			Any  ,			A  :			Optional[Any]  ,			A  :			Optional[Any]  ,			):
  											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
  											_UpperCAmelCase    :			List[Any]              =					0
  											# get prompt text embeddings
  											_UpperCAmelCase    :			str              =					self.tokenizer(
  											    A  ,			padding="max_length"  ,			max_length=self.tokenizer.model_max_length  ,			truncation=A  ,			return_tensors="pt"  ,			)
  											_UpperCAmelCase    :			Optional[int]              =					text_inputs.input_ids
  											_UpperCAmelCase    :			List[str]              =					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		):
  																_UpperCAmelCase    :			Tuple              =					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}'		)
  
  											_UpperCAmelCase    :			List[str]              =					self.text_encoder(text_input_ids.to(A		)		)
  											_UpperCAmelCase    :			Optional[Any]              =					text_encoder_output.text_embeds
  
  											_UpperCAmelCase    :			List[Any]              =					prompt_embeds.repeat_interleave(A  ,			dim=0		)
  											# in Shap-E it normalize the prompt_embeds and then later rescale it
  											_UpperCAmelCase    :			int              =					prompt_embeds / torch.linalg.norm(A  ,			dim=-1  ,			keepdim=A		)
  
  											if do_classifier_free_guidance:
  																_UpperCAmelCase    :			Dict              =					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
  																_UpperCAmelCase    :			Optional[int]              =					torch.cat([negative_prompt_embeds, prompt_embeds]		)
  
  											# Rescale the features to have unit variance
  											_UpperCAmelCase    :			int              =					math.sqrt(prompt_embeds.shape[1]		) * prompt_embeds
  
  											return prompt_embeds
  
  
  
  						@torch.no_grad()
  						@replace_example_docstring(A		)
  						def __call__(  self  :			List[str]  ,			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  ,			):
  
  											if isinstance(A  ,			A		):
  																_UpperCAmelCase    :			Dict              =					1
  											elif isinstance(A  ,			A		):
  																_UpperCAmelCase    :			Union[str, Any]              =					len(A		)
  											else:
  																raise ValueError(f'`prompt` has to be of type `str` or `list` but is {type(A		)}'		)
  
  											_UpperCAmelCase    :			List[str]              =					self._execution_device
  
  											_UpperCAmelCase    :			Optional[int]              =					batch_size * num_images_per_prompt
  
  											_UpperCAmelCase    :			str              =					guidance_scale > 1.0
  											_UpperCAmelCase    :			Dict              =					self._encode_prompt(A  ,			A  ,			A  ,			A		)
  
  											# prior
  
  											self.scheduler.set_timesteps(A  ,			device=A		)
  											_UpperCAmelCase    :			Tuple              =					self.scheduler.timesteps
  
  											_UpperCAmelCase    :			Tuple              =					self.prior.config.num_embeddings
  											_UpperCAmelCase    :			Optional[int]              =					self.prior.config.embedding_dim
  
  											_UpperCAmelCase    :			Optional[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
  											_UpperCAmelCase    :			Optional[int]              =					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
  																_UpperCAmelCase    :			Union[str, Any]              =					torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
  																_UpperCAmelCase    :			Dict              =					self.scheduler.scale_model_input(A  ,			A		)
  
  																_UpperCAmelCase    :			str              =					self.prior(
  																    A  ,			timestep=A  ,			proj_embedding=A  ,			).predicted_image_embedding
  
  																# remove the variance
  																_UpperCAmelCase    :			Union[str, 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:
  																					_UpperCAmelCase    :			str              =					noise_pred.chunk(2		)
  																					_UpperCAmelCase    :			List[Any]              =					noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
  																_UpperCAmelCase    :			int              =					self.scheduler.step(
  																    A  ,			timestep=A  ,			sample=A  ,			).prev_sample
  
  											if output_type == "latent":
  																return ShapEPipelineOutput(images=A		)
  
  											_UpperCAmelCase    :			List[Any]              =					[]
  											for i, latent in enumerate(A		):
  																_UpperCAmelCase    :			str              =					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		)
  
  											_UpperCAmelCase    :			Optional[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}'		)
  
  											_UpperCAmelCase    :			str              =					images.cpu().numpy()
  
  											if output_type == "pil":
  																_UpperCAmelCase    :			Optional[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		)
  
style_context: 
  
  
  
  """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 		__snake_case		(   SCREAMING_SNAKE_CASE__			:		Optional[Any]		,						SCREAMING_SNAKE_CASE__			:		Tuple		,						SCREAMING_SNAKE_CASE__			:		Any       )						->     Dict:
  
  
  
  
  
       '''simple docstring'''
  
       _UpperCAmelCase    :			Any              =					{"small": (512, 8, 24), "medium": (1_024, 8, 36), "large": (1_536, 16, 48)}
       _UpperCAmelCase       , _UpperCAmelCase       , _UpperCAmelCase    :			str              =					MODELS[model_size]  # set model hyperparameters
       _UpperCAmelCase    :			Tuple              =					ImageGPTConfig(n_embd=SCREAMING_SNAKE_CASE__		,						n_layer=SCREAMING_SNAKE_CASE__		,						n_head=SCREAMING_SNAKE_CASE__       )
       _UpperCAmelCase    :			int              =					ImageGPTForCausalLM(SCREAMING_SNAKE_CASE__       )
  
       # Load weights from numpy
       load_tf_weights_in_imagegpt(SCREAMING_SNAKE_CASE__		,						SCREAMING_SNAKE_CASE__		,						SCREAMING_SNAKE_CASE__       )
  
       # Save pytorch-model
       _UpperCAmelCase    :			Union[str, Any]              =					pytorch_dump_folder_path + "/" + WEIGHTS_NAME
       _UpperCAmelCase    :			int              =					pytorch_dump_folder_path + "/" + CONFIG_NAME
       print(f'Save PyTorch model to {pytorch_weights_dump_path}'       )
       torch.save(model.state_dict()		,						SCREAMING_SNAKE_CASE__       )
       print(f'Save configuration file to {pytorch_config_dump_path}'       )
       with open(SCREAMING_SNAKE_CASE__		,						"w"		,						encoding="utf-8"       ) as f:
            f.write(config.to_json_string()       )
  
  
  if __name__ == "__main__":
   _lowerCAmelCase       :      List[str]							=							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."
   )
   _lowerCAmelCase       :      Optional[int]							=							parser.parse_args()
   convert_imagegpt_checkpoint_to_pytorch(
       args.imagegpt_checkpoint_path, args.model_size, args.pytorch_dump_folder_path
   )
  