






'''simple docstring'''







from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


_A	:			Optional[int]         =logging.get_logger(__name__)  # pylint: disable=invalid-name

_A	:			str         ='''\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\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], \"corgi_3d.gif\")\n        ```\n'''

@dataclass
class _lowercase	(				_lowercase		):
							a				      =       42



class _lowercase	(				_lowercase		):




							def __init__(							self:				Optional[Any]			,							UpperCamelCase__:				Union[str, Any]			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				Optional[int]			,							UpperCamelCase__:				Union[str, Any]			,							):
														super().__init__()

														self.register_modules(
														    prior=SCREAMING_SNAKE_CASE__			,							image_encoder=SCREAMING_SNAKE_CASE__			,							image_processor=SCREAMING_SNAKE_CASE__			,							scheduler=SCREAMING_SNAKE_CASE__			,							renderer=SCREAMING_SNAKE_CASE__			,							)




							def 		lowerCamelCase_				(							self:				Tuple			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				Optional[Any]			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				Dict     ):






														if latents is None:
																					lowerCamelCase__					:	Union[str, Any]         =       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__					:	str         =       latents.to(SCREAMING_SNAKE_CASE__     )

														lowerCamelCase__					:	Tuple         =       latents * scheduler.init_noise_sigma
														return latents




							def 		lowerCamelCase_				(							self:				Any			,							UpperCamelCase__:				Tuple=0     ):






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

														lowerCamelCase__					:	Union[str, Any]         =       torch.device(F'''cuda:{gpu_id}'''     )

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




							@property
							def 		lowerCamelCase_				(							self:				Any     ):






														if self.device != torch.device("""meta"""     ) or not hasattr(self.image_encoder			,							"""_hf_hook"""     ):
																					return self.device
														for module in self.image_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:				Tuple			,							UpperCamelCase__:				List[str]			,							UpperCamelCase__:				str			,							UpperCamelCase__:				Tuple			,							UpperCamelCase__:				Tuple			,							):






														if isinstance(SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__     ) and isinstance(image[0]			,							torch.Tensor     ):
																					lowerCamelCase__					:	Tuple         =       torch.cat(SCREAMING_SNAKE_CASE__			,							axis=0     ) if image[0].ndim == 4 else torch.stack(SCREAMING_SNAKE_CASE__			,							axis=0     )

														if not isinstance(SCREAMING_SNAKE_CASE__			,							torch.Tensor     ):
																					lowerCamelCase__					:	Tuple         =       self.image_processor(SCREAMING_SNAKE_CASE__			,							return_tensors="""pt"""     ).pixel_values[0].unsqueeze(0     )

														lowerCamelCase__					:	Optional[int]         =       image.to(dtype=self.image_encoder.dtype			,							device=SCREAMING_SNAKE_CASE__     )

														lowerCamelCase__					:	Dict         =       self.image_encoder(SCREAMING_SNAKE_CASE__     )['''last_hidden_state''']
														lowerCamelCase__					:	Tuple         =       image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

														lowerCamelCase__					:	Tuple         =       image_embeds.repeat_interleave(SCREAMING_SNAKE_CASE__			,							dim=0     )

														if do_classifier_free_guidance:
																					lowerCamelCase__					:	List[str]         =       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__					:	List[str]         =       torch.cat([negative_image_embeds, image_embeds]     )

														return image_embeds




							@torch.no_grad()
							@replace_example_docstring(SCREAMING_SNAKE_CASE__     )
							def __call__(							self:				Tuple			,							UpperCamelCase__:				Dict			,							UpperCamelCase__:				Any = 1			,							UpperCamelCase__:				Dict = 25			,							UpperCamelCase__:				List[str] = None			,							UpperCamelCase__:				Optional[Any] = None			,							UpperCamelCase__:				Union[str, Any] = 4.0			,							UpperCamelCase__:				Optional[int] = 64			,							UpperCamelCase__:				Tuple = "pil"			,							UpperCamelCase__:				int = True			,							):






														if isinstance(SCREAMING_SNAKE_CASE__			,							PIL.Image.Image     ):
																					lowerCamelCase__					:	Optional[int]         =       1
														elif isinstance(SCREAMING_SNAKE_CASE__			,							torch.Tensor     ):
																					lowerCamelCase__					:	Any         =       image.shape[0]
														elif isinstance(SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__     ) and isinstance(image[0]			,							(torch.Tensor, PIL.Image.Image)     ):
																					lowerCamelCase__					:	Union[str, Any]         =       len(SCREAMING_SNAKE_CASE__     )
														else:
																					raise ValueError(
																					    F'''`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(SCREAMING_SNAKE_CASE__     )}'''     )

														lowerCamelCase__					:	Any         =       self._execution_device

														lowerCamelCase__					:	str         =       batch_size * num_images_per_prompt

														lowerCamelCase__					:	Optional[Any]         =       guidance_scale > 1.0
														lowerCamelCase__					:	List[Any]         =       self._encode_image(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__					:	List[str]         =       self.scheduler.timesteps

														lowerCamelCase__					:	List[Any]         =       self.prior.config.num_embeddings
														lowerCamelCase__					:	Dict         =       self.prior.config.embedding_dim

														lowerCamelCase__					:	List[str]         =       self.prepare_latents(
														    (batch_size, num_embeddings * embedding_dim)			,							image_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__					:	Any         =       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__					:	Union[str, Any]         =       torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
																					lowerCamelCase__					:	Optional[Any]         =       self.scheduler.scale_model_input(SCREAMING_SNAKE_CASE__			,							SCREAMING_SNAKE_CASE__     )

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

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

																					lowerCamelCase__					:	List[Any]         =       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__					:	str         =       []
														for i, latent in enumerate(SCREAMING_SNAKE_CASE__     ):
																					print()
																					lowerCamelCase__					:	Dict         =       self.renderer.decode(
																					    latent[None, :]			,							SCREAMING_SNAKE_CASE__			,							size=SCREAMING_SNAKE_CASE__			,							ray_batch_size=4_096			,							n_coarse_samples=64			,							n_fine_samples=128			,							)

																					images.append(SCREAMING_SNAKE_CASE__     )

														lowerCamelCase__					:	List[Any]         =       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__					:	Tuple         =       images.cpu().numpy()

														if output_type == "pil":
																					lowerCamelCase__					:	Union[str, Any]         =       [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"""
from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_								=		logging.get_logger(__name__)

lowerCamelCase_								=		{
    "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json",
    "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json",
    "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json",
    "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json",
    "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json",
    "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json",
    "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json",
    "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json",
    "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json",
}






class 					_SCREAMING_SNAKE_CASE(   A  ):
       SCREAMING_SNAKE_CASE_   :      Any							=  '''xmod'''




       def __init__(						self		,SCREAMING_SNAKE_CASE__=3_05_22		,SCREAMING_SNAKE_CASE__=7_68		,SCREAMING_SNAKE_CASE__=12		,SCREAMING_SNAKE_CASE__=12		,SCREAMING_SNAKE_CASE__=30_72		,SCREAMING_SNAKE_CASE__="gelu"		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=0.1		,SCREAMING_SNAKE_CASE__=5_12		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=0.0_2		,SCREAMING_SNAKE_CASE__=1E-12		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__="absolute"		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=False		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=("en_XX",)		,SCREAMING_SNAKE_CASE__=None		,**SCREAMING_SNAKE_CASE__		,)			->      Optional[Any]:





             """simple docstring"""






             super().__init__(pad_token_id=SCREAMING_SNAKE_CASE__		,bos_token_id=SCREAMING_SNAKE_CASE__		,eos_token_id=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE   :Optional[int]						=  vocab_size
             __SCREAMING_SNAKE_CASE   :List[Any]						=  hidden_size
             __SCREAMING_SNAKE_CASE   :List[str]						=  num_hidden_layers
             __SCREAMING_SNAKE_CASE   :List[str]						=  num_attention_heads
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  hidden_act
             __SCREAMING_SNAKE_CASE   :Tuple						=  intermediate_size
             __SCREAMING_SNAKE_CASE   :Dict						=  hidden_dropout_prob
             __SCREAMING_SNAKE_CASE   :str						=  attention_probs_dropout_prob
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  max_position_embeddings
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  type_vocab_size
             __SCREAMING_SNAKE_CASE   :str						=  initializer_range
             __SCREAMING_SNAKE_CASE   :List[Any]						=  layer_norm_eps
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  position_embedding_type
             __SCREAMING_SNAKE_CASE   :Any						=  use_cache
             __SCREAMING_SNAKE_CASE   :List[str]						=  classifier_dropout
             __SCREAMING_SNAKE_CASE   :Any						=  pre_norm
             __SCREAMING_SNAKE_CASE   :Dict						=  adapter_reduction_factor
             __SCREAMING_SNAKE_CASE   :Dict						=  adapter_layer_norm
             __SCREAMING_SNAKE_CASE   :Dict						=  adapter_reuse_layer_norm
             __SCREAMING_SNAKE_CASE   :Tuple						=  ln_before_adapter
             __SCREAMING_SNAKE_CASE   :Any						=  list(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  default_language






class 					_SCREAMING_SNAKE_CASE(   A  ):




       @property
       def     _UpperCamelCase     (						self							)			->      Mapping[str, Mapping[int, str]]:





             """simple docstring"""






             if self.task == "multiple-choice":
                   __SCREAMING_SNAKE_CASE   :Tuple						=  {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
             else:
                   __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  {0: '''batch''', 1: '''sequence'''}
             return OrderedDict(
                 [
                     ('''input_ids''', dynamic_axis),
                     ('''attention_mask''', dynamic_axis),
                 ]							)