





"""simple docstring"""




import logging
import os
import threading
import time


try:
		import warnings
except ImportError:
		a		:					Union[str, Any]	      =     None

try:
		import msvcrt
except ImportError:
		a		:					List[str]	      =     None

try:
		import fcntl
except ImportError:
		a		:					Union[str, Any]	      =     None


# Backward compatibility
# ------------------------------------------------
try:
		TimeoutError
except NameError:
		a		:					str	      =     OSError


# Data
# ------------------------------------------------
a		:					Any	      =     [
    '''Timeout''',
    '''BaseFileLock''',
    '''WindowsFileLock''',
    '''UnixFileLock''',
    '''SoftFileLock''',
    '''FileLock''',
]

a		:					Optional[int]	      =     '''3.0.12'''


a		:					Optional[int]	      =     None






def  _SCREAMING_SNAKE_CASE						(      )					->List[str]:






	'''simple docstring'''






	global _logger
	a :						Dict      =							_logger or logging.getLogger(__name__   )
	return _logger


class 			__UpperCamelCase							(		a__		):






							def __init__(  self ,   lowerCAmelCase__ )      ->					Tuple:
								a :						Optional[int]      =							lock_file
								return None






							def __str__(  self )      ->					List[Any]:
								a :						int      =							f"""The file lock '{self.lock_file}' could not be acquired."""
								return temp


class 			__UpperCamelCase							:






							def __init__(  self ,   lowerCAmelCase__ )      ->					Tuple:
								a :						Dict      =							lock
								return None






							def __enter__(  self )      ->					List[str]:
								return self.lock






							def __exit__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					str:
								self.lock.release()
								return None


class 			__UpperCamelCase							:






							def __init__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__=-1 ,   lowerCAmelCase__=None )      ->					Union[str, Any]:
								a :						Dict      =							max_filename_length if max_filename_length is not None else 255
								# Hash the filename if it's too long
								a :						List[Any]      =							self.hash_filename_if_too_long(lowerCAmelCase__ ,   lowerCAmelCase__ )
								# The path to the lock file.
								a :						str      =							lock_file

								# The file descriptor for the *_lock_file* as it is returned by the
								# os.open() function.
								# This file lock is only NOT None, if the object currently holds the
								# lock.
								a :						Optional[Any]      =							None

								# The default timeout value.
								a :						Any      =							timeout

								# We use this lock primarily for the lock counter.
								a :						int      =							threading.Lock()

								# The lock counter is used for implementing the nested locking
								# mechanism. Whenever the lock is acquired, the counter is increased and
								# the lock is only released, when this value is 0 again.
								a :						Optional[Any]      =							0
								return None






							@property
							def        __a  (  self )      ->					str:
								return self._lock_file






							@property
							def        __a  (  self )      ->					str:
								return self._timeout






							@timeout.setter
							def        __a  (  self ,   lowerCAmelCase__ )      ->					str:
								a :						int      =							float(lowerCAmelCase__ )
								return None






							def        __a  (  self )      ->					Any:
								raise NotImplementedError()






							def        __a  (  self )      ->					Optional[Any]:
								raise NotImplementedError()






							@property
							def        __a  (  self )      ->					List[str]:
								return self._lock_file_fd is not None






							def        __a  (  self ,   lowerCAmelCase__=None ,   lowerCAmelCase__=0.05 )      ->					Optional[int]:
								# Use the default timeout, if no timeout is provided.
								if timeout is None:
									a :						str      =							self.timeout

								# Increment the number right at the beginning.
								# We can still undo it, if something fails.
								with self._thread_lock:
									self._lock_counter += 1

								a :						Dict      =							id(self )
								a :						Optional[int]      =							self._lock_file
								a :						Dict      =							time.time()
								try:
									while True:
										with self._thread_lock:
											if not self.is_locked:
												logger().debug(f"""Attempting to acquire lock {lock_id} on {lock_filename}""" )
												self._acquire()

										if self.is_locked:
											logger().debug(f"""Lock {lock_id} acquired on {lock_filename}""" )
											break
										elif timeout >= 0 and time.time() - start_time > timeout:
											logger().debug(f"""Timeout on acquiring lock {lock_id} on {lock_filename}""" )
											raise Timeout(self._lock_file )
										else:
											logger().debug(
											    f"""Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...""" )
											time.sleep(lowerCAmelCase__ )
								except:  # noqa
									# Something did go wrong, so decrement the counter.
									with self._thread_lock:
										a :						List[Any]      =							max(0 ,   self._lock_counter - 1 )

									raise
								return _Acquire_ReturnProxy(lock=self )






							def        __a  (  self ,   lowerCAmelCase__=False )      ->					List[str]:
								with self._thread_lock:
									if self.is_locked:
										self._lock_counter -= 1

										if self._lock_counter == 0 or force:
											a :						Tuple      =							id(self )
											a :						str      =							self._lock_file

											logger().debug(f"""Attempting to release lock {lock_id} on {lock_filename}""" )
											self._release()
											a :						int      =							0
											logger().debug(f"""Lock {lock_id} released on {lock_filename}""" )

								return None






							def __enter__(  self )      ->					Optional[int]:
								self.acquire()
								return self






							def __exit__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					Tuple:
								self.release()
								return None






							def __del__(  self )      ->					int:
								self.release(force=lowerCAmelCase__ )
								return None






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					str:
								a :						List[str]      =							os.path.basename(lowerCAmelCase__ )
								if len(lowerCAmelCase__ ) > max_length and max_length > 0:
									a :						int      =							os.path.dirname(lowerCAmelCase__ )
									a :						Any      =							str(hash(lowerCAmelCase__ ) )
									a :						Optional[int]      =							filename[: max_length - len(lowerCAmelCase__ ) - 8] + "..." + hashed_filename + ".lock"
									return os.path.join(lowerCAmelCase__ ,   lowerCAmelCase__ )
								else:
									return path


