




'''simple docstring'''







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

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

SCREAMING_SNAKE_CASE_      =			"\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 __a						(					self     :							List[Any]						):





       '''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 __a						(					self     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							Optional[int]				,							SCREAMING_SNAKE_CASE__     :							Any				,							SCREAMING_SNAKE_CASE__     :							int = 1_6				,							SCREAMING_SNAKE_CASE__     :							bool = True				,							SCREAMING_SNAKE_CASE__     :							Optional[int]=None						):





       '''simple docstring'''

       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(lowerCAmelCase_						)
       __a       =   model.to(lowerCAmelCase_						)

       __a       =   AutoTokenizer.from_pretrained(lowerCAmelCase_						)

       # 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(lowerCAmelCase_						) > 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(
           lowerCAmelCase_				,							add_special_tokens=lowerCAmelCase_				,							padding=lowerCAmelCase_				,							truncation=lowerCAmelCase_				,							max_length=lowerCAmelCase_				,							return_tensors="""pt"""				,							return_attention_mask=lowerCAmelCase_				,							).to(lowerCAmelCase_						)

       __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(lowerCAmelCase_						)				,							lowerCAmelCase_						)						):
            __a       =   min(start_index + batch_size				,							len(lowerCAmelCase_						)						)
            __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(lowerCAmelCase_						)
                 __a       =   torch.cat([bos_tokens_tensor, encoded_batch]				,							dim=1						)
                 __a       =   torch.cat(
                     [torch.ones(bos_tokens_tensor.size()				,							dtype=torch.intaa						).to(lowerCAmelCase_						), attn_mask]				,							dim=1						)

            __a       =   encoded_batch

            with torch.no_grad():
                 __a       =   model(lowerCAmelCase_				,							attention_mask=lowerCAmelCase_						).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						)				,							lowerCAmelCase_						) * shift_attention_mask_batch).sum(1						)
                / shift_attention_mask_batch.sum(1						)						)

            ppls += perplexity_batch.tolist()

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










'''simple docstring'''







import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
SCREAMING_SNAKE_CASE_      =			{'LayoutLMv2Config', 'LayoutLMv3Config'}


@is_pipeline_test
class  lowerCAmelCase_						(       unittest.TestCase      ):





  """simple docstring"""



  a_       :List[Any]												=MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
  a_       :List[Any]												=TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

  if model_mapping is not None:
    a_       :List[Any]												={config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
  if tf_model_mapping is not None:
    a_       :Tuple												={
        config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
    }

  @require_torch
  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   pipeline(
           task="""text-classification"""				,							model="""hf-internal-testing/tiny-random-distilbert"""				,							framework="""pt"""						)

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       __a       =   text_classifier("""This is great !"""				,							top_k=2						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}]						)

       __a       =   text_classifier(["""This is great !""", """This is bad"""]				,							top_k=2						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
           ]				,							)

       __a       =   text_classifier("""This is great !"""				,							top_k=1						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       # Legacy behavior
       __a       =   text_classifier("""This is great !"""				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

       __a       =   text_classifier("""This is great !"""				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[[{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}]]						)

       __a       =   text_classifier(["""This is great !""", """Something else"""]				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
               [{"""label""": """LABEL_0""", """score""": 0.5_0_4}, {"""label""": """LABEL_1""", """score""": 0.4_9_6}],
           ]				,							)

       __a       =   text_classifier(["""This is great !""", """Something else"""]				,							return_all_scores=SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[
               {"""label""": """LABEL_0""", """score""": 0.5_0_4},
               {"""label""": """LABEL_0""", """score""": 0.5_0_4},
           ]				,							)

  @require_torch
  def __a						(					self     :							Optional[int]						):





       '''simple docstring'''

       import torch

       __a       =   pipeline(
           task="""text-classification"""				,							model="""hf-internal-testing/tiny-random-distilbert"""				,							framework="""pt"""				,							device=torch.device("""cpu"""						)				,							)

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

  @require_tf
  def __a						(					self     :							List[str]						):





       '''simple docstring'''

       __a       =   pipeline(
           task="""text-classification"""				,							model="""hf-internal-testing/tiny-random-distilbert"""				,							framework="""tf"""						)

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """LABEL_0""", """score""": 0.5_0_4}]						)

  @slow
  @require_torch
  def __a						(					self     :							int						):





       '''simple docstring'''

       __a       =   pipeline("""text-classification"""						)

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """POSITIVE""", """score""": 1.0}]						)
       __a       =   text_classifier("""This is bad !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """NEGATIVE""", """score""": 1.0}]						)
       __a       =   text_classifier("""Birds are a type of animal"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """POSITIVE""", """score""": 0.9_8_8}]						)

  @slow
  @require_tf
  def __a						(					self     :							Union[str, Any]						):





       '''simple docstring'''

       __a       =   pipeline("""text-classification"""				,							framework="""tf"""						)

       __a       =   text_classifier("""This is great !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """POSITIVE""", """score""": 1.0}]						)
       __a       =   text_classifier("""This is bad !"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """NEGATIVE""", """score""": 1.0}]						)
       __a       =   text_classifier("""Birds are a type of animal"""						)
       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": """POSITIVE""", """score""": 0.9_8_8}]						)

  def __a						(					self     :							Tuple				,							SCREAMING_SNAKE_CASE__     :							int				,							SCREAMING_SNAKE_CASE__     :							str				,							SCREAMING_SNAKE_CASE__     :							Tuple						):





       '''simple docstring'''

       __a       =   TextClassificationPipeline(model=SCREAMING_SNAKE_CASE__				,							tokenizer=SCREAMING_SNAKE_CASE__						)
       return text_classifier, ["HuggingFace is in", "This is another test"]


  def __a						(					self     :							Any				,							SCREAMING_SNAKE_CASE__     :							Any				,							SCREAMING_SNAKE_CASE__     :							Tuple						):





       '''simple docstring'''

       __a       =   text_classifier.model
       # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
       __a       =   """HuggingFace is in"""
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__						)

       self.assertEqual(nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}]						)
       self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()						)

       __a       =   ["""HuggingFace is in """, """Paris is in France"""]
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}, {"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}]				,							)
       self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()						)
       self.assertTrue(outputs[1]["""label"""] in model.config.idalabel.values()						)

       # Forcing to get all results with `top_k=None`
       # This is NOT the legacy format
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__				,							top_k=SCREAMING_SNAKE_CASE__						)
       __a       =   len(model.config.idalabel.values()						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}] * N, [{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}] * N]				,							)

       __a       =   {"""text""": """HuggingFace is in """, """text_pair""": """Paris is in France"""}
       __a       =   text_classifier(SCREAMING_SNAKE_CASE__						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}				,							)
       self.assertTrue(outputs["""label"""] in model.config.idalabel.values()						)

       # This might be used a text pair, but tokenizer + pipe interaction
       # makes it hard to understand that it's not using the pair properly
       # https://github.com/huggingface/transformers/issues/17305
       # We disabled this usage instead as it was outputting wrong outputs.
       __a       =   [["""HuggingFace is in """, """Paris is in France"""]]
       with self.assertRaises(SCREAMING_SNAKE_CASE__						):
            text_classifier(SCREAMING_SNAKE_CASE__						)

       # This used to be valid for doing text pairs
       # We're keeping it working because of backward compatibility
       __a       =   text_classifier([[["""HuggingFace is in """, """Paris is in France"""]]]						)
       self.assertEqual(
           nested_simplify(SCREAMING_SNAKE_CASE__						)				,							[{"""label""": ANY(SCREAMING_SNAKE_CASE__						), """score""": ANY(SCREAMING_SNAKE_CASE__						)}]				,							)
       self.assertTrue(outputs[0]["""label"""] in model.config.idalabel.values()						)






