






"""simple docstring"""





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

import datasets
from datasets import logging


UpperCamelCase_	:				Optional[int]										= """\

"""

UpperCamelCase_	:				Union[str, Any]										= """
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
"""

UpperCamelCase_	:				List[str]										= """
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to 'cuda' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = [\"lorem ipsum\", \"Happy Birthday!\", \"Bienvenue\"]
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        78.22
        >>> print(round(results[\"perplexities\"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric(\"perplexity\")
        >>> input_texts = datasets.load_dataset(\"wikitext\",
        ...                                     \"wikitext-2-raw-v1\",
        ...                                     split=\"test\")[\"text\"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!='']
        >>> results = perplexity.compute(model_id='gpt2',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        ['perplexities', 'mean_perplexity']
        >>> print(round(results[\"mean_perplexity\"], 2))
        60.35
        >>> print(round(results[\"perplexities\"][0], 2))
        81.12
"""


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


      def _UpperCamelCase						(    self				:	Optional[int]						):





            """simple docstring"""







            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 _UpperCamelCase						(    self				:	Tuple							,   a				:	str							,   a				:	Optional[int]							,   a				:	int = 1_6							,   a				:	bool = True							,   a				:	List[str]=None						):





            """simple docstring"""







            if device is not None:
                  assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
                  if device == "gpu":
                        __snake_case      :    int  			='''cuda'''
            else:
                  __snake_case      :    Dict  			='''cuda''' if torch.cuda.is_available() else '''cpu'''

            __snake_case      :    Union[str, Any]  			=AutoModelForCausalLM.from_pretrained(a						)
            __snake_case      :    Dict  			=model.to(a						)

            __snake_case      :    List[str]  			=AutoTokenizer.from_pretrained(a						)

            # 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:
                  __snake_case      :    Dict  			=list(tokenizer.special_tokens_map_extended.values()						)
                  # check that the model already has at least one special token defined
                  assert (
                      len(a						) > 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"
                  __snake_case      :    Union[str, Any]  			=model.config.max_length - 1
            else:
                  __snake_case      :    Any  			=model.config.max_length

            __snake_case      :    List[Any]  			=tokenizer(
                a							,   add_special_tokens=a							,   padding=a							,   truncation=a							,   max_length=a							,   return_tensors='''pt'''							,   return_attention_mask=a							,   ).to(a						)

            __snake_case      :    int  			=encodings['''input_ids''']
            __snake_case      :    Optional[Any]  			=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."

            __snake_case      :    int  			=[]
            __snake_case      :    List[Any]  			=CrossEntropyLoss(reduction='''none'''						)

            for start_index in logging.tqdm(range(0							,   len(a						)							,   a						)						):
                  __snake_case      :    Tuple  			=min(start_index + batch_size							,   len(a						)						)
                  __snake_case      :    str  			=encoded_texts[start_index:end_index]
                  __snake_case      :    int  			=attn_masks[start_index:end_index]

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

                  __snake_case      :    Any  			=encoded_batch

                  with torch.no_grad():
                        __snake_case      :    Tuple  			=model(a							,   attention_mask=a						).logits

                  __snake_case      :    Union[str, Any]  			=out_logits[..., :-1, :].contiguous()
                  __snake_case      :    List[Any]  			=labels[..., 1:].contiguous()
                  __snake_case      :    Optional[int]  			=attn_mask[..., 1:].contiguous()

                  __snake_case      :    List[str]  			=torch.expa(
                      (loss_fct(shift_logits.transpose(1							,   2						)							,   a						) * shift_attention_mask_batch).sum(1						)
                      / shift_attention_mask_batch.sum(1						)						)

                  ppls += perplexity_batch.tolist()

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










"""simple docstring"""





from math import acos, sin
from typing import List, Tuple, Union

import numpy as np
import torch
from PIL import Image

from ...models import AutoencoderKL, UNetaDConditionModel
from ...schedulers import DDIMScheduler, DDPMScheduler
from ...utils import randn_tensor
from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput
from .mel import Mel


class      _lowercase (     lowerCAmelCase						):
      _a   :     Optional[Any]								=   ['''vqvae''']


      def __init__(    self				:	Optional[Any]							,   a				:	AutoencoderKL							,   a				:	UNetaDConditionModel							,   a				:	Mel							,   a				:	Union[DDIMScheduler, DDPMScheduler]							,   ):





            """simple docstring"""







            super().__init__()
            self.register_modules(unet=a							,   scheduler=a							,   mel=a							,   vqvae=a						)


      def _UpperCamelCase						(    self				:	Any						):





            """simple docstring"""







            return 5_0 if isinstance(self.scheduler							,   a						) else 1_0_0_0


      @torch.no_grad()
      def __call__(    self				:	Optional[int]							,   a				:	int = 1							,   a				:	str = None							,   a				:	np.ndarray = None							,   a				:	int = 0							,   a				:	int = 0							,   a				:	int = None							,   a				:	torch.Generator = None							,   a				:	float = 0							,   a				:	float = 0							,   a				:	torch.Generator = None							,   a				:	float = 0							,   a				:	torch.Tensor = None							,   a				:	torch.Tensor = None							,   a				:	Optional[int]=True							,   ):





            """simple docstring"""







            __snake_case      :    List[Any]  			=steps or self.get_default_steps()
            self.scheduler.set_timesteps(a						)
            __snake_case      :    int  			=step_generator or generator
            # For backwards compatibility
            if type(self.unet.config.sample_size						) == int:
                  __snake_case      :    Any  			=(self.unet.config.sample_size, self.unet.config.sample_size)
            if noise is None:
                  __snake_case      :    List[str]  			=randn_tensor(
                      (
                          batch_size,
                          self.unet.config.in_channels,
                          self.unet.config.sample_size[0],
                          self.unet.config.sample_size[1],
                      )							,   generator=a							,   device=self.device							,   )
            __snake_case      :    int  			=noise
            __snake_case      :    List[str]  			=None

            if audio_file is not None or raw_audio is not None:
                  self.mel.load_audio(a							,   a						)
                  __snake_case      :    List[Any]  			=self.mel.audio_slice_to_image(a						)
                  __snake_case      :    Tuple  			=np.frombuffer(input_image.tobytes()							,   dtype='''uint8'''						).reshape(
                      (input_image.height, input_image.width)						)
                  __snake_case      :    str  			=(input_image / 2_5_5) * 2 - 1
                  __snake_case      :    Optional[int]  			=torch.tensor(input_image[np.newaxis, :, :]							,   dtype=torch.float						).to(self.device						)

                  if self.vqvae is not None:
                        __snake_case      :    Tuple  			=self.vqvae.encode(torch.unsqueeze(a							,   0						)						).latent_dist.sample(
                            generator=a						)[0]
                        __snake_case      :    Optional[int]  			=self.vqvae.config.scaling_factor * input_images

                  if start_step > 0:
                        __snake_case      :    str  			=self.scheduler.add_noise(a							,   a							,   self.scheduler.timesteps[start_step - 1]						)

                  __snake_case      :    Optional[Any]  			=(
                      self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length
                  )
                  __snake_case      :    int  			=int(mask_start_secs * pixels_per_second						)
                  __snake_case      :    Any  			=int(mask_end_secs * pixels_per_second						)
                  __snake_case      :    Union[str, Any]  			=self.scheduler.add_noise(a							,   a							,   torch.tensor(self.scheduler.timesteps[start_step:]						)						)

            for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:]						)						):
                  if isinstance(self.unet							,   a						):
                        __snake_case      :    List[str]  			=self.unet(a							,   a							,   a						)['''sample''']
                  else:
                        __snake_case      :    Union[str, Any]  			=self.unet(a							,   a						)['''sample''']

                  if isinstance(self.scheduler							,   a						):
                        __snake_case      :    List[str]  			=self.scheduler.step(
                            model_output=a							,   timestep=a							,   sample=a							,   eta=a							,   generator=a							,   )['''prev_sample''']
                  else:
                        __snake_case      :    List[Any]  			=self.scheduler.step(
                            model_output=a							,   timestep=a							,   sample=a							,   generator=a							,   )['''prev_sample''']

                  if mask is not None:
                        if mask_start > 0:
                              __snake_case      :    Any  			=mask[:, step, :, :mask_start]
                        if mask_end > 0:
                              __snake_case      :    Optional[Any]  			=mask[:, step, :, -mask_end:]

            if self.vqvae is not None:
                  # 0.18215 was scaling factor used in training to ensure unit variance
                  __snake_case      :    str  			=1 / self.vqvae.config.scaling_factor * images
                  __snake_case      :    Optional[int]  			=self.vqvae.decode(a						)['''sample''']

            __snake_case      :    int  			=(images / 2 + 0.5).clamp(0							,   1						)
            __snake_case      :    Optional[Any]  			=images.cpu().permute(0							,   2							,   3							,   1						).numpy()
            __snake_case      :    Optional[int]  			=(images * 2_5_5).round().astype('''uint8'''						)
            __snake_case      :    Tuple  			=list(
                (Image.fromarray(_[:, :, 0]						) for _ in images)
                if images.shape[3] == 1
                else (Image.fromarray(a							,   mode='''RGB'''						).convert('''L'''						) for _ in images)						)

            __snake_case      :    Union[str, Any]  			=[self.mel.image_to_audio(a						) for _ in images]
            if not return_dict:
                  return images, (self.mel.get_sample_rate(), audios)

            return BaseOutput(**AudioPipelineOutput(np.array(a						)[:, np.newaxis, :]						)							,   **ImagePipelineOutput(a						)						)


      @torch.no_grad()
      def _UpperCamelCase						(    self				:	int							,   a				:	List[Image.Image]							,   a				:	int = 5_0						):





            """simple docstring"""







            assert isinstance(self.scheduler							,   a						)
            self.scheduler.set_timesteps(a						)
            __snake_case      :    Dict  			=np.array(
                [np.frombuffer(image.tobytes()							,   dtype='''uint8'''						).reshape((1, image.height, image.width)						) for image in images]						)
            __snake_case      :    Any  			=(sample / 2_5_5) * 2 - 1
            __snake_case      :    Any  			=torch.Tensor(a						).to(self.device						)

            for t in self.progress_bar(torch.flip(self.scheduler.timesteps							,   (0,)						)						):
                  __snake_case      :    Union[str, Any]  			=t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps
                  __snake_case      :    Dict  			=self.scheduler.alphas_cumprod[t]
                  __snake_case      :    str  			=(
                      self.scheduler.alphas_cumprod[prev_timestep]
                      if prev_timestep >= 0
                      else self.scheduler.final_alpha_cumprod
                  )
                  __snake_case      :    int  			=1 - alpha_prod_t
                  __snake_case      :    Tuple  			=self.unet(a							,   a						)['''sample''']
                  __snake_case      :    str  			=(1 - alpha_prod_t_prev) ** 0.5 * model_output
                  __snake_case      :    Dict  			=(sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5)
                  __snake_case      :    Optional[int]  			=sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output

            return sample







      @staticmethod
      def _UpperCamelCase						(    a				:	torch.Tensor							,   a				:	torch.Tensor							,   a				:	float						):





            """simple docstring"""







            __snake_case      :    List[Any]  			=acos(torch.dot(torch.flatten(a						)							,   torch.flatten(a						)						) / torch.norm(a						) / torch.norm(a						)						)
            return sin((1 - alpha) * theta						) * xa / sin(a						) + sin(alpha * theta						) * xa / sin(a						)


