

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

"""

_UpperCamelCase		     =    """
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		     =    """
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   ):





        """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 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case = 16			,					snake_case = True			,					snake_case=None   ):





        """simple docstring"""

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

        lowerCAmelCase__   :				Dict 			=				AutoModelForCausalLM.from_pretrained(snake_case   )
        lowerCAmelCase__   :				str 			=				model.to(snake_case   )

        lowerCAmelCase__   :				Union[str, Any] 			=				AutoTokenizer.from_pretrained(snake_case   )

        # 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__   :				Any 			=				list(tokenizer.special_tokens_map_extended.values()   )
         # check that the model already has at least one special token defined
         assert (
             len(snake_case   ) > 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[Any] 			=				model.config.max_length - 1
        else:
         lowerCAmelCase__   :				Optional[Any] 			=				model.config.max_length

        lowerCAmelCase__   :				Any 			=				tokenizer(
            snake_case			,					add_special_tokens=snake_case			,					padding=snake_case			,					truncation=snake_case			,					max_length=snake_case			,					return_tensors="pt"			,					return_attention_mask=snake_case			,					).to(snake_case   )

        lowerCAmelCase__   :				Optional[Any] 			=				encodings["input_ids"]
        lowerCAmelCase__   :				Optional[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__   :				str 			=				[]
        lowerCAmelCase__   :				Any 			=				CrossEntropyLoss(reduction="none"   )

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

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

         lowerCAmelCase__   :				List[str] 			=				encoded_batch

         with torch.no_grad():
          lowerCAmelCase__   :				Optional[int] 			=				model(snake_case			,					attention_mask=snake_case   ).logits

         lowerCAmelCase__   :				str 			=				out_logits[..., :-1, :].contiguous()
         lowerCAmelCase__   :				str 			=				labels[..., 1:].contiguous()
         lowerCAmelCase__   :				Dict 			=				attn_mask[..., 1:].contiguous()

         lowerCAmelCase__   :				Any 			=				torch.expa(
             (loss_fct(shift_logits.transpose(1			,					2   )			,					snake_case   ) * shift_attention_mask_batch).sum(1   )
             / shift_attention_mask_batch.sum(1   )   )

         ppls += perplexity_batch.tolist()

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









"""simple docstring"""

from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_UpperCamelCase		     =    """\
@misc{wu2016googles,
      title={Google's Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
"""

_UpperCamelCase		     =    """\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the 'GLEU score'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score's range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
"""

_UpperCamelCase		     =    """\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    'google_bleu': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.44

    Example 2:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results[\"google_bleu\"], 2))
        0.61

    Example 3:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results[\"google_bleu\"], 2))
        0.53

    Example 4:
        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',
        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',
        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']
        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',
        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',
        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']
        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',
        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',
        ...          'heed', 'the', 'cat', 'commands']
        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',
        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',
        ...          'of', 'the', 'cat']

        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',
        ...         'interested', 'in', 'world', 'history']
        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',
        ...          'because', 'he', 'read', 'the', 'book']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric(\"google_bleu\")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results[\"google_bleu\"], 2))
        0.4
"""






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





       """simple docstring"""


       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        return datasets.MetricInfo(
            description=_DESCRIPTION			,					citation=_CITATION			,					inputs_description=_KWARGS_DESCRIPTION			,					features=datasets.Features(
                {
                    "predictions": datasets.Sequence(datasets.Value("string"			,					id="token"   )			,					id="sequence"   ),
                    "references": datasets.Sequence(
                        datasets.Sequence(datasets.Value("string"			,					id="token"   )			,					id="sequence"   )			,					id="references"   ),
                }   )			,					)






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case = 1			,					snake_case = 4			,					):





        """simple docstring"""

        return {
            "google_bleu": gleu_score.corpus_gleu(
                list_of_references=snake_case			,					hypotheses=snake_case			,					min_len=snake_case			,					max_len=snake_case   )
        }






