




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

import datasets
from datasets import logging


SCREAMING_SNAKE_CASE__       :      Optional[int]  =   """\

"""

SCREAMING_SNAKE_CASE__       :      Dict  =   """
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
"""

SCREAMING_SNAKE_CASE__       :      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 		UpperCamelCase__	(datasets.Metric     ):

    '''simple docstring'''



    def     _lowercase     (    self     )     ->      Optional[int]:
           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     _lowercase     (    self     ,  UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__ = 16     ,  UpperCamelCase__ = True     ,  UpperCamelCase__=None     )     ->      Tuple:
           if device is not None:
                  assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
                  if device == "gpu":
                         lowerCamelCase   :      List[Any]			 =					"""cuda"""
           else:
                  lowerCamelCase   :      int			 =					"""cuda""" if torch.cuda.is_available() else """cpu"""

           lowerCamelCase   :      int			 =					AutoModelForCausalLM.from_pretrained(a_     )
           lowerCamelCase   :      Optional[int]			 =					model.to(a_     )

           lowerCamelCase   :      Dict			 =					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:
                  lowerCamelCase   :      str			 =					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"
                  lowerCamelCase   :      Optional[int]			 =					model.config.max_length - 1
           else:
                  lowerCamelCase   :      List[str]			 =					model.config.max_length

           lowerCamelCase   :      Union[str, Any]			 =					tokenizer(
               a_     ,  add_special_tokens=a_     ,  padding=a_     ,  truncation=a_     ,  max_length=a_     ,  return_tensors="pt"     ,  return_attention_mask=a_     ,  ).to(a_     )

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

           lowerCamelCase   :      List[str]			 =					[]
           lowerCamelCase   :      Any			 =					CrossEntropyLoss(reduction="none"     )

           for start_index in logging.tqdm(range(0     ,  len(a_     )     ,  a_     )     ):
                  lowerCamelCase   :      Optional[int]			 =					min(start_index + batch_size     ,  len(a_     )     )
                  lowerCamelCase   :      int			 =					encoded_texts[start_index:end_index]
                  lowerCamelCase   :      Any			 =					attn_masks[start_index:end_index]

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

                  lowerCamelCase   :      Any			 =					encoded_batch

                  with torch.no_grad():
                         lowerCamelCase   :      Any			 =					model(a_     ,  attention_mask=a_     ).logits

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

                  lowerCamelCase   :      Any			 =					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 collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
   from ...onnx.config import PatchingSpec
   from ...tokenization_utils_base import PreTrainedTokenizerBase


A_							: Any						 =	logging.get_logger(__name__)

A_							: Optional[int]						 =	{
    """allenai/longformer-base-4096""": """https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096""": """https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json""",
    """allenai/longformer-large-4096-finetuned-triviaqa""": (
        """https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"""
    ),
    """allenai/longformer-base-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
    """allenai/longformer-large-4096-extra.pos.embd.only""": (
        """https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"""
    ),
}



class 							lowercase       (  _lowerCamelCase				):


 """simple docstring"""


 UpperCAmelCase							=  """longformer"""







 def __init__(							self  ,a_ = 512  ,a_ = 2  ,a_ = 1  ,a_ = 0  ,a_ = 2  ,a_ = 30_522  ,a_ = 768  ,a_ = 12  ,a_ = 12  ,a_ = 3_072  ,a_ = "gelu"  ,a_ = 0.1  ,a_ = 0.1  ,a_ = 512  ,a_ = 2  ,a_ = 0.02  ,a_ = 1E-1_2  ,a_ = False  ,**a_  ,)		->   List[Any]:
        super().__init__(pad_token_id=a_  ,**a_							)

        _UpperCAmelCase  :						List[Any]			     = attention_window
        _UpperCAmelCase  :						Any			     = sep_token_id
        _UpperCAmelCase  :						Dict			     = bos_token_id
        _UpperCAmelCase  :						Tuple			     = eos_token_id
        _UpperCAmelCase  :						Tuple			     = vocab_size
        _UpperCAmelCase  :						Optional[Any]			     = hidden_size
        _UpperCAmelCase  :						Optional[int]			     = num_hidden_layers
        _UpperCAmelCase  :						Union[str, Any]			     = num_attention_heads
        _UpperCAmelCase  :						Optional[int]			     = hidden_act
        _UpperCAmelCase  :						str			     = intermediate_size
        _UpperCAmelCase  :						List[Any]			     = hidden_dropout_prob
        _UpperCAmelCase  :						Union[str, Any]			     = attention_probs_dropout_prob
        _UpperCAmelCase  :						List[str]			     = max_position_embeddings
        _UpperCAmelCase  :						Optional[int]			     = type_vocab_size
        _UpperCAmelCase  :						Any			     = initializer_range
        _UpperCAmelCase  :						Optional[int]			     = layer_norm_eps
        _UpperCAmelCase  :						Union[str, Any]			     = onnx_export







class 							lowercase       (  _lowerCamelCase				):


 """simple docstring"""


 def __init__(							self  ,a_  ,a_ = "default"  ,a_ = None							)		->   int:
        super().__init__(a_  ,a_  ,a_							)
        _UpperCAmelCase  :						Tuple			     = True







 @property
 def _snake_case (							self							)		->   Mapping[str, Mapping[int, str]]:
        if self.task == "multiple-choice":
               _UpperCAmelCase  :						Optional[int]			     = {0: """batch""", 1: """choice""", 2: """sequence"""}
        else:
               _UpperCAmelCase  :						Tuple			     = {0: """batch""", 1: """sequence"""}
        return OrderedDict(
            [
                ("""input_ids""", dynamic_axis),
                ("""attention_mask""", dynamic_axis),
                ("""global_attention_mask""", dynamic_axis),
            ]							)







 @property
 def _snake_case (							self							)		->   Mapping[str, Mapping[int, str]]:
        _UpperCAmelCase  :						str			     = super().outputs
        if self.task == "default":
               _UpperCAmelCase  :						int			     = {0: """batch"""}
        return outputs







 @property
 def _snake_case (							self							)		->   float:
        return 1E-4







 @property
 def _snake_case (							self							)		->   int:
        # needs to be >= 14 to support tril operator
        return max(super().default_onnx_opset  ,14							)







 def _snake_case (							self  ,a_  ,a_ = -1  ,a_ = -1  ,a_ = False  ,a_ = None  ,)		->   Mapping[str, Any]:
        _UpperCAmelCase  :						List[str]			     = super().generate_dummy_inputs(
            preprocessor=a_  ,batch_size=a_  ,seq_length=a_  ,is_pair=a_  ,framework=a_							)
        import torch

        # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
        # makes the export fail randomly
        _UpperCAmelCase  :						int			     = torch.zeros_like(inputs["""input_ids"""]							)
        # make every second token global
        _UpperCAmelCase  :						List[str]			     = 1

        return inputs



