code: 
  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				      =					logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  __lowerCAmelCase				      =					'\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 						lowerCamelCase			(					__lowerCamelCase				):
  	UpperCamelCase_     :				int								=  4_2
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	def __init__(    self			:Any      ,    lowercase			:PriorTransformer      ,    lowercase			:CLIPTextModelWithProjection      ,    lowercase			:CLIPTokenizer      ,    lowercase			:HeunDiscreteScheduler      ,    lowercase			:ShapERenderer      ,    )		->			int:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				super().__init__()
  
  				self.register_modules(
  				    prior=A_      ,    text_encoder=A_      ,    tokenizer=A_      ,    scheduler=A_      ,    renderer=A_      ,    )
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:str      ,    lowercase			:Union[str, Any]      ,    lowercase			:Tuple      ,    lowercase			:Optional[Any]      ,    lowercase			:Optional[Any]      ,    lowercase			:Any      ,    lowercase			:Optional[int] )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				if latents is None:
  							SCREAMING_SNAKE_CASE    	=   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}""" )
  							SCREAMING_SNAKE_CASE    	=   latents.to(A_ )
  
  				SCREAMING_SNAKE_CASE    	=   latents * scheduler.init_noise_sigma
  				return latents
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:Any      ,    lowercase			:Union[str, Any]=0 )		->			str:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				if is_accelerate_available():
  							from accelerate import cpu_offload
  				else:
  							raise ImportError('''Please install accelerate via `pip install accelerate`''' )
  
  				SCREAMING_SNAKE_CASE    	=   torch.device(f"""cuda:{gpu_id}""" )
  
  				SCREAMING_SNAKE_CASE    	=   [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			:List[Any]      ,    lowercase			:Dict=0 )		->			Optional[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.''' )
  
  				SCREAMING_SNAKE_CASE    	=   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)
  
  				SCREAMING_SNAKE_CASE    	=   None
  				for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
  							SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   cpu_offload_with_hook(A_      ,    A_      ,    prev_module_hook=A_ )
  
  				if self.safety_checker is not None:
  							SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   cpu_offload_with_hook(self.safety_checker      ,    A_      ,    prev_module_hook=A_ )
  
  				# We'll offload the last model manually.
  				SCREAMING_SNAKE_CASE    	=   hook
  
  
  
  
  
  
  
  	@property
  	def    snake_case__    (    self			:Optional[Any] )		->			Optional[int]:
  
  
  
  
  
  
  
  				"""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    snake_case__    (    self			:Union[str, Any]      ,    lowercase			:Optional[Any]      ,    lowercase			:str      ,    lowercase			:Optional[int]      ,    lowercase			:Union[str, Any]      ,    )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""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
  				SCREAMING_SNAKE_CASE    	=   0
  				# get prompt text embeddings
  				SCREAMING_SNAKE_CASE    	=   self.tokenizer(
  				    A_      ,    padding='''max_length'''      ,    max_length=self.tokenizer.model_max_length      ,    truncation=A_      ,    return_tensors='''pt'''      ,    )
  				SCREAMING_SNAKE_CASE    	=   text_inputs.input_ids
  				SCREAMING_SNAKE_CASE    	=   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_ ):
  							SCREAMING_SNAKE_CASE    	=   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}""" )
  
  				SCREAMING_SNAKE_CASE    	=   self.text_encoder(text_input_ids.to(A_ ) )
  				SCREAMING_SNAKE_CASE    	=   text_encoder_output.text_embeds
  
  				SCREAMING_SNAKE_CASE    	=   prompt_embeds.repeat_interleave(A_      ,    dim=0 )
  				# in Shap-E it normalize the prompt_embeds and then later rescale it
  				SCREAMING_SNAKE_CASE    	=   prompt_embeds / torch.linalg.norm(A_      ,    dim=-1      ,    keepdim=A_ )
  
  				if do_classifier_free_guidance:
  							SCREAMING_SNAKE_CASE    	=   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
  							SCREAMING_SNAKE_CASE    	=   torch.cat([negative_prompt_embeds, prompt_embeds] )
  
  				# Rescale the features to have unit variance
  				SCREAMING_SNAKE_CASE    	=   math.sqrt(prompt_embeds.shape[1] ) * prompt_embeds
  
  				return prompt_embeds
  
  
  
  
  
  
  
  	@torch.no_grad()
  	@replace_example_docstring(A_ )
  	def __call__(    self			:Tuple      ,    lowercase			:str      ,    lowercase			:int = 1      ,    lowercase			:int = 2_5      ,    lowercase			:Optional[Union[torch.Generator, List[torch.Generator]]] = None      ,    lowercase			:Optional[torch.FloatTensor] = None      ,    lowercase			:float = 4.0      ,    lowercase			:int = 6_4      ,    lowercase			:Optional[str] = "pil"      ,    lowercase			:bool = True      ,    )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				if isinstance(A_      ,    A_ ):
  							SCREAMING_SNAKE_CASE    	=   1
  				elif isinstance(A_      ,    A_ ):
  							SCREAMING_SNAKE_CASE    	=   len(A_ )
  				else:
  							raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(A_ )}""" )
  
  				SCREAMING_SNAKE_CASE    	=   self._execution_device
  
  				SCREAMING_SNAKE_CASE    	=   batch_size * num_images_per_prompt
  
  				SCREAMING_SNAKE_CASE    	=   guidance_scale > 1.0
  				SCREAMING_SNAKE_CASE    	=   self._encode_prompt(A_      ,    A_      ,    A_      ,    A_ )
  
  				# prior
  
  				self.scheduler.set_timesteps(A_      ,    device=A_ )
  				SCREAMING_SNAKE_CASE    	=   self.scheduler.timesteps
  
  				SCREAMING_SNAKE_CASE    	=   self.prior.config.num_embeddings
  				SCREAMING_SNAKE_CASE    	=   self.prior.config.embedding_dim
  
  				SCREAMING_SNAKE_CASE    	=   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
  				SCREAMING_SNAKE_CASE    	=   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
  							SCREAMING_SNAKE_CASE    	=   torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
  							SCREAMING_SNAKE_CASE    	=   self.scheduler.scale_model_input(A_      ,    A_ )
  
  							SCREAMING_SNAKE_CASE    	=   self.prior(
  							    A_      ,    timestep=A_      ,    proj_embedding=A_      ,    ).predicted_image_embedding
  
  							# remove the variance
  							SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   noise_pred.split(
  							    scaled_model_input.shape[2]      ,    dim=2 )  # batch_size, num_embeddings, embedding_dim
  
  							if do_classifier_free_guidance is not None:
  										SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   noise_pred.chunk(2 )
  										SCREAMING_SNAKE_CASE    	=   noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
  							SCREAMING_SNAKE_CASE    	=   self.scheduler.step(
  							    A_      ,    timestep=A_      ,    sample=A_      ,    ).prev_sample
  
  				if output_type == "latent":
  							return ShapEPipelineOutput(images=A_ )
  
  				SCREAMING_SNAKE_CASE    	=   []
  				for i, latent in enumerate(A_ ):
  							SCREAMING_SNAKE_CASE    	=   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_ )
  
  				SCREAMING_SNAKE_CASE    	=   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}""" )
  
  				SCREAMING_SNAKE_CASE    	=   images.cpu().numpy()
  
  				if output_type == "pil":
  							SCREAMING_SNAKE_CASE    	=   [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: 
  import subprocess
  from argparse import ArgumentParser
  from typing import List, Union
  
  from huggingface_hub.hf_api import HfFolder, create_repo, whoami
  from requests.exceptions import HTTPError
  
  from . import BaseTransformersCLICommand
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	@staticmethod
  	def    snake_case__    (    lowercase			:ArgumentParser )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				SCREAMING_SNAKE_CASE    	=   parser.add_parser('''login'''      ,    help='''Log in using the same credentials as on huggingface.co''' )
  				login_parser.set_defaults(func=lambda lowercase : LoginCommand(lowercase ) )
  				SCREAMING_SNAKE_CASE    	=   parser.add_parser('''whoami'''      ,    help='''Find out which huggingface.co account you are logged in as.''' )
  				whoami_parser.set_defaults(func=lambda lowercase : WhoamiCommand(lowercase ) )
  				SCREAMING_SNAKE_CASE    	=   parser.add_parser('''logout'''      ,    help='''Log out''' )
  				logout_parser.set_defaults(func=lambda lowercase : LogoutCommand(lowercase ) )
  
  				# new system: git-based repo system
  				SCREAMING_SNAKE_CASE    	=   parser.add_parser(
  				    '''repo'''      ,    help='''Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos.'''      ,    )
  				SCREAMING_SNAKE_CASE    	=   repo_parser.add_subparsers(
  				    help='''Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands''' )
  				SCREAMING_SNAKE_CASE    	=   repo_subparsers.add_parser(
  				    '''create'''      ,    help='''Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co''' )
  				repo_create_parser.add_argument(
  				    '''name'''      ,    type=lowercase      ,    help='''Name for your model\'s repo. Will be namespaced under your username to build the model id.'''      ,    )
  				repo_create_parser.add_argument('''--organization'''      ,    type=lowercase      ,    help='''Optional: organization namespace.''' )
  				repo_create_parser.add_argument('''-y'''      ,    '''--yes'''      ,    action='''store_true'''      ,    help='''Optional: answer Yes to the prompt''' )
  				repo_create_parser.set_defaults(func=lambda lowercase : RepoCreateCommand(lowercase ) )
  
  
  
  
  
  class 						lowerCamelCase			:
  	UpperCamelCase_     :				List[str]								=  '\u001b[1m'
  	UpperCamelCase_     :				Union[str, Any]								=  '\u001b[31m'
  	UpperCamelCase_     :				Any								=  '\u001b[90m'
  	UpperCamelCase_     :				List[str]								=  '\u001b[0m'
  
  
  
  
  
  
  
  	@classmethod
  	def    snake_case__    (    cls			:List[Any]      ,    lowercase			:Any )		->			List[str]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				return f"""{cls._bold}{s}{cls._reset}"""
  
  
  
  
  
  
  
  	@classmethod
  	def    snake_case__    (    cls			:Optional[Any]      ,    lowercase			:str )		->			Tuple:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				return f"""{cls._bold}{cls._red}{s}{cls._reset}"""
  
  
  
  
  
  
  
  	@classmethod
  	def    snake_case__    (    cls			:List[str]      ,    lowercase			:Any )		->			List[Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				return f"""{cls._gray}{s}{cls._reset}"""
  
  
  
  def       a			(   a		,	a  )    ->str:
  
  
  
  
  			'''simple docstring'''
  
  
  			SCREAMING_SNAKE_CASE    	=   [max(len(str(a  )  ) for x in col  ) for col in zip(*a		,	a  )]
  			SCREAMING_SNAKE_CASE    	=   ('''{{:{}}} ''' * len(a  )).format(*a  )
  			SCREAMING_SNAKE_CASE    	=   []
  			lines.append(row_format.format(*a  )  )
  			lines.append(row_format.format(*['''-''' * w for w in col_widths]  )  )
  			for row in rows:
  						lines.append(row_format.format(*a  )  )
  			return "\n".join(a  )
  
  
  
  
  
  class 						lowerCamelCase			:
  
  
  
  
  
  
  
  	def __init__(    self			:List[str]      ,    lowercase			:Optional[Any] )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				SCREAMING_SNAKE_CASE    	=   args
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:List[str] )		->			Optional[Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				print(
  				    ANSI.red(
  				        '''ERROR! `huggingface-cli login` uses an outdated login mechanism '''
  				        '''that is not compatible with the Hugging Face Hub backend anymore. '''
  				        '''Please use `huggingface-cli login instead.''' ) )
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:List[Any] )		->			Any:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				print(
  				    ANSI.red(
  				        '''WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use '''
  				        '''`huggingface-cli whoami` instead.''' ) )
  				SCREAMING_SNAKE_CASE    	=   HfFolder.get_token()
  				if token is None:
  							print('''Not logged in''' )
  							exit()
  				try:
  							SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   whoami(lowercase )
  							print(lowercase )
  							if orgs:
  										print(ANSI.bold('''orgs: ''' )      ,    ''','''.join(lowercase ) )
  				except HTTPError as e:
  							print(lowercase )
  							print(ANSI.red(e.response.text ) )
  							exit(1 )
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:str )		->			Union[str, Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				print(
  				    ANSI.red(
  				        '''ERROR! `transformers-cli logout` uses an outdated logout mechanism '''
  				        '''that is not compatible with the Hugging Face Hub backend anymore. '''
  				        '''Please use `huggingface-cli logout instead.''' ) )
  
  
  
  
  
  class 						lowerCamelCase			(					__lowerCamelCase				):
  
  
  
  
  
  
  
  	def    snake_case__    (    self			:int )		->			Optional[Any]:
  
  
  
  
  
  
  
  				"""simple docstring"""
  
  
  
  
  
  
  				print(
  				    ANSI.red(
  				        '''WARNING! Managing repositories through transformers-cli is deprecated. '''
  				        '''Please use `huggingface-cli` instead.''' ) )
  				SCREAMING_SNAKE_CASE    	=   HfFolder.get_token()
  				if token is None:
  							print('''Not logged in''' )
  							exit(1 )
  				try:
  							SCREAMING_SNAKE_CASE    	=   subprocess.check_output(['''git''', '''--version'''] ).decode('''utf-8''' )
  							print(ANSI.gray(stdout.strip() ) )
  				except FileNotFoundError:
  							print('''Looks like you do not have git installed, please install.''' )
  
  				try:
  							SCREAMING_SNAKE_CASE    	=   subprocess.check_output(['''git-lfs''', '''--version'''] ).decode('''utf-8''' )
  							print(ANSI.gray(stdout.strip() ) )
  				except FileNotFoundError:
  							print(
  							    ANSI.red(
  							        '''Looks like you do not have git-lfs installed, please install.'''
  							        ''' You can install from https://git-lfs.github.com/.'''
  							        ''' Then run `git lfs install` (you only have to do this once).''' ) )
  				print('''''' )
  
  				SCREAMING_SNAKE_CASE	,       SCREAMING_SNAKE_CASE    	=   whoami(lowercase )
  				SCREAMING_SNAKE_CASE    	=   self.args.organization if self.args.organization is not None else user
  				SCREAMING_SNAKE_CASE    	=   f"""{namespace}/{self.args.name}"""
  				print(f"""You are about to create {ANSI.bold(lowercase )}""" )
  
  				if not self.args.yes:
  							SCREAMING_SNAKE_CASE    	=   input('''Proceed? [Y/n] ''' ).lower()
  							if not (choice == "" or choice == "y" or choice == "yes"):
  										print('''Abort''' )
  										exit()
  				try:
  							SCREAMING_SNAKE_CASE    	=   create_repo(lowercase      ,    name=self.args.name      ,    organization=self.args.organization )
  				except HTTPError as e:
  							print(lowercase )
  							print(ANSI.red(e.response.text ) )
  							exit(1 )
  				print('''\nYour repo now lives at:''' )
  				print(f"""  {ANSI.bold(lowercase )}""" )
  				print('''\nYou can clone it locally with the command below, and commit/push as usual.''' )
  				print(f"""\n  git clone {url}""" )
  				print('''''' )