




"""simple docstring"""







import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference




class       lowerCAmelCase__       (			_UpperCAmelCase  ,			unittest.TestCase    ):


				"""simple docstring"""





				__UpperCAmelCase :     Union[str, Any]       =      ShapEImgaImgPipeline
				__UpperCAmelCase :     Dict       =      ["image"]
				__UpperCAmelCase :     Tuple       =      ["image"]
				__UpperCAmelCase :     List[Any]       =      [
				    "num_images_per_prompt",
				    "num_inference_steps",
				    "generator",
				    "latents",
				    "guidance_scale",
				    "frame_size",
				    "output_type",
				    "return_dict",
				]
				__UpperCAmelCase :     Dict       =      False



				@property
				def       snake_case    (     self					:	List[str]						):
						return 3_2



				@property
				def       snake_case    (     self					:	int						):
						return 3_2



				@property
				def       snake_case    (     self					:	Optional[int]						):
						return self.time_input_dim * 4



				@property
				def       snake_case    (     self					:	Any						):
						return 8



				@property
				def       snake_case    (     self					:	Any						):
						torch.manual_seed(0						)
						__lowercase				:		Tuple												=				CLIPVisionConfig(
						    hidden_size=self.text_embedder_hidden_size    ,   image_size=6_4    ,   projection_dim=self.text_embedder_hidden_size    ,   intermediate_size=3_7    ,   num_attention_heads=4    ,   num_channels=3    ,   num_hidden_layers=5    ,   patch_size=1    ,   )

						__lowercase				:		Tuple												=				CLIPVisionModel(lowercase_						)
						return model



				@property
				def       snake_case    (     self					:	List[Any]						):
						__lowercase				:		Optional[int]												=				CLIPImageProcessor(
						    crop_size=2_2_4    ,   do_center_crop=lowercase_    ,   do_normalize=lowercase_    ,   do_resize=lowercase_    ,   image_mean=[0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]    ,   image_std=[0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]    ,   resample=3    ,   size=2_2_4    ,   )

						return image_processor



				@property
				def       snake_case    (     self					:	Optional[Any]						):
						torch.manual_seed(0						)

						__lowercase				:		Optional[Any]												=				{
						    """num_attention_heads""": 2,
						    """attention_head_dim""": 1_6,
						    """embedding_dim""": self.time_input_dim,
						    """num_embeddings""": 3_2,
						    """embedding_proj_dim""": self.text_embedder_hidden_size,
						    """time_embed_dim""": self.time_embed_dim,
						    """num_layers""": 1,
						    """clip_embed_dim""": self.time_input_dim * 2,
						    """additional_embeddings""": 0,
						    """time_embed_act_fn""": """gelu""",
						    """norm_in_type""": """layer""",
						    """embedding_proj_norm_type""": """layer""",
						    """encoder_hid_proj_type""": None,
						    """added_emb_type""": None,
						}

						__lowercase				:		Union[str, Any]												=				PriorTransformer(**lowercase_						)
						return model



				@property
				def       snake_case    (     self					:	List[Any]						):
						torch.manual_seed(0						)

						__lowercase				:		str												=				{
						    """param_shapes""": (
						        (self.renderer_dim, 9_3),
						        (self.renderer_dim, 8),
						        (self.renderer_dim, 8),
						        (self.renderer_dim, 8),
						    ),
						    """d_latent""": self.time_input_dim,
						    """d_hidden""": self.renderer_dim,
						    """n_output""": 1_2,
						    """background""": (
						        0.1,
						        0.1,
						        0.1,
						    ),
						}
						__lowercase				:		int												=				ShapERenderer(**lowercase_						)
						return model



				def       snake_case    (     self					:	Tuple						):
						__lowercase				:		List[str]												=				self.dummy_prior
						__lowercase				:		Union[str, Any]												=				self.dummy_image_encoder
						__lowercase				:		Union[str, Any]												=				self.dummy_image_processor
						__lowercase				:		List[Any]												=				self.dummy_renderer

						__lowercase				:		List[str]												=				HeunDiscreteScheduler(
						    beta_schedule="exp"    ,   num_train_timesteps=1_0_2_4    ,   prediction_type="sample"    ,   use_karras_sigmas=lowercase_    ,   clip_sample=lowercase_    ,   clip_sample_range=1.0    ,   )
						__lowercase				:		int												=				{
						    """prior""": prior,
						    """image_encoder""": image_encoder,
						    """image_processor""": image_processor,
						    """renderer""": renderer,
						    """scheduler""": scheduler,
						}

						return components



				def       snake_case    (     self					:	Optional[int]    ,   lowercase__					:	List[Any]    ,   lowercase__					:	List[str]=0						):
						__lowercase				:		str												=				floats_tensor((1, 3, 6_4, 6_4)    ,   rng=random.Random(lowercase_						)						).to(lowercase_						)

						if str(lowercase_						).startswith("mps"						):
								__lowercase				:		int												=				torch.manual_seed(lowercase_						)
						else:
								__lowercase				:		Dict												=				torch.Generator(device=lowercase_						).manual_seed(lowercase_						)
						__lowercase				:		int												=				{
						    """image""": input_image,
						    """generator""": generator,
						    """num_inference_steps""": 1,
						    """frame_size""": 3_2,
						    """output_type""": """np""",
						}
						return inputs



				def       snake_case    (     self					:	int						):
						__lowercase				:		Optional[Any]												=				"""cpu"""

						__lowercase				:		Union[str, Any]												=				self.get_dummy_components()

						__lowercase				:		Optional[Any]												=				self.pipeline_class(**lowercase_						)
						__lowercase				:		Tuple												=				pipe.to(lowercase_						)

						pipe.set_progress_bar_config(disable=lowercase_						)

						__lowercase				:		int												=				pipe(**self.get_dummy_inputs(lowercase_						)						)
						__lowercase				:		Union[str, Any]												=				output.images[0]
						__lowercase				:		Tuple												=				image[0, -3:, -3:, -1]

						assert image.shape == (2_0, 3_2, 3_2, 3)

						__lowercase				:		Any												=				np.array(
						    [
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						        0.0_0_0_3_9_2_1_6,
						    ]						)

						assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2



				def       snake_case    (     self					:	str						):
						# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
						self._test_inference_batch_consistent(batch_sizes=[1, 2]						)



				def       snake_case    (     self					:	str						):
						__lowercase				:		Union[str, Any]												=				torch_device == """cpu"""
						__lowercase				:		int												=				True
						self._test_inference_batch_single_identical(
						    batch_size=2    ,   test_max_difference=lowercase_    ,   relax_max_difference=lowercase_    ,   )



				def       snake_case    (     self					:	List[Any]						):
						__lowercase				:		Optional[int]												=				self.get_dummy_components()
						__lowercase				:		Any												=				self.pipeline_class(**lowercase_						)
						__lowercase				:		Optional[int]												=				pipe.to(lowercase_						)
						pipe.set_progress_bar_config(disable=lowercase_						)

						__lowercase				:		List[str]												=				1
						__lowercase				:		Optional[Any]												=				2

						__lowercase				:		Optional[Any]												=				self.get_dummy_inputs(lowercase_						)

						for key in inputs.keys():
								if key in self.batch_params:
										__lowercase				:		Tuple												=				batch_size * [inputs[key]]

						__lowercase				:		List[Any]												=				pipe(**lowercase_    ,   num_images_per_prompt=lowercase_						)[0]

						assert images.shape[0] == batch_size * num_images_per_prompt





