




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

UpperCAmelCase_       :  Any      =		'''
    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     lowerCAmelCase   ( UpperCamelCase__):
       __lowercase  :      str        =			42





class     lowerCAmelCase   ( UpperCamelCase__):


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  )      ->  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       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  )      ->  List[str]:



            '''simple docstring'''




            if latents is None:
                 __snake_case    					=  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}'''  )
                 __snake_case    					=  latents.to(snake_case_  )

            __snake_case    					=  latents * scheduler.init_noise_sigma
            return latents


       def       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE=0  )      ->  str:



            '''simple docstring'''




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

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

            __snake_case    					=  [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       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE=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.'''  )

            __snake_case    					=  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)

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

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

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


       @property
       def       lowerCAmelCase      (   self  )      ->  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       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  )      ->  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
            __snake_case    					=  0
            # get prompt text embeddings
            __snake_case    					=  self.tokenizer(
                snake_case_    ,  padding='''max_length'''    ,  max_length=self.tokenizer.model_max_length    ,  truncation=snake_case_    ,  return_tensors='''pt'''    ,  )
            __snake_case    					=  text_inputs.input_ids
            __snake_case    					=  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_  ):
                 __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}'''  )

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

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

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

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

            return prompt_embeds




       @torch.no_grad()
       @replace_example_docstring(snake_case_  )
       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    ,  )      ->  Dict:



            '''simple docstring'''




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

            __snake_case    					=  self._execution_device

            __snake_case    					=  batch_size * num_images_per_prompt

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

            # prior

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

            __snake_case    					=  self.prior.config.num_embeddings
            __snake_case    					=  self.prior.config.embedding_dim

            __snake_case    					=  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
            __snake_case    					=  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
                 __snake_case    					=  torch.cat([latents] * 2  ) if do_classifier_free_guidance else latents
                 __snake_case    					=  self.scheduler.scale_model_input(snake_case_    ,  snake_case_  )

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

                 # remove the variance
                 __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:
                      __snake_case    					=  noise_pred.chunk(2  )
                      __snake_case    					=  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

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

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

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

            __snake_case    					=  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}'''  )

            __snake_case    					=  images.cpu().numpy()

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








'''simple docstring'''



# Copyright 2022 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from typing import List







def 			_UpperCamelCase (_lowerCamelCase							:     List[str]   ,	_lowerCamelCase							:     str	)->   str:




     '''simple docstring'''





     if name != "training_function" and name != "main":
          raise ValueError(f'''Incorrect function name passed: {name}, choose either \'main\' or \'training_function\''''	)
     __snake_case					,    __snake_case    					=  [], False
     for line in lines:
          if not found_start and f'''def {name}''' in line:
               __snake_case    					=  True
               good_lines.append(_lowerCamelCase	)
               continue
          if found_start:
               if name == "training_function" and "def main" in line:
                    return good_lines
               if name == "main" and "if __name__" in line:
                    return good_lines
               good_lines.append(_lowerCamelCase	)







def 			_UpperCamelCase (_lowerCamelCase							:     List[str]	)->   int:




     '''simple docstring'''





     return [line for line in lines if not line.lstrip().startswith('''#'''	) and line != "\n"]







def 			_UpperCamelCase (_lowerCamelCase							:     str   ,	_lowerCamelCase							:     str   ,	_lowerCamelCase							:     bool   ,	_lowerCamelCase							:     str = None	)->   Optional[Any]:




     '''simple docstring'''





     with open(_lowerCamelCase   ,	'''r'''	) as f:
          __snake_case    					=  f.readlines()
     with open(os.path.abspath(os.path.join('''examples'''   ,	'''nlp_example.py'''	)	)   ,	'''r'''	) as f:
          __snake_case    					=  f.readlines()
     with open(_lowerCamelCase   ,	'''r'''	) as f:
          __snake_case    					=  f.readlines()
     if secondary_filename is not None:
          with open(_lowerCamelCase   ,	'''r'''	) as f:
               __snake_case    					=  f.readlines()

    # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content
     if parser_only:
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''main'''	)	)
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''main'''	)	)
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''main'''	)	)
          if secondary_filename is not None:
               __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''main'''	)	)
     else:
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''training_function'''	)	)
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''training_function'''	)	)
          __snake_case    					=  clean_lines(get_function_contents_by_name(_lowerCamelCase   ,	'''training_function'''	)	)
          if secondary_filename is not None:
               __snake_case    					=  clean_lines(
                   get_function_contents_by_name(_lowerCamelCase   ,	'''training_function'''	)	)

     __snake_case    					=  '''train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n'''

     # Specific code in our script that differs from the full version, aka what is new
     __snake_case    					=  []
     __snake_case    					=  []  # We keep track of the idxs just in case it's a repeated statement
     __snake_case    					=  iter(_lowerCamelCase	)
     for i in range(len(_lowerCamelCase	) - 1	):
          if i not in passed_idxs:
               __snake_case    					=  next(_lowerCamelCase	)
               if (line not in full_file_func) and (line.lstrip() != _dl_line):
                    if "TESTING_MOCKED_DATALOADERS" not in line:
                         new_feature_code.append(_lowerCamelCase	)
                         passed_idxs.append(_lowerCamelCase	)
                    else:
                         # Skip over the `config['num_epochs'] = 2` statement
                         __snake_case    					=  next(_lowerCamelCase	)

    # Extract out just the new parts from the full_file_training_func
     __snake_case    					=  []
     __snake_case    					=  []  # We keep track of the idxs just in case it's a repeated statement
     for i, line in enumerate(_lowerCamelCase	):
          if i not in passed_idxs:
               if (line not in full_file_func) and (line.lstrip() != _dl_line):
                    if "TESTING_MOCKED_DATALOADERS" not in line:
                         new_full_example_parts.append(_lowerCamelCase	)
                         passed_idxs.append(_lowerCamelCase	)

    # Finally, get the overall diff
     __snake_case    					=  [line for line in new_feature_code if line not in new_full_example_parts]
     if secondary_filename is not None:
          __snake_case    					=  [line for line in full_file_contents if line not in secondary_file_func]
          __snake_case    					=  [line for line in diff_from_example if line not in diff_from_two]

     return diff_from_example






