


'''simple docstring'''
import doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
UpperCAmelCase_ :     str								=      pytest.mark.integration


UpperCAmelCase_ :     List[str]								=      {'comet'}
UpperCAmelCase_ :     Optional[int]								=      importlib.util.find_spec('fairseq') is not None

UpperCAmelCase_ :     int								=      {'code_eval'}
UpperCAmelCase_ :     List[Any]								=      os.name == 'nt'

UpperCAmelCase_ :     Tuple								=      {'bertscore', 'frugalscore', 'perplexity'}
UpperCAmelCase_ :     Optional[Any]								=      importlib.util.find_spec('transformers') is not None


def 			_lowercase       (				UpperCamelCase__       :					Optional[Any]			):
 @wraps(UpperCamelCase__			)
 def wrapper(self       :					Union[str, Any],				UpperCamelCase__       :					Union[str, Any]			):
  if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
   self.skipTest('"test requires Fairseq"'			)
  else:
   test_case(self,				UpperCamelCase__			)

 return wrapper


def 			_lowercase       (				UpperCamelCase__       :					str			):
 @wraps(UpperCamelCase__			)
 def wrapper(self       :					Dict,				UpperCamelCase__       :					Union[str, Any]			):
  if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
   self.skipTest('"test requires transformers"'			)
  else:
   test_case(self,				UpperCamelCase__			)

 return wrapper


def 			_lowercase       (				UpperCamelCase__       :					Tuple			):
 @wraps(UpperCamelCase__			)
 def wrapper(self       :					Union[str, Any],				UpperCamelCase__       :					int			):
  if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
   self.skipTest('"test not supported on Windows"'			)
  else:
   test_case(self,				UpperCamelCase__			)

 return wrapper


def 			_lowercase       (				):
 __A  :		Optional[Any]       =			[metric_dir.split(os.sep			)[-2] for metric_dir in glob.glob('./metrics/*/'			)]
 return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished

@parameterized.named_parameters(get_local_metric_names()				)
@for_all_test_methods(
    snake_case_    ,		snake_case_    ,		snake_case_				)
@local
class 						_lowerCamelCase					(    parameterized.TestCase				):




 '''simple docstring'''
 __lowercase				:		Optional[int]    							=						{}
 __lowercase				:		List[str]    							=						None


 @pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'						)
 @pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'						)
 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		int       =			'[...]'
  __A  :		Any       =			importlib.import_module(
      datasets.load.metric_module_factory(os.path.join('metrics'      ,      __lowercase						)						).module_path						)
  __A  :		Dict       =			datasets.load.import_main_class(metric_module.__name__      ,      dataset=__lowercase						)
  # check parameters
  __A  :		Union[str, Any]       =			inspect.signature(metric._compute						).parameters
  self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()						)						)  # no **kwargs
  # run doctest
  with self.patch_intensive_calls(__lowercase      ,      metric_module.__name__						):
   with self.use_local_metrics():
    try:
     __A  :		Optional[int]       =			doctest.testmod(__lowercase      ,      verbose=__lowercase      ,      raise_on_error=__lowercase						)
    except doctest.UnexpectedException as e:
     raise e.exc_info[1]  # raise the exception that doctest caught
  self.assertEqual(results.failed      ,      0						)
  self.assertGreater(results.attempted      ,      1						)


 @slow
 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		str       =			'[...]'
  __A  :		Dict       =			importlib.import_module(
      datasets.load.metric_module_factory(os.path.join('metrics'      ,      __lowercase						)						).module_path						)
  # run doctest
  with self.use_local_metrics():
   __A  :		List[str]       =			doctest.testmod(__lowercase      ,      verbose=__lowercase      ,      raise_on_error=__lowercase						)
  self.assertEqual(results.failed      ,      0						)
  self.assertGreater(results.attempted      ,      1						)


 @contextmanager
 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if metric_name in self.INTENSIVE_CALLS_PATCHER:
   with self.INTENSIVE_CALLS_PATCHER[metric_name](__lowercase						):
    yield
  else:
   yield


 @contextmanager
 def  snake_case__   (      self						):

  """simple docstring"""







  def load_local_metric(__lowercase      ,      *__lowercase      ,      **__lowercase						):
   return load_metric(os.path.join('metrics'      ,      __lowercase						)      ,      *__lowercase      ,      **__lowercase						)

  with patch('datasets.load_metric'						) as mock_load_metric:
   __A  :		List[Any]       =			load_local_metric
   yield







 @classmethod
 def  snake_case__   (      cls      ,      __lowercase						):

  """simple docstring"""







  def wrapper(__lowercase						):
   __A  :		str       =			contextmanager(__lowercase						)
   __A  :		Optional[int]       =			patcher
   return patcher

  return wrapper


