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
  
  
  SCREAMING_SNAKE_CASE__    :    Any								=					logging.get_logger(__name__)  # pylint: disable=invalid-name
  
  SCREAMING_SNAKE_CASE__    :    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 			a_					(    SCREAMING_SNAKE_CASE__    ):
  	A					       =   42
  
  
  
  
  class 			a_					(    SCREAMING_SNAKE_CASE__    ):
  
  
  
  
  
  	def __init__(       self			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    )     ->				List[str]:
  
  
  
  
  				"""simple docstring"""
  
  
  
  				super().__init__()
  
  				self.register_modules(
  				    prior=A_			,    text_encoder=A_			,    tokenizer=A_			,    scheduler=A_			,    renderer=A_			,    )
  
  
  
  
  
  	def 	A_(       self			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			)     ->				str:
  
  
  
  
  				"""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 	A_(       self			,    SCREAMING_SNAKE_CASE=0			)     ->				int:
  
  
  
  
  				"""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 	A_(       self			,    SCREAMING_SNAKE_CASE=0			)     ->				Union[str, 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 	A_(       self			)     ->				str:
  
  
  
  
  				"""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 	A_(       self			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE			,    )     ->				Dict:
  
  
  
  
  				"""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			,    SCREAMING_SNAKE_CASE			,    SCREAMING_SNAKE_CASE = 1			,    SCREAMING_SNAKE_CASE = 25			,    SCREAMING_SNAKE_CASE = None			,    SCREAMING_SNAKE_CASE = None			,    SCREAMING_SNAKE_CASE = 4.0			,    SCREAMING_SNAKE_CASE = 64			,    SCREAMING_SNAKE_CASE = "pil"			,    SCREAMING_SNAKE_CASE = True			,    )     ->				Optional[int]:
  
  
  
  
  				"""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=4096			,    n_coarse_samples=64			,    n_fine_samples=128			,    )
  							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: 
  
  
  
  
  from dataclasses import dataclass
  from typing import List, Optional, Union
  
  import numpy as np
  import PIL
  
  from ...utils import BaseOutput, is_invisible_watermark_available, is_torch_available, is_transformers_available
  
  
  
  @dataclass
  class 			a_					(    SCREAMING_SNAKE_CASE__    ):
  	A						       =   42
  
  
  if is_transformers_available() and is_torch_available() and is_invisible_watermark_available():
  				from .pipeline_stable_diffusion_xl import StableDiffusionXLPipeline
  				from .pipeline_stable_diffusion_xl_imgaimg import StableDiffusionXLImgaImgPipeline
  