



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


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

snake_case_				:			Union[str, Any]						 =						'\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 							snake_case__			(							lowercase     ):
	lowercase__						       =    42






class 							snake_case__			(							lowercase     ):





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







							'''simple docstring'''
							super().__init__()

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





	def 			UpperCamelCase_						(				self      :       Union[str, Any]				,lowerCamelCase__      :       Union[str, Any]				,lowerCamelCase__      :       Any				,lowerCamelCase__      :       Any				,lowerCamelCase__      :       int				,lowerCamelCase__      :       Optional[Any]				,lowerCamelCase__      :       Optional[int]				):







							'''simple docstring'''
							if latents is None:
													_UpperCamelCase      :	Optional[int]				       =     randn_tensor(lowerCamelCase__				,generator=lowerCamelCase__				,device=lowerCamelCase__				,dtype=lowerCamelCase__				)
							else:
													if latents.shape != shape:
																			raise ValueError(F'Unexpected latents shape, got {latents.shape}, expected {shape}'				)
													_UpperCamelCase      :	Tuple				       =     latents.to(lowerCamelCase__				)

							_UpperCamelCase      :	str				       =     latents * scheduler.init_noise_sigma
							return latents





	def 			UpperCamelCase_						(				self      :       Optional[int]				,lowerCamelCase__      :       str=0				):







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

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

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





	def 			UpperCamelCase_						(				self      :       List[str]				,lowerCamelCase__      :       Union[str, Any]=0				):







							'''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.'				)

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

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

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

							if self.safety_checker is not None:
													_UpperCamelCase      :	Optional[int]				       =     cpu_offload_with_hook(self.safety_checker				,lowerCamelCase__				,prev_module_hook=lowerCamelCase__				)

							# We'll offload the last model manually.
							_UpperCamelCase      :	str				       =     hook





	@property
	def 			UpperCamelCase_						(				self      :       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(lowerCamelCase__				,'_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 			UpperCamelCase_						(				self      :       Optional[Any]				,lowerCamelCase__      :       List[Any]				,lowerCamelCase__      :       List[Any]				,lowerCamelCase__      :       List[Any]				,lowerCamelCase__      :       Any				,):







							'''simple docstring'''
							len(lowerCamelCase__				) if isinstance(lowerCamelCase__				,lowerCamelCase__				) else 1

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

							if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCamelCase__				,lowerCamelCase__				):
													_UpperCamelCase      :	List[str]				       =     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}'				)

							_UpperCamelCase      :	List[str]				       =     self.text_encoder(text_input_ids.to(lowerCamelCase__				)				)
							_UpperCamelCase      :	Dict				       =     text_encoder_output.text_embeds

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

							if do_classifier_free_guidance:
													_UpperCamelCase      :	Union[str, Any]				       =     torch.zeros_like(lowerCamelCase__				)

													# 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
													_UpperCamelCase      :	str				       =     torch.cat([negative_prompt_embeds, prompt_embeds]				)

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

							return prompt_embeds





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







							'''simple docstring'''

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

							_UpperCamelCase      :	Any				       =     self._execution_device

							_UpperCamelCase      :	int				       =     batch_size * num_images_per_prompt

							_UpperCamelCase      :	Tuple				       =     guidance_scale > 1.0
							_UpperCamelCase      :	List[str]				       =     self._encode_prompt(lowerCamelCase__				,lowerCamelCase__				,lowerCamelCase__				,lowerCamelCase__				)

							# prior

							self.scheduler.set_timesteps(lowerCamelCase__				,device=lowerCamelCase__				)
							_UpperCamelCase      :	List[str]				       =     self.scheduler.timesteps

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

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

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

													_UpperCamelCase      :	str				       =     self.prior(
													    lowerCamelCase__				,timestep=lowerCamelCase__				,proj_embedding=lowerCamelCase__				,).predicted_image_embedding

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

													if do_classifier_free_guidance is not None:
																			_UpperCamelCase      :	Tuple				       =     noise_pred.chunk(2				)
																			_UpperCamelCase      :	str				       =     noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

													_UpperCamelCase      :	Optional[Any]				       =     self.scheduler.step(
													    lowerCamelCase__				,timestep=lowerCamelCase__				,sample=lowerCamelCase__				,).prev_sample

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

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

							_UpperCamelCase      :	List[Any]				       =     torch.stack(lowerCamelCase__				)

							if output_type not in ["np", "pil"]:
													raise ValueError(F'Only the output types `pil` and `np` are supported not output_type={output_type}'				)

							_UpperCamelCase      :	Optional[int]				       =     images.cpu().numpy()

							if output_type == "pil":
													_UpperCamelCase      :	List[Any]				       =     [self.numpy_to_pil(lowerCamelCase__				) 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=lowerCamelCase__				)







'''simple docstring'''
import os

from ...utils import logging
from .utils import DataProcessor, InputExample


snake_case_				:			Any						 =						logging.get_logger(__name__)






class 							lowercase__			(							lowercase     ):





	def __init__(				self      :       Union[str, Any]				,lowerCamelCase__      :       Tuple				,lowerCamelCase__      :       Optional[int]=None				):







							'''simple docstring'''
							_UpperCamelCase      :	Any				       =     language
							_UpperCamelCase      :	int				       =     train_language





	def 			UpperCamelCase_						(				self      :       Optional[int]				,lowerCamelCase__      :       Dict				):







							'''simple docstring'''
							_UpperCamelCase      :	Tuple				       =     self.language if self.train_language is None else self.train_language
							_UpperCamelCase      :	List[Any]				       =     self._read_tsv(os.path.join(lowerCamelCase__				,F'XNLI-MT-1.0/multinli/multinli.train.{lg}.tsv'				)				)
							_UpperCamelCase      :	Union[str, Any]				       =     []
							for i, line in enumerate(lowerCamelCase__				):
													if i == 0:
																			continue
													_UpperCamelCase      :	Optional[Any]				       =     F'train-{i}'
													_UpperCamelCase      :	List[str]				       =     line[0]
													_UpperCamelCase      :	Union[str, Any]				       =     line[1]
													_UpperCamelCase      :	Tuple				       =     'contradiction' if line[2] == 'contradictory' else line[2]
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training input {text_a} is not a string'				)
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training input {text_b} is not a string'				)
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training label {label} is not a string'				)
													examples.append(InputExample(guid=lowerCamelCase__				,text_a=lowerCamelCase__				,text_b=lowerCamelCase__				,label=lowerCamelCase__				)				)
							return examples





	def 			UpperCamelCase_						(				self      :       Optional[Any]				,lowerCamelCase__      :       List[str]				):







							'''simple docstring'''
							_UpperCamelCase      :	Optional[int]				       =     self._read_tsv(os.path.join(lowerCamelCase__				,'XNLI-1.0/xnli.test.tsv'				)				)
							_UpperCamelCase      :	List[str]				       =     []
							for i, line in enumerate(lowerCamelCase__				):
													if i == 0:
																			continue
													_UpperCamelCase      :	Optional[int]				       =     line[0]
													if language != self.language:
																			continue
													_UpperCamelCase      :	Optional[int]				       =     F'test-{i}'
													_UpperCamelCase      :	Optional[int]				       =     line[6]
													_UpperCamelCase      :	List[str]				       =     line[7]
													_UpperCamelCase      :	str				       =     line[1]
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training input {text_a} is not a string'				)
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training input {text_b} is not a string'				)
													if not isinstance(lowerCamelCase__				,lowerCamelCase__				):
																			raise ValueError(F'Training label {label} is not a string'				)
													examples.append(InputExample(guid=lowerCamelCase__				,text_a=lowerCamelCase__				,text_b=lowerCamelCase__				,label=lowerCamelCase__				)				)
							return examples





	def 			UpperCamelCase_						(				self      :       str				):







							'''simple docstring'''
							return ["contradiction", "entailment", "neutral"]
snake_case_				:			int						 =						{
    'xnli': XnliProcessor,
}

snake_case_				:			Tuple						 =						{
    'xnli': 'classification',
}

snake_case_				:			Any						 =						{
    'xnli': 3,
}


