



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

snake_case_         = """\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    A_    (  A_       ):



						"""simple docstring"""
						__UpperCamelCase	       =							42







class    A_    (  A_       ):



						"""simple docstring"""






						def __init__(      self				:str     ,						lowercase_				:PriorTransformer     ,						lowercase_				:CLIPTextModelWithProjection     ,						lowercase_				:CLIPTokenizer     ,						lowercase_				:HeunDiscreteScheduler     ,						lowercase_				:ShapERenderer     ,						)       ->    Optional[Any]:
												super().__init__()

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






						def 			UpperCAmelCase__  (      self				:Union[str, Any]     ,						lowercase_				:Optional[Any]     ,						lowercase_				:str     ,						lowercase_				:Optional[Any]     ,						lowercase_				:Union[str, Any]     ,						lowercase_				:Any     ,						lowercase_				:Dict      )       ->    str:



												if latents is None:
																		UpperCAmelCase    =				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}"""      )
																		UpperCAmelCase    =				latents.to(lowercase_      )

												UpperCAmelCase    =				latents * scheduler.init_noise_sigma
												return latents






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:List[str]=0      )       ->    Optional[int]:



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

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

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






						def 			UpperCAmelCase__  (      self				:Optional[Any]     ,						lowercase_				:Tuple=0      )       ->    Union[str, Any]:



												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    =				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)

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

												if self.safety_checker is not None:
																		UpperCAmelCase    =				cpu_offload_with_hook(self.safety_checker     ,						lowercase_     ,						prev_module_hook=lowercase_      )

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






						@property
						def 			UpperCAmelCase__  (      self				:Dict      )       ->    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 			UpperCAmelCase__  (      self				:Union[str, Any]     ,						lowercase_				:Dict     ,						lowercase_				:Union[str, Any]     ,						lowercase_				:Dict     ,						lowercase_				:Tuple     ,						)       ->    List[str]:
												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
												UpperCAmelCase    =				0
												# get prompt text embeddings
												UpperCAmelCase    =				self.tokenizer(
												    lowercase_     ,						padding='max_length'     ,						max_length=self.tokenizer.model_max_length     ,						truncation=lowercase_     ,						return_tensors='pt'     ,						)
												UpperCAmelCase    =				text_inputs.input_ids
												UpperCAmelCase    =				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_      ):
																		UpperCAmelCase    =				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    =				self.text_encoder(text_input_ids.to(lowercase_      )      )
												UpperCAmelCase    =				text_encoder_output.text_embeds

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

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

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

												return prompt_embeds






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



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

												UpperCAmelCase    =				self._execution_device

												UpperCAmelCase    =				batch_size * num_images_per_prompt

												UpperCAmelCase    =				guidance_scale > 1.0
												UpperCAmelCase    =				self._encode_prompt(lowercase_     ,						lowercase_     ,						lowercase_     ,						lowercase_      )

												# prior

												self.scheduler.set_timesteps(lowercase_     ,						device=lowercase_      )
												UpperCAmelCase    =				self.scheduler.timesteps

												UpperCAmelCase    =				self.prior.config.num_embeddings
												UpperCAmelCase    =				self.prior.config.embedding_dim

												UpperCAmelCase    =				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
												UpperCAmelCase    =				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
																		UpperCAmelCase    =				torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents
																		UpperCAmelCase    =				self.scheduler.scale_model_input(lowercase_     ,						lowercase_      )

																		UpperCAmelCase    =				self.prior(
																		    lowercase_     ,						timestep=lowercase_     ,						proj_embedding=lowercase_     ,						).predicted_image_embedding

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

																		UpperCAmelCase    =				self.scheduler.step(
																		    lowercase_     ,						timestep=lowercase_     ,						sample=lowercase_     ,						).prev_sample

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

												UpperCAmelCase    =				[]
												for i, latent in enumerate(lowercase_      ):
																		UpperCAmelCase    =				self.renderer.decode(
																		    latent[None, :]     ,						lowercase_     ,						size=lowercase_     ,						ray_batch_size=40_96     ,						n_coarse_samples=64     ,						n_fine_samples=1_28     ,						)
																		images.append(lowercase_      )

												UpperCAmelCase    =				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}"""      )

												UpperCAmelCase    =				images.cpu().numpy()

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


from math import exp

def 				_lowerCAmelCase   (     lowercase_		):
						return 8 * x - 2 * exp(-x		)

def 				_lowerCAmelCase   (     lowercase_	,			lowercase_	,			lowercase_		):
						UpperCAmelCase    =				lower_bound
						UpperCAmelCase    =				upper_bound
						for _ in range(0	,			lowercase_		):
												UpperCAmelCase   ,					UpperCAmelCase    =				xa, xa - (f(lowercase_		) * (xa - xa)) / (f(lowercase_		) - f(lowercase_		))
						return xa


if __name__ == "__main__":
				print(f'''Example: {secant_method(1, 3, 2)}''')





