






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


__lowerCamelCase :      Any										=				logging.get_logger(__name__)  # pylint: disable=invalid-name

__lowerCamelCase :      int										=				"""
    Examples:
        ```py
        >>> from PIL import Image
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif, load_image

        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")

        >>> repo = \"openai/shap-e-img2img\"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 3.0
        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"
        >>> image = load_image(image_url).convert(\"RGB\")

        >>> images = pipe(
        ...     image,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")
        ```
"""



@dataclass
class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					a_     =		42



class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					def __init__( self					:  Dict							,		__A					:  PriorTransformer							,		__A					:  CLIPVisionModel							,		__A					:  CLIPImageProcessor							,		__A					:  HeunDiscreteScheduler							,		__A					:  ShapERenderer							,		):
						super().__init__()

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



					def 	_lowercase					( self					:  str							,		__A					:  Any							,		__A					:  List[str]							,		__A					:  Union[str, Any]							,		__A					:  Optional[int]							,		__A					:  int							,		__A					:  Optional[Any]	):
						if latents is None:
							snake_case__			:				List[Any]       =  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}'''	)
							snake_case__			:				Union[str, Any]       =  latents.to(__A	)

						snake_case__			:				Union[str, Any]       =  latents * scheduler.init_noise_sigma
						return latents



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

						snake_case__			:				Optional[Any]       =  torch.device(f'''cuda:{gpu_id}'''	)

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



					@property
					def 	_lowercase					( self					:  List[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(__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 	_lowercase					( self					:  List[Any]							,		__A					:  Any							,		__A					:  Dict							,		__A					:  List[Any]							,		__A					:  Dict							,		):
						if isinstance(__A							,		__A	) and isinstance(image[0]							,		torch.Tensor	):
							snake_case__			:				List[Any]       =  torch.cat(__A							,		axis=0	) if image[0].ndim == 4 else torch.stack(__A							,		axis=0	)

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

						snake_case__			:				Tuple       =  image.to(dtype=self.image_encoder.dtype							,		device=__A	)

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

						snake_case__			:				Dict       =  image_embeds.repeat_interleave(__A							,		dim=0	)

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

						return image_embeds






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

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

						snake_case__			:				List[Any]       =  self._execution_device

						snake_case__			:				int       =  batch_size * num_images_per_prompt

						snake_case__			:				Optional[int]       =  guidance_scale > 1.0
						snake_case__			:				List[str]       =  self._encode_image(__A							,		__A							,		__A							,		__A	)

						# prior

						self.scheduler.set_timesteps(__A							,		device=__A	)
						snake_case__			:				Any       =  self.scheduler.timesteps

						snake_case__			:				Optional[int]       =  self.prior.config.num_embeddings
						snake_case__			:				Tuple       =  self.prior.config.embedding_dim

						snake_case__			:				int       =  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
						snake_case__			:				Optional[Any]       =  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
							snake_case__			:				List[str]       =  torch.cat([latents] * 2	) if do_classifier_free_guidance else latents
							snake_case__			:				Tuple       =  self.scheduler.scale_model_input(__A							,		__A	)

							snake_case__			:				Optional[int]       =  self.prior(
							    __A							,		timestep=__A							,		proj_embedding=__A							,		).predicted_image_embedding

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

							if do_classifier_free_guidance is not None:
								snake_case__,						snake_case__			:				List[str]       =  noise_pred.chunk(2	)
								snake_case__			:				List[Any]       =  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							snake_case__			:				str       =  self.scheduler.step(
							    __A							,		timestep=__A							,		sample=__A							,		).prev_sample

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

						snake_case__			:				str       =  []
						for i, latent in enumerate(__A	):
							print()
							snake_case__			:				List[str]       =  self.renderer.decode(
							    latent[None, :]							,		__A							,		size=__A							,		ray_batch_size=4_0_9_6							,		n_coarse_samples=6_4							,		n_fine_samples=1_2_8							,		)

							images.append(__A	)

						snake_case__			:				Union[str, Any]       =  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}'''	)

						snake_case__			:				Dict       =  images.cpu().numpy()

						if output_type == "pil":
							snake_case__			:				List[str]       =  [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	)











