


"""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    				=      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  lowercase_  ( a_						):
      __magic_name__     :							Union[List[List[PIL.Image.Image]], List[List[np.ndarray]]]

class  lowercase_  ( a_						):







      def __init__(      self :							Tuple		,  _lowercase :							PriorTransformer		,  _lowercase :							CLIPTextModelWithProjection		,  _lowercase :							CLIPTokenizer		,  _lowercase :							HeunDiscreteScheduler		,  _lowercase :							ShapERenderer		,  ):
        super().__init__()

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







      def 				_lowerCAmelCase       (      self :							Union[str, Any]		,  _lowercase :							List[Any]		,  _lowercase :							str		,  _lowercase :							Any		,  _lowercase :							Any		,  _lowercase :							Any		,  _lowercase :							List[str]    ):
        if latents is None:
          lowerCAmelCase__    :    List[Any]								=					randn_tensor(_lowercase		,  generator=_lowercase		,  device=_lowercase		,  dtype=_lowercase    )
        else:
          if latents.shape != shape:
            raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}"    )
          lowerCAmelCase__    :    List[Any]								=					latents.to(_lowercase    )

        lowerCAmelCase__    :    Dict								=					latents * scheduler.init_noise_sigma
        return latents







      def 				_lowerCAmelCase       (      self :							int		,  _lowercase :							List[Any]=0    ):
        if is_accelerate_available():
          from accelerate import cpu_offload
        else:
          raise ImportError("Please install accelerate via `pip install accelerate`"    )

        lowerCAmelCase__    :    Any								=					torch.device(f"cuda:{gpu_id}"    )

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







      def 				_lowerCAmelCase       (      self :							Optional[Any]		,  _lowercase :							Dict=0    ):
        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__    :    Dict								=					torch.device(f"cuda:{gpu_id}"    )

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

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

        if self.safety_checker is not None:
          lowerCAmelCase__				,		lowerCAmelCase__    :    Union[str, Any]								=					cpu_offload_with_hook(self.safety_checker		,  _lowercase		,  prev_module_hook=_lowercase    )

        # We'll offload the last model manually.
        lowerCAmelCase__    :    Optional[int]								=					hook







      @property
      def 				_lowerCAmelCase       (      self :							Optional[int]    ):
        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(_lowercase		,  "_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 :							Union[str, Any]		,  _lowercase :							Optional[int]		,  _lowercase :							List[Any]		,  _lowercase :							Any		,  _lowercase :							Optional[Any]		,  ):
        len(_lowercase    ) if isinstance(_lowercase		,  _lowercase    ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        lowerCAmelCase__    :    Union[str, Any]								=					0
        # get prompt text embeddings
        lowerCAmelCase__    :    List[Any]								=					self.tokenizer(
            _lowercase		,  padding="max_length"		,  max_length=self.tokenizer.model_max_length		,  truncation=_lowercase		,  return_tensors="pt"		,  )
        lowerCAmelCase__    :    int								=					text_inputs.input_ids
        lowerCAmelCase__    :    Optional[Any]								=					self.tokenizer(_lowercase		,  padding="longest"		,  return_tensors="pt"    ).input_ids

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

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

        if do_classifier_free_guidance:
          lowerCAmelCase__    :    int								=					torch.zeros_like(_lowercase    )

          # 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__    :    Optional[Any]								=					math.sqrt(prompt_embeds.shape[1]    ) * prompt_embeds

        return prompt_embeds







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

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

        lowerCAmelCase__    :    Any								=					self._execution_device

        lowerCAmelCase__    :    Optional[int]								=					batch_size * num_images_per_prompt

        lowerCAmelCase__    :    List[Any]								=					guidance_scale > 1.0
        lowerCAmelCase__    :    int								=					self._encode_prompt(_lowercase		,  _lowercase		,  _lowercase		,  _lowercase    )

        # prior

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

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

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

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

          lowerCAmelCase__    :    Optional[int]								=					self.prior(
              _lowercase		,  timestep=_lowercase		,  proj_embedding=_lowercase		,  ).predicted_image_embedding

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

          lowerCAmelCase__    :    List[Any]								=					self.scheduler.step(
              _lowercase		,  timestep=_lowercase		,  sample=_lowercase		,  ).prev_sample

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

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

        lowerCAmelCase__    :    Union[str, Any]								=					torch.stack(_lowercase    )

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

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




"""simple docstring"""





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__UpperCAmelCase    				=      logging.get_logger(__name__)

__UpperCAmelCase    				=      {
    "facebook/hubert-base-ls960": "https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json",
    # See all Hubert models at https://huggingface.co/models?filter=hubert
}

class  lowercase_  ( a_						):
      __magic_name__     :							List[Any]          =				"""hubert"""







      def __init__(      self :							List[Any]		,  _lowercase :							Optional[int]=3_2		,  _lowercase :							Tuple=7_6_8		,  _lowercase :							List[Any]=1_2		,  _lowercase :							Dict=1_2		,  _lowercase :							Tuple=3_0_7_2		,  _lowercase :							str="gelu"		,  _lowercase :							Optional[int]=0.1		,  _lowercase :							int=0.1		,  _lowercase :							Tuple=0.1		,  _lowercase :							str=True		,  _lowercase :							Optional[Any]=0.0		,  _lowercase :							List[Any]=0.1		,  _lowercase :							Union[str, Any]=0.1		,  _lowercase :							Union[str, Any]=0.02		,  _lowercase :							List[Any]=1e-5		,  _lowercase :							List[Any]="group"		,  _lowercase :							Tuple="gelu"		,  _lowercase :							List[str]=(5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2, 5_1_2)		,  _lowercase :							List[Any]=(5, 2, 2, 2, 2, 2, 2)		,  _lowercase :							Tuple=(1_0, 3, 3, 3, 3, 2, 2)		,  _lowercase :							Any=False		,  _lowercase :							str=1_2_8		,  _lowercase :							int=1_6		,  _lowercase :							str=False		,  _lowercase :							Union[str, Any]=True		,  _lowercase :							Optional[Any]=0.05		,  _lowercase :							List[Any]=1_0		,  _lowercase :							Dict=2		,  _lowercase :							Optional[int]=0.0		,  _lowercase :							List[str]=1_0		,  _lowercase :							List[str]=0		,  _lowercase :							Optional[Any]="sum"		,  _lowercase :							int=False		,  _lowercase :							Any=False		,  _lowercase :							Optional[Any]=2_5_6		,  _lowercase :							int=0		,  _lowercase :							Optional[int]=1		,  _lowercase :							List[Any]=2		,  **_lowercase :							Tuple		,  ):
        super().__init__(**_lowercase		,  pad_token_id=_lowercase		,  bos_token_id=_lowercase		,  eos_token_id=_lowercase    )
        lowerCAmelCase__    :    Optional[Any]								=					hidden_size
        lowerCAmelCase__    :    int								=					feat_extract_norm
        lowerCAmelCase__    :    Optional[Any]								=					feat_extract_activation
        lowerCAmelCase__    :    Optional[Any]								=					list(_lowercase    )
        lowerCAmelCase__    :    Union[str, Any]								=					list(_lowercase    )
        lowerCAmelCase__    :    Tuple								=					list(_lowercase    )
        lowerCAmelCase__    :    str								=					conv_bias
        lowerCAmelCase__    :    Optional[Any]								=					num_conv_pos_embeddings
        lowerCAmelCase__    :    List[str]								=					num_conv_pos_embedding_groups
        lowerCAmelCase__    :    List[Any]								=					len(self.conv_dim    )
        lowerCAmelCase__    :    Union[str, Any]								=					num_hidden_layers
        lowerCAmelCase__    :    str								=					intermediate_size
        lowerCAmelCase__    :    List[Any]								=					hidden_act
        lowerCAmelCase__    :    Optional[int]								=					num_attention_heads
        lowerCAmelCase__    :    Optional[int]								=					hidden_dropout
        lowerCAmelCase__    :    Dict								=					attention_dropout
        lowerCAmelCase__    :    Dict								=					activation_dropout
        lowerCAmelCase__    :    Optional[Any]								=					feat_proj_layer_norm
        lowerCAmelCase__    :    Union[str, Any]								=					feat_proj_dropout
        lowerCAmelCase__    :    Optional[Any]								=					final_dropout
        lowerCAmelCase__    :    Dict								=					layerdrop
        lowerCAmelCase__    :    Optional[int]								=					layer_norm_eps
        lowerCAmelCase__    :    str								=					initializer_range
        lowerCAmelCase__    :    int								=					vocab_size
        lowerCAmelCase__    :    int								=					do_stable_layer_norm
        lowerCAmelCase__    :    Union[str, Any]								=					use_weighted_layer_sum
        lowerCAmelCase__    :    Tuple								=					classifier_proj_size

        if (
            (len(self.conv_stride    ) != self.num_feat_extract_layers)
            or (len(self.conv_kernel    ) != self.num_feat_extract_layers)
            or (len(self.conv_dim    ) != self.num_feat_extract_layers)
        ):
          raise ValueError(
              "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
              " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
              f" {len(self.conv_dim    )}`, `len(config.conv_stride) = {len(self.conv_stride    )}`,"
              f" `len(config.conv_kernel) = {len(self.conv_kernel    )}`."    )

        # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
        lowerCAmelCase__    :    int								=					apply_spec_augment
        lowerCAmelCase__    :    Tuple								=					mask_time_prob
        lowerCAmelCase__    :    int								=					mask_time_length
        lowerCAmelCase__    :    Dict								=					mask_time_min_masks
        lowerCAmelCase__    :    Union[str, Any]								=					mask_feature_prob
        lowerCAmelCase__    :    Dict								=					mask_feature_length
        lowerCAmelCase__    :    Tuple								=					mask_feature_min_masks

        # ctc loss
        lowerCAmelCase__    :    Tuple								=					ctc_loss_reduction
        lowerCAmelCase__    :    List[str]								=					ctc_zero_infinity







      @property
      def 				_lowerCAmelCase       (      self :							Dict    ):
        return functools.reduce(operator.mul		,  self.conv_stride		,  1    )
