



'''simple docstring'''




import os
import tempfile
from pathlib import Path
from unittest import TestCase

import pyarrow as pa
import pytest

from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader, BaseReader, FileInstructions, ReadInstruction, make_file_instructions
from datasets.info import DatasetInfo
from datasets.splits import NamedSplit, Split, SplitDict, SplitInfo

from .utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases






class 						_UpperCamelCase  (							lowerCamelCase__   ):


   '''simple docstring'''

   def UpperCamelCase__ (							self					:			str							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Tuple=False						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		(
         filename_skip_take["""filename"""],
         filename_skip_take["""skip"""] if """skip""" in filename_skip_take else None,
         filename_skip_take["""take"""] if """take""" in filename_skip_take else None,
     )
     open(os.path.join(lowerCAmelCase__						)							,					"""wb"""						).close()
     __SCREAMING_SNAKE_CASE	:		Dict   	=		pa.Table.from_pydict({"""filename""": [Path(lowerCAmelCase__						).name] * 1_0_0}						)
     if take == -1:
       __SCREAMING_SNAKE_CASE	:		int   	=		len(lowerCAmelCase__						) - skip
     if skip is not None and take is not None:
       __SCREAMING_SNAKE_CASE	:		str   	=		pa_table.slice(lowerCAmelCase__							,					lowerCAmelCase__						)
     return pa_table






class 						_UpperCamelCase  (							lowerCamelCase__   ):


   '''simple docstring'''

   def UpperCamelCase__ (							self					:			Union[str, Any]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Any   	=		"""my_name"""
     __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		SplitInfo(name="""train"""							,					num_examples=1_0_0						)
     __SCREAMING_SNAKE_CASE	:		int   	=		SplitInfo(name="""test"""							,					num_examples=1_0_0						)
     __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		[train_info, test_info]
     __SCREAMING_SNAKE_CASE	:		str   	=		SplitDict()
     split_dict.add(lowerCAmelCase__						)
     split_dict.add(lowerCAmelCase__						)
     __SCREAMING_SNAKE_CASE	:		str   	=		DatasetInfo(splits=lowerCAmelCase__						)

     with tempfile.TemporaryDirectory() as tmp_dir:
       __SCREAMING_SNAKE_CASE	:		Tuple   	=		ReaderTest(lowerCAmelCase__							,					lowerCAmelCase__						)

       __SCREAMING_SNAKE_CASE	:		Dict   	=		"""test[:33%]"""
       __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		Dataset(**reader.read(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)						)
       self.assertEqual(dset["""filename"""][0]							,					F"{name}-test"						)
       self.assertEqual(dset.num_rows							,					3_3						)
       self.assertEqual(dset.num_columns							,					1						)

       __SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		["""train""", """test[:33%]"""]
       __SCREAMING_SNAKE_CASE	:		Tuple   	=		[Split.TRAIN, ReadInstruction.from_spec("""test[:33%]"""						)]
       for instructions in [instructionsa, instructionsa]:
         __SCREAMING_SNAKE_CASE	:		List[str]   	=		[reader.read(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						) for instr in instructions]
         __SCREAMING_SNAKE_CASE	:		List[Any]   	=		(Dataset(**lowerCAmelCase__						) for dataset_kwargs in datasets_kwargs)
         self.assertEqual(train_dset["""filename"""][0]							,					F"{name}-train"						)
         self.assertEqual(train_dset.num_rows							,					1_0_0						)
         self.assertEqual(train_dset.num_columns							,					1						)
         self.assertIsInstance(train_dset.split							,					lowerCAmelCase__						)
         self.assertEqual(str(train_dset.split						)							,					"""train"""						)
         self.assertEqual(test_dset["""filename"""][0]							,					F"{name}-test"						)
         self.assertEqual(test_dset.num_rows							,					3_3						)
         self.assertEqual(test_dset.num_columns							,					1						)
         self.assertIsInstance(test_dset.split							,					lowerCAmelCase__						)
         self.assertEqual(str(test_dset.split						)							,					"""test[:33%]"""						)
         del train_dset, test_dset

   def UpperCamelCase__ (							self					:			Dict						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		"""my_name"""
     __SCREAMING_SNAKE_CASE	:		int   	=		SplitInfo(name="""train"""							,					num_examples=1_0_0_0							,					shard_lengths=[1_0_0] * 1_0						)
     __SCREAMING_SNAKE_CASE	:		int   	=		[train_info]
     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		SplitDict()
     split_dict.add(lowerCAmelCase__						)
     __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		DatasetInfo(splits=lowerCAmelCase__						)

     with tempfile.TemporaryDirectory() as tmp_dir:
       __SCREAMING_SNAKE_CASE	:		List[str]   	=		ReaderTest(lowerCAmelCase__							,					lowerCAmelCase__						)

       __SCREAMING_SNAKE_CASE	:		Any   	=		"""train[:33%]"""
       __SCREAMING_SNAKE_CASE	:		str   	=		Dataset(**reader.read(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)						)
       self.assertEqual(dset["""filename"""][0]							,					F"{name}-train-00000-of-00010"						)
       self.assertEqual(dset["""filename"""][-1]							,					F"{name}-train-00003-of-00010"						)
       self.assertEqual(dset.num_rows							,					3_3_0						)
       self.assertEqual(dset.num_columns							,					1						)



   def UpperCamelCase__ (							self					:			Optional[int]						):





     """simple docstring"""






     __SCREAMING_SNAKE_CASE	:		List[str]   	=		SplitInfo(name="""train"""							,					num_examples=1_0_0						)
     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		SplitInfo(name="""test"""							,					num_examples=1_0_0						)
     __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		SplitDict()
     split_dict.add(lowerCAmelCase__						)
     split_dict.add(lowerCAmelCase__						)
     __SCREAMING_SNAKE_CASE	:		Any   	=		DatasetInfo(splits=lowerCAmelCase__						)

     with tempfile.TemporaryDirectory() as tmp_dir:
       __SCREAMING_SNAKE_CASE	:		List[str]   	=		ReaderTest(lowerCAmelCase__							,					lowerCAmelCase__						)

       __SCREAMING_SNAKE_CASE	:		Tuple   	=		[
           {"""filename""": os.path.join(lowerCAmelCase__							,					"""train"""						)},
           {"""filename""": os.path.join(lowerCAmelCase__							,					"""test"""						), """skip""": 1_0, """take""": 1_0},
       ]
       __SCREAMING_SNAKE_CASE	:		str   	=		Dataset(**reader.read_files(lowerCAmelCase__							,					original_instructions="""train+test[10:20]"""						)						)
       self.assertEqual(dset.num_rows							,					1_1_0						)
       self.assertEqual(dset.num_columns							,					1						)
       del dset


@pytest.mark.parametrize("""in_memory"""	,				[False, True] )
def     lowerCAmelCase_       (     _lowerCamelCase:       Tuple	,				_lowerCamelCase:       int	,				_lowerCamelCase:       Tuple ):
  __SCREAMING_SNAKE_CASE	:		int   	=		arrow_file
  with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
    __SCREAMING_SNAKE_CASE	:		List[str]   	=		ArrowReader.read_table(_lowerCamelCase	,				in_memory=_lowerCamelCase )
  assert table.shape == dataset.data.shape
  assert set(table.column_names ) == set(dataset.data.column_names )
  assert dict(table.to_pydict() ) == dict(dataset.data.to_pydict() )  # to_pydict returns OrderedDict


@pytest.mark.parametrize("""in_memory"""	,				[False, True] )
def     lowerCAmelCase_       (     _lowerCamelCase:       Tuple	,				_lowerCamelCase:       Optional[Any]	,				_lowerCamelCase:       int ):
  __SCREAMING_SNAKE_CASE	:		Tuple   	=		arrow_file
  __SCREAMING_SNAKE_CASE	:		Dict   	=		ArrowReader(""""""	,				_lowerCamelCase )
  with assert_arrow_memory_increases() if in_memory else assert_arrow_memory_doesnt_increase():
    __SCREAMING_SNAKE_CASE	:		Dict   	=		reader.read_files([{"""filename""": filename}]	,				in_memory=_lowerCamelCase )
  assert dataset_kwargs.keys() == {"arrow_table", "info", "split"}
  __SCREAMING_SNAKE_CASE	:		int   	=		dataset_kwargs["""arrow_table"""]
  assert table.shape == dataset.data.shape
  assert set(table.column_names ) == set(dataset.data.column_names )
  assert dict(table.to_pydict() ) == dict(dataset.data.to_pydict() )  # to_pydict returns OrderedDict


def     lowerCAmelCase_       (     ):
  assert ReadInstruction("""train"""	,				to=10	,				unit="""abs""" ).to_spec() == "train[:10]"
  assert ReadInstruction("""train"""	,				from_=-80	,				to=10	,				unit="""%""" ).to_spec() == "train[-80%:10%]"

  __SCREAMING_SNAKE_CASE	:		Dict   	=		"""train+test"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == spec_train_test

  __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		"""train[2:10]"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == spec_train_abs

  __SCREAMING_SNAKE_CASE	:		Tuple   	=		"""train[15%:-20%]"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == spec_train_pct

  __SCREAMING_SNAKE_CASE	:		Tuple   	=		"""train[:10%](closest)"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == "train[:10%]"

  __SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		"""train[:10%](pct1_dropremainder)"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == spec_train_pct_rounding

  __SCREAMING_SNAKE_CASE	:		List[str]   	=		"""train[:10%](pct1_dropremainder)+test[-10%:](pct1_dropremainder)"""
  assert ReadInstruction.from_spec(_lowerCamelCase ).to_spec() == spec_train_test_pct_rounding


def     lowerCAmelCase_       (     ):
  __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		"""dummy"""
  __SCREAMING_SNAKE_CASE	:		Tuple   	=		[SplitInfo(name="""train"""	,				num_examples=1_00 )]
  __SCREAMING_SNAKE_CASE	:		Tuple   	=		"""train[:33%]"""
  __SCREAMING_SNAKE_CASE	:		Dict   	=		"""arrow"""
  __SCREAMING_SNAKE_CASE	:		Optional[int]   	=		"""prefix"""

  __SCREAMING_SNAKE_CASE	:		List[Any]   	=		make_file_instructions(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase )
  assert isinstance(_lowerCamelCase	,				_lowerCamelCase )
  assert file_instructions.num_examples == 33
  assert file_instructions.file_instructions == [
      {"filename": os.path.join(_lowerCamelCase	,				F"{name}-train.arrow" ), "skip": 0, "take": 33}
  ]

  __SCREAMING_SNAKE_CASE	:		Any   	=		[SplitInfo(name="""train"""	,				num_examples=1_00	,				shard_lengths=[10] * 10 )]
  __SCREAMING_SNAKE_CASE	:		List[str]   	=		make_file_instructions(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase )
  assert isinstance(_lowerCamelCase	,				_lowerCamelCase )
  assert file_instructions.num_examples == 33
  assert file_instructions.file_instructions == [
      {"filename": os.path.join(_lowerCamelCase	,				F"{name}-train-00000-of-00010.arrow" ), "skip": 0, "take": -1},
      {"filename": os.path.join(_lowerCamelCase	,				F"{name}-train-00001-of-00010.arrow" ), "skip": 0, "take": -1},
      {"filename": os.path.join(_lowerCamelCase	,				F"{name}-train-00002-of-00010.arrow" ), "skip": 0, "take": -1},
      {"filename": os.path.join(_lowerCamelCase	,				F"{name}-train-00003-of-00010.arrow" ), "skip": 0, "take": 3},
  ]


@pytest.mark.parametrize("""name, expected_exception"""	,				[(None, TypeError), ("""""", ValueError)] )
def     lowerCAmelCase_       (     _lowerCamelCase:       Tuple	,				_lowerCamelCase:       Union[str, Any] ):
  __SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		[SplitInfo(name="""train"""	,				num_examples=1_00 )]
  __SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		"""train"""
  __SCREAMING_SNAKE_CASE	:		List[str]   	=		"""arrow"""
  __SCREAMING_SNAKE_CASE	:		Tuple   	=		"""prefix_path"""
  with pytest.raises(_lowerCamelCase ):
    __SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		make_file_instructions(_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase	,				_lowerCamelCase )




'''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


UpperCamelCase__	:     List[str]    =			logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCamelCase__	:     Tuple    =			'''
    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 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			_A				:		Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]






class 						_UpperCamelCase  (							lowerCamelCase__   ):


			'''simple docstring'''

			def __init__(							self					:			List[str]							,					lowerCAmelCase__					:			PriorTransformer							,					lowerCAmelCase__					:			CLIPTextModelWithProjection							,					lowerCAmelCase__					:			CLIPTokenizer							,					lowerCAmelCase__					:			HeunDiscreteScheduler							,					lowerCAmelCase__					:			ShapERenderer							,					):





					"""simple docstring"""






					super().__init__()

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

			def UpperCamelCase__ (							self					:			Tuple							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			List[str]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Dict							,					lowerCAmelCase__					:			List[Any]							,					lowerCAmelCase__					:			int						):





					"""simple docstring"""






					if latents is None:
							__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		randn_tensor(lowerCAmelCase__							,					generator=lowerCAmelCase__							,					device=lowerCAmelCase__							,					dtype=lowerCAmelCase__						)
					else:
							if latents.shape != shape:
									raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"						)
							__SCREAMING_SNAKE_CASE	:		Any   	=		latents.to(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		latents * scheduler.init_noise_sigma
					return latents

			def UpperCamelCase__ (							self					:			str							,					lowerCAmelCase__					:			int=0						):





					"""simple docstring"""






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

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		[self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
							if cpu_offloaded_model is not None:
									cpu_offload(lowerCAmelCase__							,					lowerCAmelCase__						)

			def UpperCamelCase__ (							self					:			int							,					lowerCAmelCase__					:			str=0						):





					"""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	:		List[str]   	=		torch.device(F"cuda:{gpu_id}"						)

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

					__SCREAMING_SNAKE_CASE	:		List[str]   	=		None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Dict   	=		cpu_offload_with_hook(lowerCAmelCase__							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					if self.safety_checker is not None:
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[str]   	=		cpu_offload_with_hook(self.safety_checker							,					lowerCAmelCase__							,					prev_module_hook=lowerCAmelCase__						)

					# We'll offload the last model manually.
					__SCREAMING_SNAKE_CASE	:		str   	=		hook

			@property
			def UpperCamelCase__ (							self					:			List[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(lowerCAmelCase__							,					"""_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[int]							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Any							,					lowerCAmelCase__					:			Tuple							,					):





					"""simple docstring"""






					len(lowerCAmelCase__						) if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						) 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	:		Union[str, Any]   	=		0
					# get prompt text embeddings
					__SCREAMING_SNAKE_CASE	:		Tuple   	=		self.tokenizer(
					    lowerCAmelCase__							,					padding="""max_length"""							,					max_length=self.tokenizer.model_max_length							,					truncation=lowerCAmelCase__							,					return_tensors="""pt"""							,					)
					__SCREAMING_SNAKE_CASE	:		str   	=		text_inputs.input_ids
					__SCREAMING_SNAKE_CASE	:		Dict   	=		self.tokenizer(lowerCAmelCase__							,					padding="""longest"""							,					return_tensors="""pt"""						).input_ids

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Dict   	=		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	:		Any   	=		self.text_encoder(text_input_ids.to(lowerCAmelCase__						)						)
					__SCREAMING_SNAKE_CASE	:		Any   	=		text_encoder_output.text_embeds

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		prompt_embeds.repeat_interleave(lowerCAmelCase__							,					dim=0						)
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					__SCREAMING_SNAKE_CASE	:		Optional[int]   	=		prompt_embeds / torch.linalg.norm(lowerCAmelCase__							,					dim=-1							,					keepdim=lowerCAmelCase__						)

					if do_classifier_free_guidance:
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		torch.zeros_like(lowerCAmelCase__						)

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

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

					return prompt_embeds



			@torch.no_grad()
			@replace_example_docstring(lowerCAmelCase__						)
			def __call__(							self					:			Union[str, Any]							,					lowerCAmelCase__					:			str							,					lowerCAmelCase__					:			int = 1							,					lowerCAmelCase__					:			int = 2_5							,					lowerCAmelCase__					:			Optional[Union[torch.Generator, List[torch.Generator]]] = None							,					lowerCAmelCase__					:			Optional[torch.FloatTensor] = None							,					lowerCAmelCase__					:			float = 4.0							,					lowerCAmelCase__					:			int = 6_4							,					lowerCAmelCase__					:			Optional[str] = "pil"							,					lowerCAmelCase__					:			bool = True							,					):





					"""simple docstring"""






					if isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		str   	=		1
					elif isinstance(lowerCAmelCase__							,					lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		len(lowerCAmelCase__						)
					else:
							raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase__						)}"						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		self._execution_device

					__SCREAMING_SNAKE_CASE	:		str   	=		batch_size * num_images_per_prompt

					__SCREAMING_SNAKE_CASE	:		str   	=		guidance_scale > 1.0
					__SCREAMING_SNAKE_CASE	:		int   	=		self._encode_prompt(lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__						)

					# prior

					self.scheduler.set_timesteps(lowerCAmelCase__							,					device=lowerCAmelCase__						)
					__SCREAMING_SNAKE_CASE	:		Union[str, Any]   	=		self.scheduler.timesteps

					__SCREAMING_SNAKE_CASE	:		Optional[Any]   	=		self.prior.config.num_embeddings
					__SCREAMING_SNAKE_CASE	:		int   	=		self.prior.config.embedding_dim

					__SCREAMING_SNAKE_CASE	:		str   	=		self.prepare_latents(
					    (batch_size, num_embeddings * embedding_dim)							,					prompt_embeds.dtype							,					lowerCAmelCase__							,					lowerCAmelCase__							,					lowerCAmelCase__							,					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	:		Optional[Any]   	=		latents.reshape(latents.shape[0]							,					lowerCAmelCase__							,					lowerCAmelCase__						)

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

							__SCREAMING_SNAKE_CASE	:		str   	=		self.prior(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					proj_embedding=lowerCAmelCase__							,					).predicted_image_embedding

							# remove the variance
							__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		List[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:
									__SCREAMING_SNAKE_CASE	,						__SCREAMING_SNAKE_CASE	:		Any   	=		noise_pred.chunk(2						)
									__SCREAMING_SNAKE_CASE	:		str   	=		noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							__SCREAMING_SNAKE_CASE	:		str   	=		self.scheduler.step(
							    lowerCAmelCase__							,					timestep=lowerCAmelCase__							,					sample=lowerCAmelCase__							,					).prev_sample

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

					__SCREAMING_SNAKE_CASE	:		Dict   	=		[]
					for i, latent in enumerate(lowerCAmelCase__						):
							__SCREAMING_SNAKE_CASE	:		List[Any]   	=		self.renderer.decode(
							    latent[None, :]							,					lowerCAmelCase__							,					size=lowerCAmelCase__							,					ray_batch_size=4_0_9_6							,					n_coarse_samples=6_4							,					n_fine_samples=1_2_8							,					)
							images.append(lowerCAmelCase__						)

					__SCREAMING_SNAKE_CASE	:		Dict   	=		torch.stack(lowerCAmelCase__						)

					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	:		str   	=		images.cpu().numpy()

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