




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

import datasets
from datasets import logging


_lowerCamelCase	:		List[str]							       =   """\

"""

_lowerCamelCase	:		List[Any]							       =   """
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	:		Any							       =   """
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        SCREAMING_SNAKE_CASE							(			self      :	Tuple)						->Dict:





           '''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      :	Optional[Any]					, UpperCAmelCase__      :	Optional[int]					, UpperCAmelCase__      :	Any					, UpperCAmelCase__      :	int = 16					, UpperCAmelCase__      :	bool = True					, UpperCAmelCase__      :	Optional[Any]=None)						->int:





           '''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(UpperCAmelCase__)
           A__       =    model.to(UpperCAmelCase__)

           A__       =    AutoTokenizer.from_pretrained(UpperCAmelCase__)

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

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

                  A__       =    encoded_batch

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

                  ppls += perplexity_batch.tolist()

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







import json
import os
from pathlib import Path

import pytest

from datasets.download.download_config import DownloadConfig
from datasets.download.download_manager import DownloadManager
from datasets.utils.file_utils import hash_url_to_filename


A__								=						'''http://www.mocksite.com/file1.txt'''
A__								=						'''"text": ["foo", "foo"]'''
A__								=						'''6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8'''


class       a							:
		__lowerCAmelCase	:    Optional[int]											=					2_00
		__lowerCAmelCase	:    List[str]											=					{"""Content-Length""": """100"""}
		__lowerCAmelCase	:    Dict											=					{}



		def 	__lowerCamelCase			(     self     :Dict   ,**__lowercase     :List[Any]  ):
						return [bytes(__lowercase   ,'''utf-8'''  )]



def 			_lowerCAmelCase       (					*__lowerCAmelCase  ,  **__lowerCAmelCase      )   ->					Optional[Any]:


				"""simple docstring"""

				return MockResponse()



