


"""simple docstring"""







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

import datasets
from datasets import logging


lowerCamelCase_       :       List[Any]      						=  """\

"""

lowerCamelCase_       :       List[str]      						=  """
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
"""

lowerCamelCase_       :       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 				__A    (	datasets.Metric      ):






 """simple docstring"""




 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Any:
     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 				SCREAMING_SNAKE_CASE							(		self			,   __A			,   __A			,   __A = 16			,   __A = True			,   __A=None						) ->					Union[str, Any]:
     if device is not None:
         assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
         if device == "gpu":
             a					='''cuda'''
     else:
         a					='''cuda''' if torch.cuda.is_available() else '''cpu'''

     a					=AutoModelForCausalLM.from_pretrained(__A						)
     a					=model.to(__A						)

     a					=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:
         a					=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"
         a					=model.config.max_length - 1
     else:
         a					=model.config.max_length

     a					=tokenizer(
         __A			,   add_special_tokens=__A			,   padding=__A			,   truncation=__A			,   max_length=__A			,   return_tensors='''pt'''			,   return_attention_mask=__A			,   ).to(__A						)

     a					=encodings['''input_ids''']
     a					=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."

     a					=[]
     a					=CrossEntropyLoss(reduction='''none'''						)

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

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

         a					=encoded_batch

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

         a					=out_logits[..., :-1, :].contiguous()
         a					=labels[..., 1:].contiguous()
         a					=attn_mask[..., 1:].contiguous()

         a					=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"""







import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
       import tensorflow as tf

if is_tensorflow_text_available():
       from transformers.models.bert import TFBertTokenizer


lowerCamelCase_       :       str      						=  ["""bert-base-uncased""", """bert-base-cased"""]
lowerCamelCase_       :       List[str]      						=  """hf-internal-testing/tiny-bert-tf-only"""

if is_tf_available():






       class 				__A    (	tf.keras.Model      ):






        """simple docstring"""




        def __init__(		self			,   __A						) ->					Dict:
            super().__init__()
            a					=tokenizer
            a					=AutoConfig.from_pretrained(__A						)
            a					=TFAutoModel.from_config(__A						)





        def 				SCREAMING_SNAKE_CASE							(		self			,   __A						) ->					int:
            a					=self.tokenizer(__A						)
            a					=self.bert(**__A						)
            return out["pooler_output"]






@require_tf
@require_tensorflow_text
class 				__A    (	unittest.TestCase      ):






 """simple docstring"""




 def 				SCREAMING_SNAKE_CASE							(		self						) ->					str:
     super().setUp()

     a					=[
         BertTokenizer.from_pretrained(__A						) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
     ]  # repeat for when fast_bert_tokenizer=false
     a					=[TFBertTokenizer.from_pretrained(__A						) for checkpoint in TOKENIZER_CHECKPOINTS] + [
         TFBertTokenizer.from_pretrained(__A			,   use_fast_bert_tokenizer=__A						)
         for checkpoint in TOKENIZER_CHECKPOINTS
     ]
     assert len(self.tokenizers						) == len(self.tf_tokenizers						)

     a					=[
         '''This is a straightforward English test sentence.''',
         '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
         '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
         '''And some much more rare Chinese: 齉 堃 齉堃''',
         '''Je vais aussi écrire en français pour tester les accents''',
         '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
     ]
     a					=list(zip(self.test_sentences			,   self.test_sentences[::-1]						)						)


 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Optional[int]:
     for tokenizer, tf_tokenizer in zip(self.tokenizers			,   self.tf_tokenizers						):
         for test_inputs in (self.test_sentences, self.paired_sentences):
             a					=tokenizer(__A			,   return_tensors='''tf'''			,   padding='''longest'''						)
             a					=tf_tokenizer(__A						)

             for key in python_outputs.keys():
                 self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape						)						)
                 self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key]			,   tf.intaa						) == tf_outputs[key]						)						)


 @slow
 def 				SCREAMING_SNAKE_CASE							(		self						) ->					str:
     for tf_tokenizer in self.tf_tokenizers:
         a					=tf_tokenizer(self.paired_sentences						)
         a					=tf_tokenizer(
             text=[sentence[0] for sentence in self.paired_sentences]			,   text_pair=[sentence[1] for sentence in self.paired_sentences]			,   )
         for key in merged_outputs.keys():
             self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key]			,   tf.intaa						) == separated_outputs[key]						)						)


 @slow
 def 				SCREAMING_SNAKE_CASE							(		self						) ->					List[str]:
     for tf_tokenizer in self.tf_tokenizers:
         a					=tf.function(__A						)
         for test_inputs in (self.test_sentences, self.paired_sentences):
             a					=tf.constant(__A						)
             a					=compiled_tokenizer(__A						)
             a					=tf_tokenizer(__A						)

             for key in eager_outputs.keys():
                 self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]						)						)





 @slow
 def 				SCREAMING_SNAKE_CASE							(		self						) ->					Tuple:
     for tf_tokenizer in self.tf_tokenizers:
         a					=ModelToSave(tokenizer=__A						)
         a					=tf.convert_to_tensor(self.test_sentences						)
         a					=model(__A						)  # Build model with some sample inputs
         with TemporaryDirectory() as tempdir:
             a					=Path(__A						) / '''saved.model'''
             model.save(__A						)
             a					=tf.keras.models.load_model(__A						)
         a					=loaded_model(__A						)
         # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
         self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output						)						)			,   1E-5						)