class 			__UpperCamelCase							(		a__		):






							def __init__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__=-1 ,   lowerCAmelCase__=None )      ->					Optional[int]:
								from .file_utils import relative_to_absolute_path

								super().__init__(lowerCAmelCase__ ,   timeout=lowerCAmelCase__ ,   max_filename_length=lowerCAmelCase__ )
								a :						str      =							"\\\\?\\" + relative_to_absolute_path(self.lock_file )






							def        __a  (  self )      ->					Union[str, Any]:
								a :						Optional[Any]      =							os.O_RDWR | os.O_CREAT | os.O_TRUNC

								try:
									a :						Any      =							os.open(self._lock_file ,   lowerCAmelCase__ )
								except OSError:
									pass
								else:
									try:
										msvcrt.locking(lowerCAmelCase__ ,   msvcrt.LK_NBLCK ,   1 )
									except OSError:
										os.close(lowerCAmelCase__ )
									else:
										a :						Optional[int]      =							fd
								return None






							def        __a  (  self )      ->					List[str]:
								a :						int      =							self._lock_file_fd
								a :						Optional[int]      =							None
								msvcrt.locking(lowerCAmelCase__ ,   msvcrt.LK_UNLCK ,   1 )
								os.close(lowerCAmelCase__ )

								try:
									os.remove(self._lock_file )
								# Probably another instance of the application
								# that acquired the file lock.
								except OSError:
									pass
								return None


class 			__UpperCamelCase							(		a__		):






							def __init__(  self ,   lowerCAmelCase__ ,   lowerCAmelCase__=-1 ,   lowerCAmelCase__=None )      ->					str:
								a :						Optional[int]      =							os.statvfs(os.path.dirname(lowerCAmelCase__ ) ).f_namemax
								super().__init__(lowerCAmelCase__ ,   timeout=lowerCAmelCase__ ,   max_filename_length=lowerCAmelCase__ )






							def        __a  (  self )      ->					Tuple:
								a :						Optional[Any]      =							os.O_RDWR | os.O_CREAT | os.O_TRUNC
								a :						str      =							os.open(self._lock_file ,   lowerCAmelCase__ )

								try:
									fcntl.flock(lowerCAmelCase__ ,   fcntl.LOCK_EX | fcntl.LOCK_NB )
								except OSError:
									os.close(lowerCAmelCase__ )
								else:
									a :						Optional[Any]      =							fd
								return None






							def        __a  (  self )      ->					Optional[Any]:
								# Do not remove the lockfile:
								#
								#   https://github.com/benediktschmitt/py-filelock/issues/31
								#   https://stackoverflow.com/questions/17708885/flock-removing-locked-file-without-race-condition
								a :						List[str]      =							self._lock_file_fd
								a :						int      =							None
								fcntl.flock(lowerCAmelCase__ ,   fcntl.LOCK_UN )
								os.close(lowerCAmelCase__ )
								return None


class 			__UpperCamelCase							(		a__		):






							def        __a  (  self )      ->					int:
								a :						str      =							os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
								try:
									a :						Union[str, Any]      =							os.open(self._lock_file ,   lowerCAmelCase__ )
								except OSError:
									pass
								else:
									a :						Any      =							fd
								return None






							def        __a  (  self )      ->					Any:
								os.close(self._lock_file_fd )
								a :						Optional[int]      =							None

								try:
									os.remove(self._lock_file )
								# The file is already deleted and that's what we want.
								except OSError:
									pass
								return None
a		:					int	      =     None

if msvcrt:
		a		:					str	      =     WindowsFileLock
elif fcntl:
		a		:					int	      =     UnixFileLock
else:
		a		:					str	      =     SoftFileLock

		if warnings is not None:
				warnings.warn('''only soft file lock is available''')









"""simple docstring"""




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

import datasets
from datasets import logging


a		:					List[Any]	      =     '''\

'''

a		:					Optional[int]	      =     '''
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
'''

a		:					List[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		):






							def        __a  (  self )      ->					List[Any]:
								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 ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ = 16 ,   lowerCAmelCase__ = True ,   lowerCAmelCase__=None )      ->					Tuple:
								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 :						str      =							"cuda" if torch.cuda.is_available() else "cpu"

								a :						str      =							AutoModelForCausalLM.from_pretrained(lowerCAmelCase__ )
								a :						int      =							model.to(lowerCAmelCase__ )

								a :						str      =							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 :						str      =							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 :						List[Any]      =							model.config.max_length - 1
								else:
									a :						Union[str, Any]      =							model.config.max_length

								a :						Union[str, Any]      =							tokenizer(
								    lowerCAmelCase__ ,   add_special_tokens=lowerCAmelCase__ ,   padding=lowerCAmelCase__ ,   truncation=lowerCAmelCase__ ,   max_length=lowerCAmelCase__ ,   return_tensors="pt" ,   return_attention_mask=lowerCAmelCase__ ,   ).to(lowerCAmelCase__ )

								a :						str      =							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 :						List[Any]      =							[]
								a :						List[Any]      =							CrossEntropyLoss(reduction="none" )

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

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

									a :						Any      =							encoded_batch

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

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

									a :						Dict      =							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__ )}