@slow
@require_torch_gpu
class       lowerCAmelCase__       (			unittest.TestCase    ):


				"""simple docstring"""





				def       snake_case    (     self					:	str						):
						# clean up the VRAM after each test
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



				def       snake_case    (     self					:	Optional[int]						):
						__lowercase				:		Tuple												=				load_image(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/shap_e/corgi.png"						)
						__lowercase				:		str												=				load_numpy(
						    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
						    "/shap_e/test_shap_e_img2img_out.npy"						)
						__lowercase				:		Union[str, Any]												=				ShapEImgaImgPipeline.from_pretrained("openai/shap-e-img2img"						)
						__lowercase				:		List[Any]												=				pipe.to(lowercase_						)
						pipe.set_progress_bar_config(disable=lowercase_						)

						__lowercase				:		Optional[Any]												=				torch.Generator(device=lowercase_						).manual_seed(0						)

						__lowercase				:		List[Any]												=				pipe(
						    lowercase_    ,   generator=lowercase_    ,   guidance_scale=3.0    ,   num_inference_steps=6_4    ,   frame_size=6_4    ,   output_type="np"    ,   ).images[0]

						assert images.shape == (2_0, 6_4, 6_4, 3)

						assert_mean_pixel_difference(lowercase_    ,   lowercase_						)






"""simple docstring"""







import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


__A   :  str					=      '\\n\n'

__A   :  int					=      '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'

__A   :  Optional[Any]					=      '\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        78.22\n        >>> print(round(results["perplexities"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = datasets.load_dataset("wikitext",\n        ...                                     "wikitext-2-raw-v1",\n        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!=\'\']\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        60.35\n        >>> print(round(results["perplexities"][0], 2))\n        81.12\n'




@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,			_KWARGS_DESCRIPTION    )
class       lowerCAmelCase__       (			datasets.Metric    ):


				"""simple docstring"""





				def       snake_case    (     self					:	Dict						):
						return datasets.MetricInfo(
						    description=_DESCRIPTION    ,   citation=_CITATION    ,   inputs_description=_KWARGS_DESCRIPTION    ,   features=datasets.Features(
						        {
						            "input_texts": datasets.Value("string"						),
						        }						)    ,   reference_urls=["https://huggingface.co/docs/transformers/perplexity"]    ,   )



				def       snake_case    (     self					:	Optional[Any]    ,   lowercase__					:	int    ,   lowercase__					:	str    ,   lowercase__					:	int = 1_6    ,   lowercase__					:	bool = True    ,   lowercase__					:	List[Any]=None						):
						if device is not None:
								assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
								if device == "gpu":
										__lowercase				:		Optional[Any]												=				"cuda"
						else:
								__lowercase				:		Optional[Any]												=				"cuda" if torch.cuda.is_available() else "cpu"

						__lowercase				:		List[str]												=				AutoModelForCausalLM.from_pretrained(lowercase__						)
						__lowercase				:		str												=				model.to(lowercase__						)

						__lowercase				:		Any												=				AutoTokenizer.from_pretrained(lowercase__						)

						# if batch_size > 1 (which generally leads to padding being required), and
						# if there is not an already assigned pad_token, assign an existing
						# special token to also be the padding token
						if tokenizer.pad_token is None and batch_size > 1:
								__lowercase				:		Any												=				list(tokenizer.special_tokens_map_extended.values()						)
								# check that the model already has at least one special token defined
								assert (
								    len(lowercase__						) > 0
								), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
								# assign one of the special tokens to also be the pad token
								tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]}						)

						if add_start_token:
								# leave room for <BOS> token to be added:
								assert (
								    tokenizer.bos_token is not None
								), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
								__lowercase				:		Any												=				model.config.max_length - 1
						else:
								__lowercase				:		Union[str, Any]												=				model.config.max_length

						__lowercase				:		List[Any]												=				tokenizer(
						    lowercase__    ,   add_special_tokens=lowercase__    ,   padding=lowercase__    ,   truncation=lowercase__    ,   max_length=lowercase__    ,   return_tensors="pt"    ,   return_attention_mask=lowercase__    ,   ).to(lowercase__						)

						__lowercase				:		Tuple												=				encodings["input_ids"]
						__lowercase				:		Tuple												=				encodings["attention_mask"]

						# check that each input is long enough:
						if add_start_token:
								assert torch.all(torch.ge(attn_masks.sum(1						)    ,   1						)						), "Each input text must be at least one token long."
						else:
								assert torch.all(
								    torch.ge(attn_masks.sum(1						)    ,   2						)						), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

						__lowercase				:		Optional[int]												=				[]
						__lowercase				:		List[Any]												=				CrossEntropyLoss(reduction="none"						)

						for start_index in logging.tqdm(range(0    ,   len(lowercase__						)    ,   lowercase__						)						):
								__lowercase				:		List[str]												=				min(start_index + batch_size    ,   len(lowercase__						)						)
								__lowercase				:		Any												=				encoded_texts[start_index:end_index]
								__lowercase				:		Dict												=				attn_masks[start_index:end_index]

								if add_start_token:
										__lowercase				:		str												=				torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0						)						).to(lowercase__						)
										__lowercase				:		Optional[Any]												=				torch.cat([bos_tokens_tensor, encoded_batch]    ,   dim=1						)
										__lowercase				:		Union[str, Any]												=				torch.cat(
										    [torch.ones(bos_tokens_tensor.size()    ,   dtype=torch.intaa						).to(lowercase__						), attn_mask]    ,   dim=1						)

								__lowercase				:		Optional[int]												=				encoded_batch

								with torch.no_grad():
										__lowercase				:		Any												=				model(lowercase__    ,   attention_mask=lowercase__						).logits

								__lowercase				:		Any												=				out_logits[..., :-1, :].contiguous()
								__lowercase				:		Tuple												=				labels[..., 1:].contiguous()
								__lowercase				:		str												=				attn_mask[..., 1:].contiguous()

								__lowercase				:		Optional[int]												=				torch.expa(
								    (loss_fct(shift_logits.transpose(1    ,   2						)    ,   lowercase__						) * shift_attention_mask_batch).sum(1						)
								    / shift_attention_mask_batch.sum(1						)						)

								ppls += perplexity_batch.tolist()

						return {"perplexities": ppls, "mean_perplexity": np.mean(lowercase__						)}
