





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_      :			str		  =      logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE_      :			Dict		  =      '''
    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 		snake_case_      (       UpperCamelCase__	):







	'''simple docstring'''
	__UpperCamelCase        =		42





class 		snake_case_      (       UpperCamelCase__	):







	'''simple docstring'''




	def __init__(	self       :    Optional[int]				,			__lowerCamelCase       :    str				,			__lowerCamelCase       :    Optional[Any]				,			__lowerCamelCase       :    Optional[int]				,			__lowerCamelCase       :    int				,			__lowerCamelCase       :    Dict				,			)					->   int:

			'''simple docstring'''




			super().__init__()

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




	def       UpperCAmelCase (	self       :    Union[str, Any]				,			__lowerCamelCase       :    Optional[Any]				,			__lowerCamelCase       :    Union[str, Any]				,			__lowerCamelCase       :    Optional[Any]				,			__lowerCamelCase       :    str				,			__lowerCamelCase       :    Tuple				,			__lowerCamelCase       :    Union[str, Any]      )					->   List[str]:

			'''simple docstring'''




			if latents is None:
					__lowercase					=    randn_tensor(snake_case_				,			generator=snake_case_				,			device=snake_case_				,			dtype=snake_case_      )
			else:
					if latents.shape != shape:
							raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"      )
					__lowercase					=    latents.to(snake_case_      )

			__lowercase					=    latents * scheduler.init_noise_sigma
			return latents




	def       UpperCAmelCase (	self       :    Tuple				,			__lowerCamelCase       :    Any=0      )					->   str:

			'''simple docstring'''




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

			__lowercase					=    torch.device(F"cuda:{gpu_id}"      )

			__lowercase					=    [self.text_encoder, self.prior]
			for cpu_offloaded_model in models:
					if cpu_offloaded_model is not None:
							cpu_offload(snake_case_				,			snake_case_      )




	def       UpperCAmelCase (	self       :    Dict				,			__lowerCamelCase       :    str=0      )					->   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.'      )

			__lowercase					=    torch.device(F"cuda:{gpu_id}"      )

			if self.device.type != "cpu":
					self.to('cpu'				,			silence_dtype_warnings=snake_case_      )
					torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

			__lowercase					=    None
			for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
					__lowercase					=    cpu_offload_with_hook(snake_case_				,			snake_case_				,			prev_module_hook=snake_case_      )

			if self.safety_checker is not None:
					__lowercase					=    cpu_offload_with_hook(self.safety_checker				,			snake_case_				,			prev_module_hook=snake_case_      )

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




	@property
	def       UpperCAmelCase (	self       :    Union[str, 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(snake_case_				,			'_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       UpperCAmelCase (	self       :    Optional[Any]				,			__lowerCamelCase       :    str				,			__lowerCamelCase       :    List[Any]				,			__lowerCamelCase       :    List[Any]				,			__lowerCamelCase       :    Tuple				,			)					->   List[Any]:

			'''simple docstring'''




			len(snake_case_      ) if isinstance(snake_case_				,			snake_case_      ) else 1

			# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
			__lowercase					=    0
			# get prompt text embeddings
			__lowercase					=    self.tokenizer(
			    snake_case_				,			padding='max_length'				,			max_length=self.tokenizer.model_max_length				,			truncation=snake_case_				,			return_tensors='pt'				,			)
			__lowercase					=    text_inputs.input_ids
			__lowercase					=    self.tokenizer(snake_case_				,			padding='longest'				,			return_tensors='pt'      ).input_ids

			if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(snake_case_				,			snake_case_      ):
					__lowercase					=    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}"      )

			__lowercase					=    self.text_encoder(text_input_ids.to(snake_case_      )      )
			__lowercase					=    text_encoder_output.text_embeds

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

			if do_classifier_free_guidance:
					__lowercase					=    torch.zeros_like(snake_case_      )

					# 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
					__lowercase					=    torch.cat([negative_prompt_embeds, prompt_embeds]      )

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

			return prompt_embeds






	@torch.no_grad()
	@replace_example_docstring(snake_case_      )
	def __call__(	self       :    Dict				,			__lowerCamelCase       :    List[Any]				,			__lowerCamelCase       :    Any = 1				,			__lowerCamelCase       :    Optional[Any] = 25				,			__lowerCamelCase       :    Tuple = None				,			__lowerCamelCase       :    Union[str, Any] = None				,			__lowerCamelCase       :    int = 4.0				,			__lowerCamelCase       :    Dict = 64				,			__lowerCamelCase       :    Any = "pil"				,			__lowerCamelCase       :    Dict = True				,			)					->   Dict:

			'''simple docstring'''




			if isinstance(snake_case_				,			snake_case_      ):
					__lowercase					=    1
			elif isinstance(snake_case_				,			snake_case_      ):
					__lowercase					=    len(snake_case_      )
			else:
					raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(snake_case_      )}"      )

			__lowercase					=    self._execution_device

			__lowercase					=    batch_size * num_images_per_prompt

			__lowercase					=    guidance_scale > 1.0
			__lowercase					=    self._encode_prompt(snake_case_				,			snake_case_				,			snake_case_				,			snake_case_      )

			# prior

			self.scheduler.set_timesteps(snake_case_				,			device=snake_case_      )
			__lowercase					=    self.scheduler.timesteps

			__lowercase					=    self.prior.config.num_embeddings
			__lowercase					=    self.prior.config.embedding_dim

			__lowercase					=    self.prepare_latents(
			    (batch_size, num_embeddings * embedding_dim)				,			prompt_embeds.dtype				,			snake_case_				,			snake_case_				,			snake_case_				,			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
			__lowercase					=    latents.reshape(latents.shape[0]				,			snake_case_				,			snake_case_      )

			for i, t in enumerate(self.progress_bar(snake_case_      )      ):
					# expand the latents if we are doing classifier free guidance
					__lowercase					=    torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
					__lowercase					=    self.scheduler.scale_model_input(snake_case_				,			snake_case_      )

					__lowercase					=    self.prior(
					    snake_case_				,			timestep=snake_case_				,			proj_embedding=snake_case_				,			).predicted_image_embedding

					# remove the variance
					__lowercase					=    noise_pred.split(
					    scaled_model_input.shape[2]				,			dim=2      )  # batch_size, num_embeddings, embedding_dim

					if do_classifier_free_guidance is not None:
							__lowercase					=    noise_pred.chunk(2      )
							__lowercase					=    noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

					__lowercase					=    self.scheduler.step(
					    snake_case_				,			timestep=snake_case_				,			sample=snake_case_				,			).prev_sample

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

			__lowercase					=    []
			for i, latent in enumerate(snake_case_      ):
					__lowercase					=    self.renderer.decode(
					    latent[None, :]				,			snake_case_				,			size=snake_case_				,			ray_batch_size=4_096				,			n_coarse_samples=64				,			n_fine_samples=128				,			)
					images.append(snake_case_      )

			__lowercase					=    torch.stack(snake_case_      )

			if output_type not in ["np", "pil"]:
					raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"      )

			__lowercase					=    images.cpu().numpy()

			if output_type == "pil":
					__lowercase					=    [self.numpy_to_pil(snake_case_      ) 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=snake_case_      )












import torch
import torch.nn.functional as F

from diffusers import VQDiffusionScheduler

from .test_schedulers import SchedulerCommonTest

class 		snake_case_      (       UpperCAmelCase_	):







	'''simple docstring'''
	__UpperCamelCase        =		(VQDiffusionScheduler,)




	def       UpperCAmelCase (	self       :    int				,			**__lowerCamelCase       :    List[Any]      )					->   Tuple:

			'''simple docstring'''




			__lowercase					=    {
			    'num_vec_classes': 4_097,
			    'num_train_timesteps': 100,
			}

			config.update(**__lowerCamelCase      )
			return config




	def       UpperCAmelCase (	self       :    List[Any]				,			__lowerCamelCase       :    List[str]      )					->   Tuple:

			'''simple docstring'''




			__lowercase					=    4
			__lowercase					=    8
			__lowercase					=    8

			__lowercase					=    torch.randint(0				,			__lowerCamelCase				,			(batch_size, height * width)      )

			return sample




	@property
	def       UpperCAmelCase (	self       :    Any      )					->   List[Any]:

			'''simple docstring'''




			assert False




	def       UpperCAmelCase (	self       :    Union[str, Any]				,			__lowerCamelCase       :    str      )					->   Dict:

			'''simple docstring'''




			def model(__lowerCamelCase       :    Dict				,			__lowerCamelCase       :    Optional[Any]				,			*__lowerCamelCase       :    List[Any]      ):
					__lowercase	,			__lowercase					=    sample.shape
					__lowercase					=    torch.rand((batch_size, num_vec_classes - 1, num_latent_pixels)      )
					__lowercase					=    F.log_softmax(logits.double()				,			dim=1      ).float()
					return return_value

			return model




	def       UpperCAmelCase (	self       :    Dict      )					->   List[Any]:

			'''simple docstring'''




			for timesteps in [2, 5, 100, 1_000]:
					self.check_over_configs(num_train_timesteps=__lowerCamelCase      )




	def       UpperCAmelCase (	self       :    Optional[Any]      )					->   int:

			'''simple docstring'''




			for num_vec_classes in [5, 100, 1_000, 4_000]:
					self.check_over_configs(num_vec_classes=__lowerCamelCase      )




	def       UpperCAmelCase (	self       :    Any      )					->   List[Any]:

			'''simple docstring'''




			for t in [0, 50, 99]:
					self.check_over_forward(time_step=__lowerCamelCase      )






	def       UpperCAmelCase (	self       :    str      )					->   Optional[int]:

			'''simple docstring'''




			pass