@LocalMetricTest.register_intensive_calls_patcher('bleurt'			)
def 			_lowercase       (				UpperCamelCase__       :					List[str]			):
 import tensorflow.compat.va as tf
 from bleurt.score import Predictor

 tf.flags.DEFINE_string('sv',				'',				''			)  # handle pytest cli flags

 class 						_lowerCamelCase					(    snake_case_				):




  '''simple docstring'''


  def  snake_case__   (      self      ,      __lowercase						):

   """simple docstring"""







   assert len(input_dict['input_ids']						) == 2
   return np.array([1.0_3, 1.0_4]						)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
 with patch('bleurt.score._create_predictor'			) as mock_create_predictor:
  __A  :		str       =			MockedPredictor()
  yield


@LocalMetricTest.register_intensive_calls_patcher('bertscore'			)
def 			_lowercase       (				UpperCamelCase__       :					Any			):
 import torch

 def bert_cos_score_idf(UpperCamelCase__       :					Tuple,				UpperCamelCase__       :					Union[str, Any],				*UpperCamelCase__       :					Optional[int],				**UpperCamelCase__       :					int			):
  return torch.tensor([[1.0, 1.0, 1.0]] * len(UpperCamelCase__			)			)

 # mock get_model which is supposed to do download a bert model
 # mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
 with patch('bert_score.scorer.get_model'			), patch(
     'bert_score.scorer.bert_cos_score_idf'			) as mock_bert_cos_score_idf:
  __A  :		Optional[int]       =			bert_cos_score_idf
  yield


@LocalMetricTest.register_intensive_calls_patcher('comet'			)
def 			_lowercase       (				UpperCamelCase__       :					List[str]			):
 def load_from_checkpoint(UpperCamelCase__       :					Tuple			):

  class 						_lowerCamelCase					:




   '''simple docstring'''


   def  snake_case__   (      self      ,      __lowercase      ,      *__lowercase      ,      **__lowercase						):

    """simple docstring"""







    assert len(__lowercase						) == 2
    __A  :		List[str]       =			[0.1_9, 0.9_2]
    return scores, sum(__lowercase						) / len(__lowercase						)


  return Model()

 # mock load_from_checkpoint which is supposed to do download a bert model
 # mock load_from_checkpoint which is supposed to do download a bert model
 with patch('comet.download_model'			) as mock_download_model:
  __A  :		Tuple       =			None
  with patch('comet.load_from_checkpoint'			) as mock_load_from_checkpoint:
   __A  :		int       =			load_from_checkpoint
   yield


def 			_lowercase       (				):
 __A  :		List[Any]       =			load_metric(os.path.join('metrics',				'seqeval'			)			)
 __A  :		int       =			'ERROR'
 __A  :		int       =			f"""Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}"""
 with pytest.raises(UpperCamelCase__,				match=re.escape(UpperCamelCase__			)			):
  metric.compute(predictions=[],				references=[],				scheme=UpperCamelCase__			)










'''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]								=      '\\n\n'

UpperCAmelCase_ :     Tuple								=      '\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'

UpperCAmelCase_ :     str								=      '\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  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  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase = 16      ,      __lowercase = True      ,      __lowercase=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  :		Optional[Any]       =			'cuda'
  else:
   __A  :		Optional[int]       =			'cuda' if torch.cuda.is_available() else 'cpu'

  __A  :		List[Any]       =			AutoModelForCausalLM.from_pretrained(__lowercase						)
  __A  :		Any       =			model.to(__lowercase						)

  __A  :		List[Any]       =			AutoTokenizer.from_pretrained(__lowercase						)

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

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

  __A  :		Union[str, Any]       =			encodings['input_ids']
  __A  :		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."

  __A  :		Union[str, Any]       =			[]
  __A  :		str       =			CrossEntropyLoss(reduction='none'						)

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

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

   __A  :		Tuple       =			encoded_batch

   with torch.no_grad():
    __A  :		List[str]       =			model(__lowercase      ,      attention_mask=__lowercase						).logits

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

   __A  :		Tuple       =			torch.expa(
       (loss_fct(shift_logits.transpose(1      ,      2						)      ,      __lowercase						) * shift_attention_mask_batch).sum(1						)
       / shift_attention_mask_batch.sum(1						)						)

   ppls += perplexity_batch.tolist()

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