import random
import timeit
from functools import wraps
from typing import Callable, Optional

from ..configuration_utils import PretrainedConfig
from ..models.auto.modeling_tf_auto import TF_MODEL_MAPPING, TF_MODEL_WITH_LM_HEAD_MAPPING
from ..utils import is_pyanvml_available, is_tf_available, logging
from .benchmark_utils import (
    Benchmark,
    Memory,
    MemorySummary,
    measure_peak_memory_cpu,
    start_memory_tracing,
    stop_memory_tracing,
)


if is_tf_available():
	import tensorflow as tf
	from tensorflow.python.framework.errors_impl import ResourceExhaustedError

	from .benchmark_args_tf import TensorFlowBenchmarkArguments

if is_pyanvml_available():
	import pyanvml.pyanvml as nvml

__lowerCamelCase :      List[Any]										=				logging.get_logger(__name__)







def 					SCREAMING_SNAKE_CASE    (			snake_case_ :							bool					,  snake_case_ :							bool       ):
	def run_func(snake_case_ :							str       ):
		@wraps(snake_case_       )
		def run_in_eager_mode(*snake_case_ :							str					,  **snake_case_ :							Union[str, Any]       ):
			return func(*snake_case_					,  **snake_case_       )

		@wraps(snake_case_       )
		@tf.function(experimental_compile=snake_case_       )
		def run_in_graph_mode(*snake_case_ :							List[Any]					,  **snake_case_ :							List[Any]       ):
			return func(*snake_case_					,  **snake_case_       )

		if do_eager_mode is True:
			if use_xla is not False:
				raise ValueError(
				    "Cannot run model in XLA, if `args.eager_mode` is set to `True`. Please set `args.eager_mode=False`."       )
			return run_in_eager_mode
		else:
			return run_in_graph_mode

	return run_func







def 					SCREAMING_SNAKE_CASE    (			snake_case_ :							int					,  snake_case_ :							int					,  snake_case_ :							int       ):
	snake_case__			:				Dict       =  random.Random()
	snake_case__			:				List[Any]       =  [rng.randint(0					,  vocab_size - 1       ) for i in range(batch_size * sequence_length       )]
	return tf.constant(snake_case_					,  shape=(batch_size, sequence_length)					,  dtype=tf.intaa       )





