

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


SCREAMING_SNAKE_CASE_  :      int							=      logging.get_logger(__name__)  # pylint: disable=invalid-name

SCREAMING_SNAKE_CASE_  :      Optional[int]							=      '''
    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 		_A							(      __a       ):
      __a             =						42






class 		_A							(      __a       ):





      def __init__(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    ) ->       Optional[Any]:
         super().__init__()

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





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		) ->       Any:
         if latents is None:
            lowerCamelCase__						       =      randn_tensor(SCREAMING_SNAKE_CASE__     ,    generator=SCREAMING_SNAKE_CASE__     ,    device=SCREAMING_SNAKE_CASE__     ,    dtype=SCREAMING_SNAKE_CASE__		)
         else:
            if latents.shape != shape:
               raise ValueError(f'Unexpected latents shape, got {latents.shape}, expected {shape}'		)
            lowerCamelCase__						       =      latents.to(SCREAMING_SNAKE_CASE__		)

         lowerCamelCase__						       =      latents * scheduler.init_noise_sigma
         return latents





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__=0		) ->       str:
         if is_accelerate_available():
            from accelerate import cpu_offload
         else:
            raise ImportError("Please install accelerate via `pip install accelerate`"		)

         lowerCamelCase__						       =      torch.device(f'cuda:{gpu_id}'		)

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





      def        _lowerCamelCase	(	self     ,    SCREAMING_SNAKE_CASE__=0		) ->       List[str]:
         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__						       =      torch.device(f'cuda:{gpu_id}'		)

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

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

         if self.safety_checker is not None:
            lowerCamelCase__       ,							lowerCamelCase__						       =      cpu_offload_with_hook(self.safety_checker     ,    SCREAMING_SNAKE_CASE__     ,    prev_module_hook=SCREAMING_SNAKE_CASE__		)

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





      @property
      def        _lowerCamelCase	(	self		) ->       Union[str, Any]:
         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(SCREAMING_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__     ,    ) ->       Union[str, Any]:
         len(SCREAMING_SNAKE_CASE__		) if isinstance(SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		) else 1

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

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

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

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

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

         return prompt_embeds





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

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

         lowerCamelCase__						       =      self._execution_device

         lowerCamelCase__						       =      batch_size * num_images_per_prompt

         lowerCamelCase__						       =      guidance_scale > 1.0
         lowerCamelCase__						       =      self._encode_prompt(SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__     ,    SCREAMING_SNAKE_CASE__		)

         # prior

         self.scheduler.set_timesteps(SCREAMING_SNAKE_CASE__     ,    device=SCREAMING_SNAKE_CASE__		)
         lowerCamelCase__						       =      self.scheduler.timesteps

         lowerCamelCase__						       =      self.prior.config.num_embeddings
         lowerCamelCase__						       =      self.prior.config.embedding_dim

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

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

            lowerCamelCase__						       =      self.prior(
                SCREAMING_SNAKE_CASE__     ,    timestep=SCREAMING_SNAKE_CASE__     ,    proj_embedding=SCREAMING_SNAKE_CASE__     ,    ).predicted_image_embedding

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

            lowerCamelCase__						       =      self.scheduler.step(
                SCREAMING_SNAKE_CASE__     ,    timestep=SCREAMING_SNAKE_CASE__     ,    sample=SCREAMING_SNAKE_CASE__     ,    ).prev_sample

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

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

         lowerCamelCase__						       =      torch.stack(SCREAMING_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}'		)

         lowerCamelCase__						       =      images.cpu().numpy()

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







"""simple docstring"""




import numpy as np
from numpy import floataa
from numpy.typing import NDArray



def 						UpperCAmelCase__ (					A__						,     A__ )   ->   NDArray[floataa]:




   """simple docstring"""
   lowerCamelCase__       ,							lowerCamelCase__						       =      np.shape(A__ )

   lowerCamelCase__						       =      np.zeros((rows, 1)						,     dtype=A__ )
   for row in reversed(range(A__ ) ):
      lowerCamelCase__						       =      0
      for col in range(row + 1						,     A__ ):
         total += coefficients[row, col] * x[col]

      lowerCamelCase__						       =      (vector[row] - total) / coefficients[row, row]

   return x



def 						UpperCAmelCase__ (					A__						,     A__ )   ->   NDArray[floataa]:




   """simple docstring"""
   lowerCamelCase__       ,							lowerCamelCase__						       =      np.shape(A__ )
   if rows != columns:
      return np.array(()						,     dtype=A__ )

   # augmented matrix
   lowerCamelCase__						       =      np.concatenate((coefficients, vector)						,     axis=1 )
   lowerCamelCase__						       =      augmented_mat.astype("float64" )

   # scale the matrix leaving it triangular
   for row in range(rows - 1 ):
      lowerCamelCase__						       =      augmented_mat[row, row]
      for col in range(row + 1						,     A__ ):
         lowerCamelCase__						       =      augmented_mat[col, row] / pivot
         augmented_mat[col, :] -= factor * augmented_mat[row, :]

   lowerCamelCase__						       =      retroactive_resolution(
       augmented_mat[:, 0:columns]						,     augmented_mat[:, columns : columns + 1] )

   return x


if __name__ == "__main__":
     import doctest

     doctest.testmod()




