
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


_SCREAMING_SNAKE_CASE     :   int							 =      logging.get_logger(__name__)  # pylint: disable=invalid-name

_SCREAMING_SNAKE_CASE     :   List[str]							 =      '\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 			UpperCamelCase__		(     snake_case_ ):







	'''simple docstring'''
	_lowerCAmelCase											=					42







class 			UpperCamelCase__		(     snake_case_ ):







	'''simple docstring'''





	def __init__(      self					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							):
					super().__init__()

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





	def 	__snake_case					(      self					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__		):






					if latents is None:
									A__	:						Any								=				randn_tensor(UpperCamelCase__					,							generator=UpperCamelCase__					,							device=UpperCamelCase__					,							dtype=UpperCamelCase__		)
					else:
									if latents.shape != shape:
													raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"		)
									A__	:						int								=				latents.to(UpperCamelCase__		)

					A__	:						str								=				latents * scheduler.init_noise_sigma
					return latents





	def 	__snake_case					(      self					,							UpperCamelCase__=0		):






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

					A__	:						Tuple								=				torch.device(F"cuda:{gpu_id}"		)

					A__	:						Optional[int]								=				[self.text_encoder, self.prior]
					for cpu_offloaded_model in models:
									if cpu_offloaded_model is not None:
													cpu_offload(UpperCamelCase__					,							UpperCamelCase__		)





	def 	__snake_case					(      self					,							UpperCamelCase__=0		):






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

					A__	:						str								=				torch.device(F"cuda:{gpu_id}"		)

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

					A__	:						str								=				None
					for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
									A__							,				A__	:						Optional[Any]								=				cpu_offload_with_hook(UpperCamelCase__					,							UpperCamelCase__					,							prev_module_hook=UpperCamelCase__		)

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

					# We'll offload the last model manually.
					A__	:						int								=				hook





	@property
	def 	__snake_case					(      self		):






					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(UpperCamelCase__					,							'''_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 	__snake_case					(      self					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							):
					len(UpperCamelCase__		) if isinstance(UpperCamelCase__					,							UpperCamelCase__		) else 1

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

					if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(UpperCamelCase__					,							UpperCamelCase__		):
									A__	:						Union[str, Any]								=				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}"		)

					A__	:						List[Any]								=				self.text_encoder(text_input_ids.to(UpperCamelCase__		)		)
					A__	:						Any								=				text_encoder_output.text_embeds

					A__	:						List[str]								=				prompt_embeds.repeat_interleave(UpperCamelCase__					,							dim=0		)
					# in Shap-E it normalize the prompt_embeds and then later rescale it
					A__	:						str								=				prompt_embeds / torch.linalg.norm(UpperCamelCase__					,							dim=-1					,							keepdim=UpperCamelCase__		)

					if do_classifier_free_guidance:
									A__	:						Any								=				torch.zeros_like(UpperCamelCase__		)

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

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

					return prompt_embeds





	@torch.no_grad()
	@replace_example_docstring(UpperCamelCase__		)
	def __call__(      self					,							UpperCamelCase__					,							UpperCamelCase__ = 1					,							UpperCamelCase__ = 25					,							UpperCamelCase__ = None					,							UpperCamelCase__ = None					,							UpperCamelCase__ = 4.0					,							UpperCamelCase__ = 64					,							UpperCamelCase__ = "pil"					,							UpperCamelCase__ = True					,							):






					if isinstance(UpperCamelCase__					,							UpperCamelCase__		):
									A__	:						Optional[Any]								=				1
					elif isinstance(UpperCamelCase__					,							UpperCamelCase__		):
									A__	:						Any								=				len(UpperCamelCase__		)
					else:
									raise ValueError(F"`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase__		)}"		)

					A__	:						Any								=				self._execution_device

					A__	:						Optional[int]								=				batch_size * num_images_per_prompt

					A__	:						Any								=				guidance_scale > 1.0
					A__	:						List[str]								=				self._encode_prompt(UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__					,							UpperCamelCase__		)

					# prior

					self.scheduler.set_timesteps(UpperCamelCase__					,							device=UpperCamelCase__		)
					A__	:						Union[str, Any]								=				self.scheduler.timesteps

					A__	:						Union[str, Any]								=				self.prior.config.num_embeddings
					A__	:						Any								=				self.prior.config.embedding_dim

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

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

									A__	:						Dict								=				self.prior(
									    UpperCamelCase__					,							timestep=UpperCamelCase__					,							proj_embedding=UpperCamelCase__					,							).predicted_image_embedding

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

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

									A__	:						Union[str, Any]								=				self.scheduler.step(
									    UpperCamelCase__					,							timestep=UpperCamelCase__					,							sample=UpperCamelCase__					,							).prev_sample

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

					A__	:						Tuple								=				[]
					for i, latent in enumerate(UpperCamelCase__		):
									A__	:						Tuple								=				self.renderer.decode(
									    latent[None, :]					,							UpperCamelCase__					,							size=UpperCamelCase__					,							ray_batch_size=4096					,							n_coarse_samples=64					,							n_fine_samples=128					,							)
									images.append(UpperCamelCase__		)

					A__	:						List[Any]								=				torch.stack(UpperCamelCase__		)

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

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

					if output_type == "pil":
									A__	:						Dict								=				[self.numpy_to_pil(UpperCamelCase__		) 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=UpperCamelCase__		)



import argparse
import logging
import sys
import time

import tensorflow as tf
from datasets import load_dataset

from transformers import AutoTokenizer, TFAutoModelForSequenceClassification


if __name__ == "__main__":
							SCREAMING_SNAKE_CASE__       			=				argparse.ArgumentParser()

							# Hyperparameters sent by the client are passed as command-line arguments to the script.
							parser.add_argument("""--epochs""", type=int, default=1)
							parser.add_argument("""--per_device_train_batch_size""", type=int, default=1_6)
							parser.add_argument("""--per_device_eval_batch_size""", type=int, default=8)
							parser.add_argument("""--model_name_or_path""", type=str)
							parser.add_argument("""--learning_rate""", type=str, default=5E-5)
							parser.add_argument("""--do_train""", type=bool, default=True)
							parser.add_argument("""--do_eval""", type=bool, default=True)
							parser.add_argument("""--output_dir""", type=str)

							SCREAMING_SNAKE_CASE__			,      SCREAMING_SNAKE_CASE__       			=				parser.parse_known_args()

							# overwrite batch size until we have tf_glue.py
							SCREAMING_SNAKE_CASE__       			=				1_6
							SCREAMING_SNAKE_CASE__       			=				1_6

							# Set up logging
							SCREAMING_SNAKE_CASE__       			=				logging.getLogger(__name__)

							logging.basicConfig(
							    level=logging.getLevelName("""INFO"""),
							    handlers=[logging.StreamHandler(sys.stdout)],
							    format="""%(asctime)s - %(name)s - %(levelname)s - %(message)s""",
							)

							# Load model and tokenizer
							SCREAMING_SNAKE_CASE__       			=				TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path)
							SCREAMING_SNAKE_CASE__       			=				AutoTokenizer.from_pretrained(args.model_name_or_path)

							# Load dataset
							SCREAMING_SNAKE_CASE__			,      SCREAMING_SNAKE_CASE__       			=				load_dataset("""imdb""", split=["""train""", """test"""])
							SCREAMING_SNAKE_CASE__       			=				train_dataset.shuffle().select(range(5_0_0_0))  # smaller the size for train dataset to 5k
							SCREAMING_SNAKE_CASE__       			=				test_dataset.shuffle().select(range(5_0_0))  # smaller the size for test dataset to 500

							# Preprocess train dataset
							SCREAMING_SNAKE_CASE__       			=				train_dataset.map(
							    lambda e: tokenizer(e["""text"""], truncation=True, padding="""max_length"""), batched=True
							)
							train_dataset.set_format(type="""tensorflow""", columns=["""input_ids""", """attention_mask""", """label"""])

							SCREAMING_SNAKE_CASE__       			=				{
							    x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
							    for x in ["""input_ids""", """attention_mask"""]
							}
							SCREAMING_SNAKE_CASE__       			=				tf.data.Dataset.from_tensor_slices((train_features, train_dataset["""label"""])).batch(
							    args.per_device_train_batch_size
							)

							# Preprocess test dataset
							SCREAMING_SNAKE_CASE__       			=				test_dataset.map(
							    lambda e: tokenizer(e["""text"""], truncation=True, padding="""max_length"""), batched=True
							)
							test_dataset.set_format(type="""tensorflow""", columns=["""input_ids""", """attention_mask""", """label"""])

							SCREAMING_SNAKE_CASE__       			=				{
							    x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length])
							    for x in ["""input_ids""", """attention_mask"""]
							}
							SCREAMING_SNAKE_CASE__       			=				tf.data.Dataset.from_tensor_slices((test_features, test_dataset["""label"""])).batch(
							    args.per_device_eval_batch_size
							)

							# fine optimizer and loss
							SCREAMING_SNAKE_CASE__       			=				tf.keras.optimizers.Adam(learning_rate=args.learning_rate)
							SCREAMING_SNAKE_CASE__       			=				tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
							SCREAMING_SNAKE_CASE__       			=				[tf.keras.metrics.SparseCategoricalAccuracy()]
							model.compile(optimizer=optimizer, loss=loss, metrics=metrics)

							SCREAMING_SNAKE_CASE__       			=				time.time()
							SCREAMING_SNAKE_CASE__       			=				model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size)
							SCREAMING_SNAKE_CASE__       			=				time.time() - start_train_time

							logger.info("""*** Train ***""")
							logger.info(f"""train_runtime = {end_train_time}""")
							for key, value in train_results.history.items():
														logger.info(f"""  {key} = {value}""")

