


'''simple docstring'''






import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


a_       :     Optional[int] 							=     logging.getLogger(__name__)

require_version("pytorch_lightning>=1.0.4")

a_       :     int 							=     {
    "base": AutoModel,
    "sequence-classification": AutoModelForSequenceClassification,
    "question-answering": AutoModelForQuestionAnswering,
    "pretraining": AutoModelForPreTraining,
    "token-classification": AutoModelForTokenClassification,
    "language-modeling": AutoModelWithLMHead,
    "summarization": AutoModelForSeqaSeqLM,
    "translation": AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
a_       :     List[Any] 							=     {
    "linear": get_linear_schedule_with_warmup,
    "cosine": get_cosine_schedule_with_warmup,
    "cosine_w_restarts": get_cosine_with_hard_restarts_schedule_with_warmup,
    "polynomial": get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
a_       :     int 							=     sorted(arg_to_scheduler.keys())
a_       :     Dict 							=     "{" + ", ".join(arg_to_scheduler_choices) + "}"




class 			a  (  pl.LightningModule							):
 def __init__(			self   ,					__magic_name__   ,					__magic_name__=None   ,					__magic_name__="base"   ,					__magic_name__=None   ,					__magic_name__=None   ,					__magic_name__=None   ,					**__magic_name__   ,					)       ->				int:
      super().__init__()
      # TODO: move to self.save_hyperparameters()
      # self.save_hyperparameters()
      # can also expand arguments into trainer signature for easier reading

      self.save_hyperparameters(A_    )
      _a         =				0
      _a         =				Path(self.hparams.output_dir    )
      _a         =				self.hparams.cache_dir if self.hparams.cache_dir else None
      if config is None:
           _a         =				AutoConfig.from_pretrained(
               self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path   ,					**({'num_labels': num_labels} if num_labels is not None else {})   ,					cache_dir=A_   ,					**A_   ,					)
      else:
           _a         =				config

      _a         =				("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
      for p in extra_model_params:
           if getattr(self.hparams   ,					A_   ,					A_    ):
                assert hasattr(self.config   ,					A_    ), f'model config doesn\'t have a `{p}` attribute'
                setattr(self.config   ,					A_   ,					getattr(self.hparams   ,					A_    )    )

      if tokenizer is None:
           _a         =				AutoTokenizer.from_pretrained(
               self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path   ,					cache_dir=A_   ,					)
      else:
           _a         =				tokenizer
      _a         =				MODEL_MODES[mode]
      if model is None:
           _a         =				self.model_type.from_pretrained(
               self.hparams.model_name_or_path   ,					from_tf=bool('.ckpt' in self.hparams.model_name_or_path    )   ,					config=self.config   ,					cache_dir=A_   ,					)
      else:
           _a         =				model
 def 				__UpperCAmelCase		(			self   ,					*__magic_name__   ,					**__magic_name__    )       ->				Tuple:
      _a         =				self.model_type.from_pretrained(*A_   ,					**A_    )
 def 				__UpperCAmelCase		(			self    )       ->				List[str]:
      _a         =				arg_to_scheduler[self.hparams.lr_scheduler]
      _a         =				get_schedule_func(
          self.opt   ,					num_warmup_steps=self.hparams.warmup_steps   ,					num_training_steps=self.total_steps()    )
      _a         =				{"scheduler": scheduler, "interval": "step", "frequency": 1}
      return scheduler
 def 				__UpperCAmelCase		(			self    )       ->				str:
      _a         =				self.model
      _a         =				["bias", "LayerNorm.weight"]
      _a         =				[
          {
              "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay    )],
              "weight_decay": self.hparams.weight_decay,
          },
          {
              "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay    )],
              "weight_decay": 0.0,
          },
      ]
      if self.hparams.adafactor:
           _a         =				Adafactor(
               A_   ,					lr=self.hparams.learning_rate   ,					scale_parameter=A_   ,					relative_step=A_    )

      else:
           _a         =				AdamW(
               A_   ,					lr=self.hparams.learning_rate   ,					eps=self.hparams.adam_epsilon    )
      _a         =				optimizer

      _a         =				self.get_lr_scheduler()

      return [optimizer], [scheduler]
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__    )       ->				Optional[int]:
      return self.validation_step(A_   ,					A_    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				Optional[Any]:
      return self.validation_end(A_    )
 def 				__UpperCAmelCase		(			self    )       ->				str:
      _a         =				max(1   ,					self.hparams.gpus    )  # TODO: consider num_tpu_cores
      _a         =				self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
      return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				List[str]:




      if mode == "test":
           _a         =				len(self.test_dataloader().dataset    )
      else:
           _a         =				self.get_dataloader('train'   ,					self.hparams.train_batch_size   ,					shuffle=A_    )
           _a         =				len(self.train_dataloader().dataset    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__   ,					__magic_name__ = False    )       ->				Tuple:
      raise NotImplementedError('You must implement this for your task'    )
 def 				__UpperCAmelCase		(			self    )       ->				Any:
      return self.train_loader
 def 				__UpperCAmelCase		(			self    )       ->				Dict:
      return self.get_dataloader('dev'   ,					self.hparams.eval_batch_size   ,					shuffle=A_    )
 def 				__UpperCAmelCase		(			self    )       ->				Any:
      return self.get_dataloader('test'   ,					self.hparams.eval_batch_size   ,					shuffle=A_    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				List[Any]:
      return os.path.join(
          self.hparams.data_dir   ,					'cached_{}_{}_{}'.format(
              A_   ,					list(filter(A_   ,					self.hparams.model_name_or_path.split('/'    )    )    ).pop()   ,					str(self.hparams.max_seq_length    )   ,					)   ,					)
 @pl.utilities.rank_zero_only
 def 				__UpperCAmelCase		(			self   ,					__magic_name__    )       ->				List[Any]:
      _a         =				self.output_dir.joinpath('best_tfmr'    )
      _a         =				self.step_count
      self.model.save_pretrained(A_    )
      self.tokenizer.save_pretrained(A_    )




 @staticmethod
 def 				__UpperCAmelCase		(			__magic_name__   ,					__magic_name__    )       ->				List[str]:
      parser.add_argument(
          '--model_name_or_path'   ,					default=A_   ,					type=A_   ,					required=A_   ,					help='Path to pretrained model or model identifier from huggingface.co/models'   ,					)
      parser.add_argument(
          '--config_name'   ,					default=''   ,					type=A_   ,					help='Pretrained config name or path if not the same as model_name'    )
      parser.add_argument(
          '--tokenizer_name'   ,					default=A_   ,					type=A_   ,					help='Pretrained tokenizer name or path if not the same as model_name'   ,					)
      parser.add_argument(
          '--cache_dir'   ,					default=''   ,					type=A_   ,					help='Where do you want to store the pre-trained models downloaded from huggingface.co'   ,					)
      parser.add_argument(
          '--encoder_layerdrop'   ,					type=A_   ,					help='Encoder layer dropout probability (Optional). Goes into model.config'   ,					)
      parser.add_argument(
          '--decoder_layerdrop'   ,					type=A_   ,					help='Decoder layer dropout probability (Optional). Goes into model.config'   ,					)
      parser.add_argument(
          '--dropout'   ,					type=A_   ,					help='Dropout probability (Optional). Goes into model.config'   ,					)
      parser.add_argument(
          '--attention_dropout'   ,					type=A_   ,					help='Attention dropout probability (Optional). Goes into model.config'   ,					)
      parser.add_argument('--learning_rate'   ,					default=5e-5   ,					type=A_   ,					help='The initial learning rate for Adam.'    )
      parser.add_argument(
          '--lr_scheduler'   ,					default='linear'   ,					choices=A_   ,					metavar=A_   ,					type=A_   ,					help='Learning rate scheduler'   ,					)
      parser.add_argument('--weight_decay'   ,					default=0.0   ,					type=A_   ,					help='Weight decay if we apply some.'    )
      parser.add_argument('--adam_epsilon'   ,					default=1e-8   ,					type=A_   ,					help='Epsilon for Adam optimizer.'    )
      parser.add_argument('--warmup_steps'   ,					default=0   ,					type=A_   ,					help='Linear warmup over warmup_steps.'    )
      parser.add_argument('--num_workers'   ,					default=4   ,					type=A_   ,					help='kwarg passed to DataLoader'    )
      parser.add_argument('--num_train_epochs'   ,					dest='max_epochs'   ,					default=3   ,					type=A_    )
      parser.add_argument('--train_batch_size'   ,					default=32   ,					type=A_    )
      parser.add_argument('--eval_batch_size'   ,					default=32   ,					type=A_    )
      parser.add_argument('--adafactor'   ,					action='store_true'    )





class 			a  (  pl.Callback							):
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__    )       ->				Dict:
      _a         =				trainer.lr_schedulers[0]["scheduler"]
      _a         =				{f'lr_group_{i}': lr for i, lr in enumerate(lr_scheduler.get_lr()    )}
      pl_module.logger.log_metrics(A_    )
 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__    )       ->				str:
      rank_zero_info('***** Validation results *****'    )
      _a         =				trainer.callback_metrics
      # Log results
      for key in sorted(A_    ):
           if key not in ["log", "progress_bar"]:
                rank_zero_info('{} = {}\n'.format(A_   ,					str(metrics[key]    )    )    )




 def 				__UpperCAmelCase		(			self   ,					__magic_name__   ,					__magic_name__    )       ->				Optional[int]:
      rank_zero_info('***** Test results *****'    )
      _a         =				trainer.callback_metrics
      # Log and save results to file
      _a         =				os.path.join(pl_module.hparams.output_dir   ,					'test_results.txt'    )
      with open(A_   ,					'w'    ) as writer:
           for key in sorted(A_    ):
                if key not in ["log", "progress_bar"]:
                     rank_zero_info('{} = {}\n'.format(A_   ,					str(metrics[key]    )    )    )
                     writer.write('{} = {}\n'.format(A_   ,					str(metrics[key]    )    )    )






def 						_A					(lowerCAmelCase__	:List[Any]					,    lowerCAmelCase__	:Optional[Any]		) ->	None:




     '''simple docstring'''



     parser.add_argument(
         '--output_dir'					,    default=lowerCAmelCase__					,    type=lowerCAmelCase__					,    required=lowerCAmelCase__					,    help='The output directory where the model predictions and checkpoints will be written.'					,    )
     parser.add_argument(
         '--fp16'					,    action='store_true'					,    help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'					,    )

     parser.add_argument(
         '--fp16_opt_level'					,    type=lowerCAmelCase__					,    default='O2'					,    help=(
             'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'
             'See details at https://nvidia.github.io/apex/amp.html'
         )					,    )
     parser.add_argument('--n_tpu_cores'					,    dest='tpu_cores'					,    type=lowerCAmelCase__		)
     parser.add_argument('--max_grad_norm'					,    dest='gradient_clip_val'					,    default=1.0					,    type=lowerCAmelCase__					,    help='Max gradient norm'		)
     parser.add_argument('--do_train'					,    action='store_true'					,    help='Whether to run training.'		)
     parser.add_argument('--do_predict'					,    action='store_true'					,    help='Whether to run predictions on the test set.'		)
     parser.add_argument(
         '--gradient_accumulation_steps'					,    dest='accumulate_grad_batches'					,    type=lowerCAmelCase__					,    default=1					,    help='Number of updates steps to accumulate before performing a backward/update pass.'					,    )
     parser.add_argument('--seed'					,    type=lowerCAmelCase__					,    default=42					,    help='random seed for initialization'		)
     parser.add_argument(
         '--data_dir'					,    default=lowerCAmelCase__					,    type=lowerCAmelCase__					,    required=lowerCAmelCase__					,    help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.'					,    )






def 						_A					(lowerCAmelCase__	:List[Any]					,    lowerCAmelCase__	:str					,    lowerCAmelCase__	:Optional[Any]=None					,    lowerCAmelCase__	:Dict=True					,    lowerCAmelCase__	:List[str]=[]					,    lowerCAmelCase__	:int=None					,    lowerCAmelCase__	:Any=None					,    **lowerCAmelCase__	:Any					,    ) ->	Dict:




     '''simple docstring'''



     pl.seed_everything(args.seed		)

     # init model
     _a         =				Path(model.hparams.output_dir		)
     odir.mkdir(exist_ok=lowerCAmelCase__		)

     # add custom checkpoints
     if checkpoint_callback is None:
          _a         =				pl.callbacks.ModelCheckpoint(
              filepath=args.output_dir					,    prefix='checkpoint'					,    monitor='val_loss'					,    mode='min'					,    save_top_k=1		)
     if early_stopping_callback:
          extra_callbacks.append(lowerCAmelCase__		)
     if logging_callback is None:
          _a         =				LoggingCallback()

     _a         =				{}

     # TODO: remove with PyTorch 1.6 since pl uses native amp
     if args.fpaa:
          _a         =				16
          _a         =				args.fpaa_opt_level

     if args.gpus > 1:
          _a         =				"ddp"

     _a         =				args.accumulate_grad_batches
     _a         =				extra_train_kwargs.get('accelerator'					,    lowerCAmelCase__		)
     _a         =				extra_train_kwargs.get('profiler'					,    lowerCAmelCase__		)

     _a         =				pl.Trainer.from_argparse_args(
         lowerCAmelCase__					,    weights_summary=lowerCAmelCase__					,    callbacks=[logging_callback] + extra_callbacks					,    logger=lowerCAmelCase__					,    checkpoint_callback=lowerCAmelCase__					,    **lowerCAmelCase__					,    )

     if args.do_train:
          trainer.fit(lowerCAmelCase__		)

     return trainer




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

__UpperCAmelCase     					=  '\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__     (			A			):



 """simple docstring"""







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





class A__     (			A			):



 """simple docstring"""







 def __init__(		self			:						Dict  ,    A_			:						PriorTransformer  ,    A_			:						CLIPTextModelWithProjection  ,    A_			:						CLIPTokenizer  ,    A_			:						HeunDiscreteScheduler  ,    A_			:						ShapERenderer  ,    ):






      '''simple docstring'''




      super().__init__()

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

 def  __magic_name__							(		self			:						Tuple  ,    A_			:						List[Any]  ,    A_			:						Optional[Any]  ,    A_			:						int  ,    A_			:						Optional[Any]  ,    A_			:						str  ,    A_			:						Dict							):






      '''simple docstring'''




      if latents is None:
           _lowerCAmelCase :       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}'''							)
           _lowerCAmelCase :       Union[str, Any]	   =     latents.to(A_							)

      _lowerCAmelCase :       Union[str, Any]	   =     latents * scheduler.init_noise_sigma
      return latents

 def  __magic_name__							(		self			:						Any  ,    A_			:						List[Any]=0							):






      '''simple docstring'''




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

      _lowerCAmelCase :       int	   =     torch.device(F'''cuda:{gpu_id}'''							)

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

 def  __magic_name__							(		self			:						List[str]  ,    A_			:						List[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."							)

      _lowerCAmelCase :       Optional[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)

      _lowerCAmelCase :       Union[str, Any]	   =     None
      for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
           _lowerCAmelCase   ,      _lowerCAmelCase :       Optional[int]	   =     cpu_offload_with_hook(A_  ,    A_  ,    prev_module_hook=A_							)

      if self.safety_checker is not None:
           _lowerCAmelCase   ,      _lowerCAmelCase :       Optional[Any]	   =     cpu_offload_with_hook(self.safety_checker  ,    A_  ,    prev_module_hook=A_							)

      # We'll offload the last model manually.
      _lowerCAmelCase :       Any	   =     hook

 @property
 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''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  __magic_name__							(		self			:						str  ,    A_			:						List[str]  ,    A_			:						Optional[int]  ,    A_			:						List[str]  ,    A_			:						str  ,    ):






      '''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
      _lowerCAmelCase :       Dict	   =     0
      # get prompt text embeddings
      _lowerCAmelCase :       Any	   =     self.tokenizer(
          A_  ,    padding="max_length"  ,    max_length=self.tokenizer.model_max_length  ,    truncation=A_  ,    return_tensors="pt"  ,    )
      _lowerCAmelCase :       List[Any]	   =     text_inputs.input_ids
      _lowerCAmelCase :       Any	   =     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_							):
           _lowerCAmelCase :       Any	   =     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}'''							)

      _lowerCAmelCase :       Any	   =     self.text_encoder(text_input_ids.to(A_							)							)
      _lowerCAmelCase :       Union[str, Any]	   =     text_encoder_output.text_embeds

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

      if do_classifier_free_guidance:
           _lowerCAmelCase :       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
           _lowerCAmelCase :       Union[str, Any]	   =     torch.cat([negative_prompt_embeds, prompt_embeds]							)

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

      return prompt_embeds


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






      '''simple docstring'''




      if isinstance(A_  ,    A_							):
           _lowerCAmelCase :       Tuple	   =     1
      elif isinstance(A_  ,    A_							):
           _lowerCAmelCase :       List[Any]	   =     len(A_							)
      else:
           raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(A_							)}'''							)

      _lowerCAmelCase :       int	   =     self._execution_device

      _lowerCAmelCase :       int	   =     batch_size * num_images_per_prompt

      _lowerCAmelCase :       List[Any]	   =     guidance_scale > 1.0
      _lowerCAmelCase :       Tuple	   =     self._encode_prompt(A_  ,    A_  ,    A_  ,    A_							)

      # prior

      self.scheduler.set_timesteps(A_  ,    device=A_							)
      _lowerCAmelCase :       List[str]	   =     self.scheduler.timesteps

      _lowerCAmelCase :       Dict	   =     self.prior.config.num_embeddings
      _lowerCAmelCase :       int	   =     self.prior.config.embedding_dim

      _lowerCAmelCase :       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
      _lowerCAmelCase :       int	   =     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
           _lowerCAmelCase :       Any	   =     torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
           _lowerCAmelCase :       Optional[int]	   =     self.scheduler.scale_model_input(A_  ,    A_							)

           _lowerCAmelCase :       Optional[int]	   =     self.prior(
               A_  ,    timestep=A_  ,    proj_embedding=A_  ,    ).predicted_image_embedding

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

           if do_classifier_free_guidance is not None:
                _lowerCAmelCase   ,      _lowerCAmelCase :       int	   =     noise_pred.chunk(2							)
                _lowerCAmelCase :       Any	   =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

           _lowerCAmelCase :       str	   =     self.scheduler.step(
               A_  ,    timestep=A_  ,    sample=A_  ,    ).prev_sample

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

      _lowerCAmelCase :       Optional[Any]	   =     []
      for i, latent in enumerate(A_							):
           _lowerCAmelCase :       Optional[int]	   =     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_							)

      _lowerCAmelCase :       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}'''							)

      _lowerCAmelCase :       List[Any]	   =     images.cpu().numpy()

      if output_type == "pil":
           _lowerCAmelCase :       Optional[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_							)