class 							SCREAMING_SNAKE_CASE__						(    UpperCamelCase_						):





					"""simple docstring"""






					a_     =		42
					a_     =		42
					a_     =		"TensorFlow"



					@property
					def 	_lowercase					( self					:  List[str]	):
						return tf.__version__



					def 	_lowercase					( self					:  List[str]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						# initialize GPU on separate process
						snake_case__			:				str       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Dict       =  self._prepare_inference_func(__A							,		__A							,		__A	)
						return self._measure_speed(_inference	)



					def 	_lowercase					( self					:  Tuple							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				Optional[int]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Any       =  self._prepare_train_func(__A							,		__A							,		__A	)
						return self._measure_speed(_train	)



					def 	_lowercase					( self					:  List[Any]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						# initialize GPU on separate process
						if self.args.is_gpu:
							tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,		__A	)
						snake_case__			:				List[str]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)
						snake_case__			:				Optional[Any]       =  self._prepare_inference_func(__A							,		__A							,		__A	)
						return self._measure_memory(_inference	)



					def 	_lowercase					( self					:  str							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						if self.args.is_gpu:
							tf.config.experimental.set_memory_growth(self.args.gpu_list[self.args.device_idx]							,		__A	)
						snake_case__			:				List[Any]       =  self.args.strategy
						if strategy is None:
							raise ValueError("A device strategy has to be initialized before using TensorFlow."	)

						snake_case__			:				int       =  self._prepare_train_func(__A							,		__A							,		__A	)
						return self._measure_memory(_train	)



					def 	_lowercase					( self					:  Union[str, Any]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				int       =  self.config_dict[model_name]

						if self.args.fpaa:
							raise NotImplementedError("Mixed precision is currently not supported."	)

						snake_case__			:				Tuple       =  (
						    hasattr(__A							,		"architectures"	)
						    and isinstance(config.architectures							,		__A	)
						    and len(config.architectures	) > 0
						)
						if not self.args.only_pretrain_model and has_model_class_in_config:
							try:
								snake_case__			:				Dict       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
								snake_case__			:				Union[str, Any]       =  __import__("transformers"							,		fromlist=[model_class]	)
								snake_case__			:				Any       =  getattr(__A							,		__A	)
								snake_case__			:				Dict       =  model_cls(__A	)
							except ImportError:
								raise ImportError(
								    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
								    " set `--only_pretrain_model` or `args.only_pretrain_model=True`."	)
						else:
							snake_case__			:				Dict       =  TF_MODEL_MAPPING[config.__class__](__A	)

						# encoder-decoder has vocab size saved differently
						snake_case__			:				Optional[int]       =  config.vocab_size if hasattr(__A							,		"vocab_size"	) else config.encoder.vocab_size
						snake_case__			:				List[Any]       =  random_input_ids(__A							,		__A							,		__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_decoder_forward():
							return model(__A							,		decoder_input_ids=__A							,		training=__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_forward():
							return model(__A							,		training=__A	)

						snake_case__			:				Optional[int]       =  encoder_decoder_forward if config.is_encoder_decoder else encoder_forward

						return _inference



					def 	_lowercase					( self					:  List[str]							,		__A					:  str							,		__A					:  int							,		__A					:  int	):
						snake_case__			:				Optional[Any]       =  self.config_dict[model_name]

						if self.args.eager_mode is not False:
							raise ValueError("Training cannot be done in eager mode. Please make sure that `args.eager_mode = False`."	)

						if self.args.fpaa:
							raise NotImplementedError("Mixed precision is currently not supported."	)

						snake_case__			:				Any       =  (
						    hasattr(__A							,		"architectures"	)
						    and isinstance(config.architectures							,		__A	)
						    and len(config.architectures	) > 0
						)
						if not self.args.only_pretrain_model and has_model_class_in_config:
							try:
								snake_case__			:				Dict       =  "TF" + config.architectures[0]  # prepend 'TF' for tensorflow model
								snake_case__			:				List[Any]       =  __import__("transformers"							,		fromlist=[model_class]	)
								snake_case__			:				Optional[int]       =  getattr(__A							,		__A	)
								snake_case__			:				str       =  model_cls(__A	)
							except ImportError:
								raise ImportError(
								    f'''{model_class} does not exist. If you just want to test the pretrained model, you might want to'''
								    " set `--only_pretrain_model` or `args.only_pretrain_model=True`."	)
						else:
							snake_case__			:				Union[str, Any]       =  TF_MODEL_WITH_LM_HEAD_MAPPING[config.__class__](__A	)

						# encoder-decoder has vocab size saved differently
						snake_case__			:				Union[str, Any]       =  config.vocab_size if hasattr(__A							,		"vocab_size"	) else config.encoder.vocab_size
						snake_case__			:				List[str]       =  random_input_ids(__A							,		__A							,		__A	)

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_decoder_train():
							snake_case__			:				str       =  model(__A							,		decoder_input_ids=__A							,		labels=__A							,		training=__A	)[0]
							snake_case__			:				Dict       =  tf.gradients(__A							,		model.trainable_variables	)
							return gradients

						@run_with_tf_optimizations(self.args.eager_mode							,		self.args.use_xla	)
						def encoder_train():
							snake_case__			:				Optional[Any]       =  model(__A							,		labels=__A							,		training=__A	)[0]
							snake_case__			:				Dict       =  tf.gradients(__A							,		model.trainable_variables	)
							return gradients

						snake_case__			:				int       =  encoder_decoder_train if config.is_encoder_decoder else encoder_train

						return _train



					def 	_lowercase					( self					:  int							,		__A					:  List[Any]	):
						with self.args.strategy.scope():
							try:
								if self.args.is_tpu or self.args.use_xla:
									# run additional 10 times to stabilize compilation for tpu
									logger.info("Do inference on TPU. Running model 5 times to stabilize compilation"	)
									timeit.repeat(__A							,		repeat=1							,		number=5	)

								# as written in https://docs.python.org/2/library/timeit.html#timeit.Timer.repeat, min should be taken rather than the average
								snake_case__			:				Optional[Any]       =  timeit.repeat(
								    __A							,		repeat=self.args.repeat							,		number=1_0							,		)

								return min(__A	) / 1_0.0
							except ResourceExhaustedError as e:
								self.print_fn(f'''Doesn\'t fit on GPU. {e}'''	)






					def 	_lowercase					( self					:  str							,		__A					:  Callable[[], None]	):
						logger.info(
						    "Note that TensorFlow allocates more memory than "
						    "it might need to speed up computation. "
						    "The memory reported here corresponds to the memory "
						    "reported by `nvidia-smi`, which can vary depending "
						    "on total available memory on the GPU that is used."	)
						with self.args.strategy.scope():
							try:
								if self.args.trace_memory_line_by_line:
									if not self.args.eager_mode:
										raise ValueError(
										    "`args.eager_mode` is set to `False`. Make sure to run model in eager mode to measure memory"
										    " consumption line by line."	)
									snake_case__			:				Optional[int]       =  start_memory_tracing("transformers"	)

								if self.args.is_tpu:
									# tpu
									raise NotImplementedError(
									    "Memory Benchmarking is currently not implemented for TPU. Please disable memory benchmarking"
									    " with `args.memory=False`"	)
								elif self.args.is_gpu:
									# gpu
									if not is_pyanvml_available():
										logger.warning(
										    "py3nvml not installed, we won't log GPU memory usage. "
										    "Install py3nvml (pip install py3nvml) to log information about GPU."	)
										snake_case__			:				List[str]       =  "N/A"
									else:
										logger.info(
										    "Measuring total GPU usage on GPU device. Make sure to not have additional processes"
										    " running on the same GPU."	)
										# init nvml
										nvml.nvmlInit()
										func()
										snake_case__			:				Any       =  nvml.nvmlDeviceGetHandleByIndex(self.args.device_idx	)
										snake_case__			:				Optional[Any]       =  nvml.nvmlDeviceGetMemoryInfo(__A	)
										snake_case__			:				Optional[int]       =  meminfo.used
										snake_case__			:				Any       =  Memory(__A	)
										# shutdown nvml
										nvml.nvmlShutdown()
								else:
									# cpu
									if self.args.trace_memory_line_by_line:
										logger.info(
										    "When enabling line by line tracing, the max peak memory for CPU is inaccurate in"
										    " TensorFlow."	)
										snake_case__			:				int       =  None
									else:
										snake_case__			:				Any       =  measure_peak_memory_cpu(__A	)
										snake_case__			:				Tuple       =  Memory(__A	) if isinstance(__A							,		__A	) else memory_bytes
								if self.args.trace_memory_line_by_line:
									snake_case__			:				Optional[int]       =  stop_memory_tracing(__A	)
									if memory is None:
										snake_case__			:				Dict       =  summary.total
								else:
									snake_case__			:				List[str]       =  None

								return memory, summary
							except ResourceExhaustedError as e:
								self.print_fn(f'''Doesn\'t fit on GPU. {e}'''	)
								return "N/A", None



