'''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 _SCREAMING_SNAKE_CASE(							datasets.Metric					):




						def      __lowerCamelCase       (    self :       List[str]      )     ->				Tuple:
													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      __lowerCamelCase       (    self :       Optional[int]							,							UpperCamelCase_ :       Union[str, Any]							,							UpperCamelCase_ :       Optional[int]							,							UpperCamelCase_ :       int = 16							,							UpperCamelCase_ :       bool = True							,							UpperCamelCase_ :       List[str]=None      )     ->				Tuple:







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

													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = AutoModelForCausalLM.from_pretrained(UpperCamelCase_      )
													SCREAMING_SNAKE_CASE__     :Dict						    = model.to(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :int						    = 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:
																				SCREAMING_SNAKE_CASE__     :List[Any]						    = 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"
																				SCREAMING_SNAKE_CASE__     :str						    = model.config.max_length - 1
													else:
																				SCREAMING_SNAKE_CASE__     :str						    = model.config.max_length

													SCREAMING_SNAKE_CASE__     :Any						    = tokenizer(
													    UpperCamelCase_							,							add_special_tokens=UpperCamelCase_							,							padding=UpperCamelCase_							,							truncation=UpperCamelCase_							,							max_length=UpperCamelCase_							,							return_tensors='pt'							,							return_attention_mask=UpperCamelCase_							,							).to(UpperCamelCase_      )

													SCREAMING_SNAKE_CASE__     :List[str]						    = encodings["""input_ids"""]
													SCREAMING_SNAKE_CASE__     :List[Any]						    = 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."

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = []
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = CrossEntropyLoss(reduction='none'      )

													for start_index in logging.tqdm(range(0							,							len(UpperCamelCase_      )							,							UpperCamelCase_      )      ):
																				SCREAMING_SNAKE_CASE__     :int						    = min(start_index + batch_size							,							len(UpperCamelCase_      )      )
																				SCREAMING_SNAKE_CASE__     :Dict						    = encoded_texts[start_index:end_index]
																				SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = attn_masks[start_index:end_index]

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

																				SCREAMING_SNAKE_CASE__     :Tuple						    = encoded_batch

																				with torch.no_grad():
																											SCREAMING_SNAKE_CASE__     :Optional[Any]						    = model(UpperCamelCase_							,							attention_mask=UpperCamelCase_      ).logits

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

																				SCREAMING_SNAKE_CASE__     :Dict						    = 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 warnings
from typing import Dict, List, Optional, Tuple

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


a__		     =     logging.get_logger(__name__)


class    SCREAMING_SNAKE_CASE_				(       _UpperCamelCase   ):



	"""simple docstring"""


	__magic_name__   :       int      	=		['input_ids', 'attention_mask']






	def __init__(					self		:						List[Any]					,     lowerCAmelCase		:						Union[str, Any]="</s>"					,     lowerCAmelCase		:						Tuple="<unk>"					,     lowerCAmelCase		:						Union[str, Any]="<pad>"					,     lowerCAmelCase		:						Tuple=125					,     lowerCAmelCase		:						str=None					,     **lowerCAmelCase		:						Optional[Any]					,     )	->       None:







						"""simple docstring"""







						if extra_ids > 0 and additional_special_tokens is None:
											__UpperCamelCase					:	str             =      [F'''<extra_id_{i}>''' for i in range(lowerCAmelCase	)]
						elif extra_ids > 0 and additional_special_tokens is not None:
											# Check that we have the right number of extra_id special tokens
											__UpperCamelCase					:	Tuple             =      len(set(filter(lambda lowerCAmelCase	: bool("""extra_id""" in str(lowerCAmelCase	)	)					,     lowerCAmelCase	)	)	)
											if extra_tokens != extra_ids:
																raise ValueError(
																    F'''Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are'''
																    """ provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"""
																    """ extra_ids tokens"""	)

						__UpperCamelCase					:	Tuple             =      AddedToken(lowerCAmelCase					,     lstrip=lowerCAmelCase					,     rstrip=lowerCAmelCase	) if isinstance(lowerCAmelCase					,     lowerCAmelCase	) else pad_token
						__UpperCamelCase					:	Tuple             =      AddedToken(lowerCAmelCase					,     lstrip=lowerCAmelCase					,     rstrip=lowerCAmelCase	) if isinstance(lowerCAmelCase					,     lowerCAmelCase	) else eos_token
						__UpperCamelCase					:	int             =      AddedToken(lowerCAmelCase					,     lstrip=lowerCAmelCase					,     rstrip=lowerCAmelCase	) if isinstance(lowerCAmelCase					,     lowerCAmelCase	) else unk_token

						super().__init__(
						    eos_token=lowerCAmelCase					,     unk_token=lowerCAmelCase					,     pad_token=lowerCAmelCase					,     extra_ids=lowerCAmelCase					,     additional_special_tokens=lowerCAmelCase					,     **lowerCAmelCase					,     )

						__UpperCamelCase					:	Any             =      extra_ids

						__UpperCamelCase					:	List[Any]             =      2**8  # utf is 8 bits

						# define special tokens dict
						__UpperCamelCase					:	Dict[int, str]             =      {
						    self.pad_token: 0,
						    self.eos_token: 1,
						    self.unk_token: 2,
						}
						__UpperCamelCase					:	int             =      len(self.special_tokens_encoder	)
						__UpperCamelCase					:	Tuple             =      len(lowerCAmelCase	)
						for i, token in enumerate(lowerCAmelCase	):
											__UpperCamelCase					:	Optional[int]             =      self.vocab_size + i - n
						__UpperCamelCase					:	Dict[str, int]             =      {v: k for k, v in self.special_tokens_encoder.items()}






	@property
	def 					lowerCamelCase__     (					self		:						Any	)	->       Optional[int]:







						"""simple docstring"""







						return self._utf_vocab_size + self._num_special_tokens + self._extra_ids






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						List[int]					,     lowerCAmelCase		:						Optional[List[int]] = None					,     lowerCAmelCase		:						bool = False	)	->       List[int]:







						"""simple docstring"""







						if already_has_special_tokens:
											return super().get_special_tokens_mask(
											    token_ids_a=lowerCAmelCase					,     token_ids_a=lowerCAmelCase					,     already_has_special_tokens=lowerCAmelCase	)

						# normal case: some special tokens
						if token_ids_a is None:
											return ([0] * len(lowerCAmelCase	)) + [1]
						return ([0] * len(lowerCAmelCase	)) + [1] + ([0] * len(lowerCAmelCase	)) + [1]






	def 					lowerCamelCase__     (					self		:						Tuple					,     lowerCAmelCase		:						List[int]	)	->       List[int]:







						"""simple docstring"""







						if len(lowerCAmelCase	) > 0 and token_ids[-1] == self.eos_token_id:
											warnings.warn(
											    F'''This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated'''
											    """ eos tokens being added."""	)
											return token_ids
						else:
											return token_ids + [self.eos_token_id]






	def 					lowerCamelCase__     (					self		:						List[Any]					,     lowerCAmelCase		:						List[int]					,     lowerCAmelCase		:						Optional[List[int]] = None	)	->       List[int]:







						"""simple docstring"""







						__UpperCamelCase					:	Any             =      [self.eos_token_id]

						if token_ids_a is None:
											return len(token_ids_a + eos	) * [0]
						return len(token_ids_a + eos + token_ids_a + eos	) * [0]






	def 					lowerCamelCase__     (					self		:						List[str]					,     lowerCAmelCase		:						List[int]					,     lowerCAmelCase		:						Optional[List[int]] = None	)	->       List[int]:







						"""simple docstring"""







						__UpperCamelCase					:	List[str]             =      self._add_eos_if_not_present(lowerCAmelCase	)
						if token_ids_a is None:
											return token_ids_a
						else:
											__UpperCamelCase					:	List[Any]             =      self._add_eos_if_not_present(lowerCAmelCase	)
											return token_ids_a + token_ids_a






	def 					lowerCamelCase__     (					self		:						str					,     lowerCAmelCase		:						str	)	->       List[str]:







						"""simple docstring"""







						__UpperCamelCase					:	Optional[int]             =      [chr(lowerCAmelCase	) for i in text.encode("""utf-8"""	)]
						return tokens






	def 					lowerCamelCase__     (					self		:						Union[str, Any]					,     lowerCAmelCase		:						Optional[int]	)	->       int:







						"""simple docstring"""







						if token in self.special_tokens_encoder:
											__UpperCamelCase					:	Dict             =      self.special_tokens_encoder[token]
						elif token in self.added_tokens_encoder:
											__UpperCamelCase					:	Tuple             =      self.added_tokens_encoder[token]
						elif len(lowerCAmelCase	) != 1:
											__UpperCamelCase					:	Dict             =      self.unk_token_id
						else:
											__UpperCamelCase					:	Union[str, Any]             =      ord(lowerCAmelCase	) + self._num_special_tokens
						return token_id






	def 					lowerCamelCase__     (					self		:						Union[str, Any]					,     lowerCAmelCase		:						Dict	)	->       Optional[Any]:







						"""simple docstring"""







						if index in self.special_tokens_decoder:
											__UpperCamelCase					:	str             =      self.special_tokens_decoder[index]
						else:
											__UpperCamelCase					:	Any             =      chr(index - self._num_special_tokens	)
						return token






	def 					lowerCamelCase__     (					self		:						str					,     lowerCAmelCase		:						List[Any]	)	->       List[Any]:







						"""simple docstring"""







						__UpperCamelCase					:	Union[str, Any]             =      b""""""
						for token in tokens:
											if token in self.special_tokens_decoder:
																__UpperCamelCase					:	Optional[Any]             =      self.special_tokens_decoder[token].encode("""utf-8"""	)
											elif token in self.added_tokens_decoder:
																__UpperCamelCase					:	Optional[int]             =      self.special_tokens_decoder[token].encode("""utf-8"""	)
											elif token in self.special_tokens_encoder:
																__UpperCamelCase					:	Tuple             =      token.encode("""utf-8"""	)
											elif token in self.added_tokens_encoder:
																__UpperCamelCase					:	Tuple             =      token.encode("""utf-8"""	)
											else:
																__UpperCamelCase					:	Union[str, Any]             =      bytes([ord(lowerCAmelCase	)]	)
											bstring += tok_string
						__UpperCamelCase					:	Optional[int]             =      bstring.decode("""utf-8"""					,     errors="""ignore"""	)
						return string






	def 					lowerCamelCase__     (					self		:						Optional[int]					,     lowerCAmelCase		:						str					,     lowerCAmelCase		:						Optional[str] = None	)	->       Tuple[str]:







						"""simple docstring"""







						return ()






