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					:Optional[Any]  =      logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  _lowerCAmelCase					:Union[str, 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							(				a   ):
  
  
  
  
  
       '''simple docstring'''
  
  
  
       a__             =42
  
  
  
  class 							_UpperCAmelCase							(				a   ):
  
  
  
  
  
       '''simple docstring'''
  
  
  
       def __init__(      self ,			A ,			A ,			A ,			A ,			A ,			)							->      Union[str, Any]:
           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	)							->      Any:
           if latents is None:
               _UpperCAmelCase							:						Optional[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}'	)
               _UpperCAmelCase							:						Tuple       							=					latents.to(A	)
  
           _UpperCAmelCase							:						str       							=					latents * scheduler.init_noise_sigma
           return latents
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A=0	)							->      Any:
           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							:						Union[str, Any]       							=					[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	)							->      Union[str, Any]:
           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							:						int       							=					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							:						Optional[int]       							=					None
           for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
               _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[int]       							=					cpu_offload_with_hook(A ,			A ,			prev_module_hook=A	)
  
           if self.safety_checker is not None:
               _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[int]       							=					cpu_offload_with_hook(self.safety_checker ,			A ,			prev_module_hook=A	)
  
           # We'll offload the last model manually.
           _UpperCAmelCase							:						str       							=					hook
  
  
  
  
  
       @property
       def 				__lowerCAmelCase			(      self	)							->      Dict:
           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:
           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							:						Optional[int]       							=					self.tokenizer(
               A ,			padding='''max_length''' ,			max_length=self.tokenizer.model_max_length ,			truncation=A ,			return_tensors='''pt''' ,			)
           _UpperCAmelCase							:						Any       							=					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							:						List[str]       							=					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							:						Dict       							=					text_encoder_output.text_embeds
  
           _UpperCAmelCase							:						Tuple       							=					prompt_embeds.repeat_interleave(A ,			dim=0	)
           # in Shap-E it normalize the prompt_embeds and then later rescale it
           _UpperCAmelCase							:						Dict       							=					prompt_embeds / torch.linalg.norm(A ,			dim=-1 ,			keepdim=A	)
  
           if do_classifier_free_guidance:
               _UpperCAmelCase							:						Union[str, Any]       							=					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							:						str       							=					torch.cat([negative_prompt_embeds, prompt_embeds]	)
  
           # Rescale the features to have unit variance
           _UpperCAmelCase							:						Optional[int]       							=					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 ,			)							->      Optional[Any]:
  
           if isinstance(A ,			A	):
               _UpperCAmelCase							:						List[Any]       							=					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							:						Any       							=					self._execution_device
  
           _UpperCAmelCase							:						int       							=					batch_size * num_images_per_prompt
  
           _UpperCAmelCase							:						Tuple       							=					guidance_scale > 1.0
           _UpperCAmelCase							:						List[str]       							=					self._encode_prompt(A ,			A ,			A ,			A	)
  
           # prior
  
           self.scheduler.set_timesteps(A ,			device=A	)
           _UpperCAmelCase							:						List[str]       							=					self.scheduler.timesteps
  
           _UpperCAmelCase							:						List[Any]       							=					self.prior.config.num_embeddings
           _UpperCAmelCase							:						Dict       							=					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[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
               _UpperCAmelCase							:						str       							=					torch.cat([latents] * 2	) if do_classifier_free_guidance else latents
               _UpperCAmelCase							:						str       							=					self.scheduler.scale_model_input(A ,			A	)
  
               _UpperCAmelCase							:						str       							=					self.prior(
                   A ,			timestep=A ,			proj_embedding=A ,			).predicted_image_embedding
  
               # remove the variance
               _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[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							,       _UpperCAmelCase							:						Tuple       							=					noise_pred.chunk(2	)
                   _UpperCAmelCase							:						str       							=					noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)
  
               _UpperCAmelCase							:						Optional[Any]       							=					self.scheduler.step(
                   A ,			timestep=A ,			sample=A ,			).prev_sample
  
           if output_type == "latent":
               return ShapEPipelineOutput(images=A	)
  
           _UpperCAmelCase							:						Any       							=					[]
           for i, latent in enumerate(A	):
               _UpperCAmelCase							:						Dict       							=					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							:						List[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							:						Optional[int]       							=					images.cpu().numpy()
  
           if output_type == "pil":
               _UpperCAmelCase							:						List[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"""
  from collections import OrderedDict
  from typing import Any, List, Mapping, Optional
  
  from ... import PreTrainedTokenizer, TensorType, is_torch_available
  from ...configuration_utils import PretrainedConfig
  from ...onnx import OnnxConfigWithPast, PatchingSpec
  from ...utils import logging
  
  
  _lowerCAmelCase					:Union[str, Any]  =      logging.get_logger(__name__)
  
  _lowerCAmelCase					:List[str]  =      {
      'gpt2': 'https://huggingface.co/gpt2/resolve/main/config.json',
      'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/config.json',
      'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/config.json',
      'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/config.json',
      'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/config.json',
  }
  class 							_UpperCAmelCase							(				a   ):
  
  
  
  
  
       '''simple docstring'''
  
  
  
       a__             ='''gpt2'''
       a__             =['''past_key_values''']
       a__             ={
           '''hidden_size''': '''n_embd''',
           '''max_position_embeddings''': '''n_positions''',
           '''num_attention_heads''': '''n_head''',
           '''num_hidden_layers''': '''n_layer''',
       }
  
  
  
  
  
       def __init__(      self ,			A=5_0_2_5_7 ,			A=1_0_2_4 ,			A=7_6_8 ,			A=1_2 ,			A=1_2 ,			A=None ,			A="gelu_new" ,			A=0.1 ,			A=0.1 ,			A=0.1 ,			A=1E-5 ,			A=0.02 ,			A="cls_index" ,			A=True ,			A=None ,			A=True ,			A=0.1 ,			A=True ,			A=True ,			A=5_0_2_5_6 ,			A=5_0_2_5_6 ,			A=False ,			A=False ,			**A ,			)							->      Union[str, Any]:
           _UpperCAmelCase							:						Optional[int]       							=					vocab_size
           _UpperCAmelCase							:						Union[str, Any]       							=					n_positions
           _UpperCAmelCase							:						Optional[Any]       							=					n_embd
           _UpperCAmelCase							:						Tuple       							=					n_layer
           _UpperCAmelCase							:						Any       							=					n_head
           _UpperCAmelCase							:						Union[str, Any]       							=					n_inner
           _UpperCAmelCase							:						Optional[int]       							=					activation_function
           _UpperCAmelCase							:						Optional[int]       							=					resid_pdrop
           _UpperCAmelCase							:						Dict       							=					embd_pdrop
           _UpperCAmelCase							:						List[Any]       							=					attn_pdrop
           _UpperCAmelCase							:						Tuple       							=					layer_norm_epsilon
           _UpperCAmelCase							:						Optional[int]       							=					initializer_range
           _UpperCAmelCase							:						List[str]       							=					summary_type
           _UpperCAmelCase							:						Tuple       							=					summary_use_proj
           _UpperCAmelCase							:						List[Any]       							=					summary_activation
           _UpperCAmelCase							:						Optional[int]       							=					summary_first_dropout
           _UpperCAmelCase							:						int       							=					summary_proj_to_labels
           _UpperCAmelCase							:						Union[str, Any]       							=					scale_attn_weights
           _UpperCAmelCase							:						Any       							=					use_cache
           _UpperCAmelCase							:						Tuple       							=					scale_attn_by_inverse_layer_idx
           _UpperCAmelCase							:						Optional[Any]       							=					reorder_and_upcast_attn
  
           _UpperCAmelCase							:						Union[str, Any]       							=					bos_token_id
           _UpperCAmelCase							:						Optional[int]       							=					eos_token_id
  
           super().__init__(bos_token_id=A ,			eos_token_id=A ,			**A	)
  
  
  
  class 							_UpperCAmelCase							(				a   ):
  
  
  
  
  
       '''simple docstring'''
  
  
  
       def __init__(      self ,			A ,			A = "default" ,			A = None ,			A = False ,			)							->      str:
           super().__init__(A ,			task=A ,			patching_specs=A ,			use_past=A	)
           if not getattr(self._config ,			'''pad_token_id''' ,			A	):
               # TODO: how to do that better?
               _UpperCAmelCase							:						Optional[int]       							=					0
  
  
  
  
  
       @property
       def 				__lowerCAmelCase			(      self	)							->      Mapping[str, Mapping[int, str]]:
           _UpperCAmelCase							:						List[str]       							=					OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}	)
           if self.use_past:
               self.fill_with_past_key_values_(A ,			direction='''inputs'''	)
               _UpperCAmelCase							:						Union[str, Any]       							=					{0: '''batch''', 1: '''past_sequence + sequence'''}
           else:
               _UpperCAmelCase							:						Tuple       							=					{0: '''batch''', 1: '''sequence'''}
  
           return common_inputs
  
  
  
  
  
       @property
       def 				__lowerCAmelCase			(      self	)							->      int:
           return self._config.n_layer
  
  
  
  
  
       @property
       def 				__lowerCAmelCase			(      self	)							->      int:
           return self._config.n_head
  
  
  
  
  
       def 				__lowerCAmelCase			(      self ,			A ,			A = -1 ,			A = -1 ,			A = False ,			A = None ,			)							->      Mapping[str, Any]:
           _UpperCAmelCase							:						int       							=					super(A ,			self	).generate_dummy_inputs(
               A ,			batch_size=A ,			seq_length=A ,			is_pair=A ,			framework=A	)
  
           # We need to order the input in the way they appears in the forward()
           _UpperCAmelCase							:						List[Any]       							=					OrderedDict({'''input_ids''': common_inputs['''input_ids''']}	)
  
           # Need to add the past_keys
           if self.use_past:
               if not is_torch_available():
                   raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''	)
               else:
                   import torch
  
                   _UpperCAmelCase							,       _UpperCAmelCase							:						Optional[Any]       							=					common_inputs['''input_ids'''].shape
                   # Not using the same length for past_key_values
                   _UpperCAmelCase							:						Optional[Any]       							=					seqlen + 2
                   _UpperCAmelCase							:						Union[str, Any]       							=					(
                       batch,
                       self.num_attention_heads,
                       past_key_values_length,
                       self._config.hidden_size // self.num_attention_heads,
                   )
                   _UpperCAmelCase							:						List[Any]       							=					[
                       (torch.zeros(A	), torch.zeros(A	)) for _ in range(self.num_layers	)
                   ]
  
           _UpperCAmelCase							:						int       							=					common_inputs['''attention_mask''']
           if self.use_past:
               _UpperCAmelCase							:						int       							=					ordered_inputs['''attention_mask'''].dtype
               _UpperCAmelCase							:						Dict       							=					torch.cat(
                   [ordered_inputs['''attention_mask'''], torch.ones(A ,			A ,			dtype=A	)] ,			dim=1	)
  
           return ordered_inputs
  
  
  
  
  
       @property
       def 				__lowerCAmelCase			(      self	)							->      int:
           return 1_3
  
  
  