


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

A	:		List[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 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			42






class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self   :						Tuple				, _UpperCAmelCase   :						PriorTransformer				, _UpperCAmelCase   :						CLIPVisionModel				, _UpperCAmelCase   :						CLIPImageProcessor				, _UpperCAmelCase   :						HeunDiscreteScheduler				, _UpperCAmelCase   :						ShapERenderer				, )						->       Optional[Any]:




							"""simple docstring"""


							super().__init__()

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

					def   lowerCamelCase__					(self   :						Optional[int]				, _UpperCAmelCase   :						Dict				, _UpperCAmelCase   :						Optional[Any]				, _UpperCAmelCase   :						Tuple				, _UpperCAmelCase   :						str				, _UpperCAmelCase   :						Union[str, Any]				, _UpperCAmelCase   :						Union[str, Any]		)						->       str:




							"""simple docstring"""


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

							lowercase__					      =		latents * scheduler.init_noise_sigma
							return latents

					def   lowerCamelCase__					(self   :						Optional[int]				, _UpperCAmelCase   :						str=0		)						->       Dict:




							"""simple docstring"""


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

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

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

					@property
					def   lowerCamelCase__					(self   :						Dict		)						->       Tuple:




							"""simple docstring"""


							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(__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   lowerCamelCase__					(self   :						List[Any]				, _UpperCAmelCase   :						str				, _UpperCAmelCase   :						str				, _UpperCAmelCase   :						List[Any]				, _UpperCAmelCase   :						List[str]				, )						->       int:




							"""simple docstring"""


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

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

							lowercase__					      =		image.to(dtype=self.image_encoder.dtype				, device=__A		)

							lowercase__					      =		self.image_encoder(__A		)["""last_hidden_state"""]
							lowercase__					      =		image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

							lowercase__					      =		image_embeds.repeat_interleave(__A				, dim=0		)

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

							return image_embeds


					@torch.no_grad()
					@replace_example_docstring(__A		)
					def __call__(self   :						List[str]				, _UpperCAmelCase   :						Union[PIL.Image.Image, List[PIL.Image.Image]]				, _UpperCAmelCase   :						int = 1				, _UpperCAmelCase   :						int = 25				, _UpperCAmelCase   :						Optional[Union[torch.Generator, List[torch.Generator]]] = None				, _UpperCAmelCase   :						Optional[torch.FloatTensor] = None				, _UpperCAmelCase   :						float = 4.0				, _UpperCAmelCase   :						int = 64				, _UpperCAmelCase   :						Optional[str] = "pil"				, _UpperCAmelCase   :						bool = True				, )						->       int:




							"""simple docstring"""


							if isinstance(__A				, PIL.Image.Image		):
									lowercase__					      =		1
							elif isinstance(__A				, torch.Tensor		):
									lowercase__					      =		image.shape[0]
							elif isinstance(__A				, __A		) and isinstance(image[0]				, (torch.Tensor, PIL.Image.Image)		):
									lowercase__					      =		len(__A		)
							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(__A		)}'''		)

							lowercase__					      =		self._execution_device

							lowercase__					      =		batch_size * num_images_per_prompt

							lowercase__					      =		guidance_scale > 1.0
							lowercase__					      =		self._encode_image(__A				, __A				, __A				, __A		)

							# prior

							self.scheduler.set_timesteps(__A				, device=__A		)
							lowercase__					      =		self.scheduler.timesteps

							lowercase__					      =		self.prior.config.num_embeddings
							lowercase__					      =		self.prior.config.embedding_dim

							lowercase__					      =		self.prepare_latents(
							    (batch_size, num_embeddings * embedding_dim)				, image_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
							lowercase__					      =		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
									lowercase__					      =		torch.cat([latents] * 2		) if do_classifier_free_guidance else latents
									lowercase__					      =		self.scheduler.scale_model_input(__A				, __A		)

									lowercase__					      =		self.prior(
									    __A				, timestep=__A				, proj_embedding=__A				, ).predicted_image_embedding

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

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

									lowercase__					      =		self.scheduler.step(
									    __A				, timestep=__A				, sample=__A				, ).prev_sample

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

							lowercase__					      =		[]
							for i, latent in enumerate(__A		):
									print()
									lowercase__					      =		self.renderer.decode(
									    latent[None, :]				, __A				, size=__A				, ray_batch_size=4096				, n_coarse_samples=64				, n_fine_samples=128				, )

									images.append(__A		)

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

							lowercase__					      =		images.cpu().numpy()

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






from collections import OrderedDict
from typing import Mapping

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


A	:		Optional[Any]    =       logging.get_logger(__name__)

A	:		Tuple    =       {
    'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json',
    'YituTech/conv-bert-medium-small': (
        'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json'
    ),
    'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json',
    # See all ConvBERT models at https://huggingface.co/models?filter=convbert
}



class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			'''convbert'''

					def __init__(self   :						str				, _UpperCAmelCase   :						Union[str, Any]=3_0522				, _UpperCAmelCase   :						Dict=768				, _UpperCAmelCase   :						Optional[int]=12				, _UpperCAmelCase   :						List[str]=12				, _UpperCAmelCase   :						str=3072				, _UpperCAmelCase   :						Tuple="gelu"				, _UpperCAmelCase   :						Optional[int]=0.1				, _UpperCAmelCase   :						int=0.1				, _UpperCAmelCase   :						str=512				, _UpperCAmelCase   :						Dict=2				, _UpperCAmelCase   :						int=0.02				, _UpperCAmelCase   :						Tuple=1E-1_2				, _UpperCAmelCase   :						Dict=1				, _UpperCAmelCase   :						Optional[Any]=0				, _UpperCAmelCase   :						List[str]=2				, _UpperCAmelCase   :						str=768				, _UpperCAmelCase   :						List[Any]=2				, _UpperCAmelCase   :						Optional[Any]=9				, _UpperCAmelCase   :						List[Any]=1				, _UpperCAmelCase   :						Union[str, Any]=None				, **_UpperCAmelCase   :						List[Any]				, )						->       List[str]:




							"""simple docstring"""


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

							lowercase__					      =		vocab_size
							lowercase__					      =		hidden_size
							lowercase__					      =		num_hidden_layers
							lowercase__					      =		num_attention_heads
							lowercase__					      =		intermediate_size
							lowercase__					      =		hidden_act
							lowercase__					      =		hidden_dropout_prob
							lowercase__					      =		attention_probs_dropout_prob
							lowercase__					      =		max_position_embeddings
							lowercase__					      =		type_vocab_size
							lowercase__					      =		initializer_range
							lowercase__					      =		layer_norm_eps
							lowercase__					      =		embedding_size
							lowercase__					      =		head_ratio
							lowercase__					      =		conv_kernel_size
							lowercase__					      =		num_groups
							lowercase__					      =		classifier_dropout






class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






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




							"""simple docstring"""


							if self.task == "multiple-choice":
									lowercase__					      =		{0: """batch""", 1: """choice""", 2: """sequence"""}
							else:
									lowercase__					      =		{0: """batch""", 1: """sequence"""}
							return OrderedDict(
							    [
							        ("""input_ids""", dynamic_axis),
							        ("""attention_mask""", dynamic_axis),
							        ("""token_type_ids""", dynamic_axis),
							    ]		)