@pytest.mark.parametrize('''urls_type'''  ,  [str, list, dict]      )
def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase      )   ->					List[str]:


				"""simple docstring"""

				import requests

				monkeypatch.setattr(__lowerCAmelCase  ,  '''request'''  ,  __lowerCAmelCase      )

				snake_case__	:      Union[str, Any]     		=	URL
				if issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      Optional[Any]     		=	url
				elif issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      int     		=	[url]
				elif issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      int     		=	{'''train''': url}
				snake_case__	:      Dict     		=	'''dummy'''
				snake_case__	:      Any     		=	'''downloads'''
				snake_case__	:      int     		=	tmp_path
				snake_case__	:      Any     		=	DownloadConfig(
				    cache_dir=os.path.join(__lowerCAmelCase  ,  __lowerCAmelCase      )  ,  use_etag=__lowerCAmelCase  ,  )
				snake_case__	:      Tuple     		=	DownloadManager(dataset_name=__lowerCAmelCase  ,  download_config=__lowerCAmelCase      )
				snake_case__	:      List[Any]     		=	dl_manager.download(__lowerCAmelCase      )
				snake_case__	:      Union[str, Any]     		=	urls
				for downloaded_paths in [downloaded_paths]:
								if isinstance(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												snake_case__	:      Optional[int]     		=	[downloaded_paths]
												snake_case__	:      Dict     		=	[urls]
								elif isinstance(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												assert "train" in downloaded_paths.keys()
												snake_case__	:      str     		=	downloaded_paths.values()
												snake_case__	:      List[str]     		=	urls.values()
								assert downloaded_paths
								for downloaded_path, input_url in zip(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												assert downloaded_path == dl_manager.downloaded_paths[input_url]
												snake_case__	:      List[Any]     		=	Path(__lowerCAmelCase      )
												snake_case__	:      Any     		=	downloaded_path.parts
												assert parts[-1] == HASH
												assert parts[-2] == cache_subdir
												assert downloaded_path.exists()
												snake_case__	:      List[str]     		=	downloaded_path.read_text()
												assert content == CONTENT
												snake_case__	:      List[str]     		=	downloaded_path.with_suffix('''.json'''      )
												assert metadata_downloaded_path.exists()
												snake_case__	:      str     		=	json.loads(metadata_downloaded_path.read_text()      )
												assert metadata_content == {"url": URL, "etag": None}



@pytest.mark.parametrize('''paths_type'''  ,  [str, list, dict]      )
def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase  ,  __lowerCAmelCase      )   ->					Any:


				"""simple docstring"""

				snake_case__	:      Any     		=	str(__lowerCAmelCase      )
				if issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      Tuple     		=	filename
				elif issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      Dict     		=	[filename]
				elif issubclass(__lowerCAmelCase  ,  __lowerCAmelCase      ):
								snake_case__	:      Dict     		=	{'''train''': filename}
				snake_case__	:      Any     		=	'''dummy'''
				snake_case__	:      Any     		=	xz_file.parent
				snake_case__	:      List[str]     		=	'''extracted'''
				snake_case__	:      Dict     		=	DownloadConfig(
				    cache_dir=__lowerCAmelCase  ,  use_etag=__lowerCAmelCase  ,  )
				snake_case__	:      Dict     		=	DownloadManager(dataset_name=__lowerCAmelCase  ,  download_config=__lowerCAmelCase      )
				snake_case__	:      str     		=	dl_manager.extract(__lowerCAmelCase      )
				snake_case__	:      int     		=	paths
				for extracted_paths in [extracted_paths]:
								if isinstance(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												snake_case__	:      Dict     		=	[extracted_paths]
												snake_case__	:      Optional[Any]     		=	[paths]
								elif isinstance(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												assert "train" in extracted_paths.keys()
												snake_case__	:      int     		=	extracted_paths.values()
												snake_case__	:      int     		=	paths.values()
								assert extracted_paths
								for extracted_path, input_path in zip(__lowerCAmelCase  ,  __lowerCAmelCase      ):
												assert extracted_path == dl_manager.extracted_paths[input_path]
												snake_case__	:      Optional[int]     		=	Path(__lowerCAmelCase      )
												snake_case__	:      int     		=	extracted_path.parts
												assert parts[-1] == hash_url_to_filename(__lowerCAmelCase  ,  etag=__lowerCAmelCase      )
												assert parts[-2] == extracted_subdir
												assert extracted_path.exists()
												snake_case__	:      List[Any]     		=	extracted_path.read_text()
												snake_case__	:      List[str]     		=	text_file.read_text()
												assert extracted_file_content == expected_file_content



def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase      )   ->					List[Any]:


				"""simple docstring"""

				assert path.endswith('''.jsonl'''      )
				for num_items, line in enumerate(__lowerCAmelCase  ,  start=1      ):
								snake_case__	:      Any     		=	json.loads(line.decode('''utf-8'''      )      )
								assert item.keys() == {"col_1", "col_2", "col_3"}
				assert num_items == 4



@pytest.mark.parametrize('''archive_jsonl'''  ,  ['''tar_jsonl_path''', '''zip_jsonl_path''']      )
def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase      )   ->					Union[str, Any]:


				"""simple docstring"""

				snake_case__	:      Any     		=	request.getfixturevalue(__lowerCAmelCase      )
				snake_case__	:      Union[str, Any]     		=	DownloadManager()
				for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(__lowerCAmelCase      )  ,  start=1      ):
								_test_jsonl(__lowerCAmelCase  ,  __lowerCAmelCase      )
				assert num_jsonl == 2



@pytest.mark.parametrize('''archive_nested_jsonl'''  ,  ['''tar_nested_jsonl_path''', '''zip_nested_jsonl_path''']      )
def 			_lowerCAmelCase       (					__lowerCAmelCase  ,  __lowerCAmelCase      )   ->					List[str]:


				"""simple docstring"""

				snake_case__	:      Union[str, Any]     		=	request.getfixturevalue(__lowerCAmelCase      )
				snake_case__	:      Optional[int]     		=	DownloadManager()
				for num_tar, (path, file) in enumerate(dl_manager.iter_archive(__lowerCAmelCase      )  ,  start=1      ):
								for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(__lowerCAmelCase      )  ,  start=1      ):
												_test_jsonl(__lowerCAmelCase  ,  __lowerCAmelCase      )
				assert num_tar == 1
				assert num_jsonl == 2





def 			_lowerCAmelCase       (					__lowerCAmelCase      )   ->					str:


				"""simple docstring"""

				snake_case__	:      Any     		=	DownloadManager()
				for num_file, file in enumerate(dl_manager.iter_files(__lowerCAmelCase      )  ,  start=1      ):
								assert os.path.basename(__lowerCAmelCase      ) == ("test.txt" if num_file == 1 else "train.txt")
				assert num_file == 2

