




'''simple docstring'''




import logging
import math
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union

import torch

from .tensor_utils import tensor_tree_map, tree_map




def 						UpperCamelCase	(			a			)				->     List[Any]:






     '''simple docstring'''
     __magic_name__						       =    []
     if isinstance(lowerCamelCase__		,						lowerCamelCase__			):
          for v in tree.values():
               shapes.extend(_fetch_dims(lowerCamelCase__			)			)
     elif isinstance(lowerCamelCase__		,						(list, tuple)			):
          for t in tree:
               shapes.extend(_fetch_dims(lowerCamelCase__			)			)
     elif isinstance(lowerCamelCase__		,						torch.Tensor			):
          shapes.append(tree.shape			)
     else:
          raise ValueError('''Not supported'''			)

     return shapes




@torch.jit.ignore
def 						UpperCamelCase	(			a		,						a			)				->     Optional[Any]:






     '''simple docstring'''
     __magic_name__						       =    []
     for d in reversed(lowerCamelCase__			):
          idx.append(flat_idx % d			)
          __magic_name__						       =    flat_idx // d

     return tuple(reversed(lowerCamelCase__			)			)




@torch.jit.ignore
def 						UpperCamelCase	(			a		,						a		,						a		,						a = None		,						a = None		,						)				->     str:






     '''simple docstring'''

     # start_edges and end_edges both indicate whether, starting from any given
     # dimension, the start/end index is at the top/bottom edge of the
     # corresponding tensor, modeled as a tree
     def reduce_edge_list(a			) -> None:
          __magic_name__						       =    True
          for i in range(len(lowerCamelCase__			)			):
               __magic_name__						       =    -1 * (i + 1)
               l[reversed_idx] &= tally
               __magic_name__						       =    l[reversed_idx]

     if start_edges is None:
          __magic_name__						       =    [s == 0 for s in start]
          reduce_edge_list(lowerCamelCase__			)
     if end_edges is None:
          __magic_name__						       =    [e == (d - 1) for e, d in zip(lowerCamelCase__		,						lowerCamelCase__			)]
          reduce_edge_list(lowerCamelCase__			)

     # Base cases. Either start/end are empty and we're done, or the final,
     # one-dimensional tensor can be simply sliced
     if len(lowerCamelCase__			) == 0:
          return [()]
     elif len(lowerCamelCase__			) == 1:
          return [(slice(start[0]		,						end[0] + 1			),)]

     __magic_name__						       =    []
     __magic_name__						       =    []

     # Dimensions common to start and end can be selected directly
     for s, e in zip(lowerCamelCase__		,						lowerCamelCase__			):
          if s == e:
               path_list.append(slice(lowerCamelCase__		,						s + 1			)			)
          else:
               break

     __magic_name__						       =    tuple(lowerCamelCase__			)
     __magic_name__						       =    len(lowerCamelCase__			)

     # start == end, and we're done
     if divergence_idx == len(lowerCamelCase__			):
          return [path]

     def upper() -> Tuple[Tuple[slice, ...], ...]:
          assert start_edges is not None
          assert end_edges is not None

          __magic_name__						       =    start[divergence_idx]
          return tuple(
              path + (slice(lowerCamelCase__		,						sdi + 1			),) + s
              for s in _get_minimal_slice_set(
                  start[divergence_idx + 1 :]		,						[d - 1 for d in dims[divergence_idx + 1 :]]		,						dims[divergence_idx + 1 :]		,						start_edges=start_edges[divergence_idx + 1 :]		,						end_edges=[True for _ in end_edges[divergence_idx + 1 :]]		,						)			)

     def lower() -> Tuple[Tuple[slice, ...], ...]:
          assert start_edges is not None
          assert end_edges is not None

          __magic_name__						       =    end[divergence_idx]
          return tuple(
              path + (slice(lowerCamelCase__		,						edi + 1			),) + s
              for s in _get_minimal_slice_set(
                  [0 for _ in start[divergence_idx + 1 :]]		,						end[divergence_idx + 1 :]		,						dims[divergence_idx + 1 :]		,						start_edges=[True for _ in start_edges[divergence_idx + 1 :]]		,						end_edges=end_edges[divergence_idx + 1 :]		,						)			)

     # If both start and end are at the edges of the subtree rooted at
     # divergence_idx, we can just select the whole subtree at once
     if start_edges[divergence_idx] and end_edges[divergence_idx]:
          slices.append(path + (slice(start[divergence_idx]		,						end[divergence_idx] + 1			),)			)
     # If just start is at the edge, we can grab almost all of the subtree,
     # treating only the ragged bottom edge as an edge case
     elif start_edges[divergence_idx]:
          slices.append(path + (slice(start[divergence_idx]		,						end[divergence_idx]			),)			)
          slices.extend(lower()			)
     # Analogous to the previous case, but the top is ragged this time
     elif end_edges[divergence_idx]:
          slices.extend(upper()			)
          slices.append(path + (slice(start[divergence_idx] + 1		,						end[divergence_idx] + 1			),)			)
     # If both sides of the range are ragged, we need to handle both sides
     # separately. If there's contiguous meat in between them, we can index it
     # in one big chunk
     else:
          slices.extend(upper()			)
          __magic_name__						       =    end[divergence_idx] - start[divergence_idx]
          if middle_ground > 1:
               slices.append(path + (slice(start[divergence_idx] + 1		,						end[divergence_idx]			),)			)
          slices.extend(lower()			)

     return slices




@torch.jit.ignore
def 						UpperCamelCase	(			a		,						a		,						a		,						a			)				->     Union[str, Any]:






     '''simple docstring'''
     __magic_name__						       =    t.shape[:no_batch_dims]
     __magic_name__						       =    list(_flat_idx_to_idx(lowerCamelCase__		,						lowerCamelCase__			)			)
     # _get_minimal_slice_set is inclusive
     __magic_name__						       =    list(_flat_idx_to_idx(flat_end - 1		,						lowerCamelCase__			)			)

     # Get an ordered list of slices to perform
     __magic_name__						       =    _get_minimal_slice_set(
         lowerCamelCase__		,						lowerCamelCase__		,						lowerCamelCase__		,						)

     __magic_name__						       =    [t[s] for s in slices]

     return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]			) for s in sliced_tensors]			)




def 						UpperCamelCase	(			a		,						a		,						a		,						a		,						a = False		,						a = None		,						a = False		,						)				->     Optional[Any]:






     '''simple docstring'''
     if not (len(lowerCamelCase__			) > 0):
          raise ValueError('''Must provide at least one input'''			)

     __magic_name__						       =    [shape[:no_batch_dims] for shape in _fetch_dims(lowerCamelCase__			)]
     __magic_name__						       =    tuple([max(lowerCamelCase__			) for s in zip(*lowerCamelCase__			)]			)

     def _prep_inputs(a			) -> torch.Tensor:
          if not low_mem:
               if not sum(t.shape[:no_batch_dims]			) == no_batch_dims:
                    __magic_name__						       =    t.expand(orig_batch_dims + t.shape[no_batch_dims:]			)
               __magic_name__						       =    t.reshape(-1		,						*t.shape[no_batch_dims:]			)
          else:
               __magic_name__						       =    t.expand(orig_batch_dims + t.shape[no_batch_dims:]			)
          return t

     __magic_name__						       =    tensor_tree_map(_prep_inputs		,						lowerCamelCase__			)
     __magic_name__						       =    None
     if _out is not None:
          __magic_name__						       =    tensor_tree_map(lambda a			: t.view([-1] + list(t.shape[no_batch_dims:]			)			)		,						_out			)

     __magic_name__						       =    1
     for d in orig_batch_dims:
          flat_batch_dim *= d

     __magic_name__						       =    flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)

     def _select_chunk(a			) -> torch.Tensor:
          return t[i : i + chunk_size] if t.shape[0] != 1 else t

     __magic_name__						       =    0
     __magic_name__						       =    prepped_outputs
     for _ in range(lowerCamelCase__			):
          # Chunk the input
          if not low_mem:
               __magic_name__						       =    _select_chunk
          else:
               __magic_name__						       =    partial(
                   _chunk_slice		,						flat_start=lowerCamelCase__		,						flat_end=min(lowerCamelCase__		,						i + chunk_size			)		,						no_batch_dims=len(lowerCamelCase__			)		,						)

          __magic_name__						       =    tensor_tree_map(lowerCamelCase__		,						lowerCamelCase__			)

          # Run the layer on the chunk
          __magic_name__						       =    layer(**lowerCamelCase__			)

          # Allocate space for the output
          if out is None:
               __magic_name__						       =    tensor_tree_map(lambda a			: t.new_zeros((flat_batch_dim,) + t.shape[1:]			)		,						lowerCamelCase__			)

          # Put the chunk in its pre-allocated space
          if isinstance(lowerCamelCase__		,						lowerCamelCase__			):

               def assign(a		,						a			) -> None:
                    for k, v in da.items():
                         if isinstance(lowerCamelCase__		,						lowerCamelCase__			):
                              assign(lowerCamelCase__		,						da[k]			)
                         else:
                              if _add_into_out:
                                   v[i : i + chunk_size] += da[k]
                              else:
                                   __magic_name__						       =    da[k]

               assign(lowerCamelCase__		,						lowerCamelCase__			)
          elif isinstance(lowerCamelCase__		,						lowerCamelCase__			):
               for xa, xa in zip(lowerCamelCase__		,						lowerCamelCase__			):
                    if _add_into_out:
                         xa[i : i + chunk_size] += xa
                    else:
                         __magic_name__						       =    xa
          elif isinstance(lowerCamelCase__		,						torch.Tensor			):
               if _add_into_out:
                    out[i : i + chunk_size] += output_chunk
               else:
                    __magic_name__						       =    output_chunk
          else:
               raise ValueError('''Not supported'''			)

          i += chunk_size

     __magic_name__						       =    tensor_tree_map(lambda a			: t.view(orig_batch_dims + t.shape[1:]			)		,						lowerCamelCase__			)

     return out






class   _SCREAMING_SNAKE_CASE   :



 def __init__(   self		:   Any			,				a__		:   Dict = 512			,				):
      __magic_name__						       =    max_chunk_size
      __magic_name__						       =    None
      __magic_name__						       =    None



 def 			snake_case__  (   self		:   List[Any]			,				a__		:   str			,				a__		:   Tuple			,				a__		:   str      ):
      logging.info('''Tuning chunk size...'''      )

      if min_chunk_size >= self.max_chunk_size:
           return min_chunk_size

      __magic_name__						       =    [2**l for l in range(int(math.log(self.max_chunk_size			,				2      )      ) + 1      )]
      __magic_name__						       =    [c for c in candidates if c > min_chunk_size]
      __magic_name__						       =    [min_chunk_size] + candidates
      candidates[-1] += 4

      def test_chunk_size(a__		:   str      ) -> bool:
           try:
                with torch.no_grad():
                     fn(*a__			,				chunk_size=a__      )
                return True
           except RuntimeError:
                return False

      __magic_name__						       =    0
      __magic_name__						       =    len(a__      ) - 1
      while i > min_viable_chunk_size_index:
           __magic_name__						       =    test_chunk_size(candidates[i]      )
           if not viable:
                __magic_name__						       =    (min_viable_chunk_size_index + i) // 2
           else:
                __magic_name__						       =    i
                __magic_name__						       =    (i + len(a__      ) - 1) // 2

      return candidates[min_viable_chunk_size_index]



 def 			snake_case__  (   self		:   List[Any]			,				a__		:   Optional[int]			,				a__		:   Tuple      ):
      __magic_name__						       =    True
      for aa, aa in zip(a__			,				a__      ):
           assert type(a__      ) == type(a__      )
           if isinstance(a__			,				(list, tuple)      ):
                consistent &= self._compare_arg_caches(a__			,				a__      )
           elif isinstance(a__			,				a__      ):
                __magic_name__						       =    [v for _, v in sorted(aa.items()			,				key=lambda a__      : x[0]      )]
                __magic_name__						       =    [v for _, v in sorted(aa.items()			,				key=lambda a__      : x[0]      )]
                consistent &= self._compare_arg_caches(a__			,				a__      )
           else:
                consistent &= aa == aa

      return consistent



 def 			snake_case__  (   self		:   Optional[int]			,				a__		:   Union[str, Any]			,				a__		:   Any			,				a__		:   str			,				):
      __magic_name__						       =    True
      __magic_name__						       =    tree_map(lambda a__      : a.shape if isinstance(a__			,				torch.Tensor      ) else a			,				a__			,				a__      )
      if self.cached_arg_data is not None:
           # If args have changed shape/value, we need to re-tune
           assert len(self.cached_arg_data      ) == len(a__      )
           __magic_name__						       =    self._compare_arg_caches(self.cached_arg_data			,				a__      )
      else:
           # Otherwise, we can reuse the precomputed value
           __magic_name__						       =    False

      if not consistent:
           __magic_name__						       =    self._determine_favorable_chunk_size(
               a__			,				a__			,				a__			,				)
           __magic_name__						       =    arg_data

      assert self.cached_chunk_size is not None

      return self.cached_chunk_size









'''simple docstring'''




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

import datasets
from datasets import logging


_lowerCAmelCase         =						"\\n\n"

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

_lowerCAmelCase         =						"\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   _SCREAMING_SNAKE_CASE   (   datasets.Metric     ):



 def 			snake_case__  (   self		:   Dict      ):
      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		:   Optional[int]			,				a__		:   int			,				a__		:   Dict			,				a__		:   int = 16			,				a__		:   bool = True			,				a__		:   Any=None      ):
      if device is not None:
           assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
           if device == "gpu":
                __magic_name__						       =    '''cuda'''
      else:
           __magic_name__						       =    '''cuda''' if torch.cuda.is_available() else '''cpu'''

      __magic_name__						       =    AutoModelForCausalLM.from_pretrained(a__      )
      __magic_name__						       =    model.to(a__      )

      __magic_name__						       =    AutoTokenizer.from_pretrained(a__      )

      # 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:
           __magic_name__						       =    list(tokenizer.special_tokens_map_extended.values()      )
           # check that the model already has at least one special token defined
           assert (
               len(a__      ) > 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"
           __magic_name__						       =    model.config.max_length - 1
      else:
           __magic_name__						       =    model.config.max_length

      __magic_name__						       =    tokenizer(
          a__			,				add_special_tokens=a__			,				padding=a__			,				truncation=a__			,				max_length=a__			,				return_tensors='''pt'''			,				return_attention_mask=a__			,				).to(a__      )

      __magic_name__						       =    encodings['''input_ids''']
      __magic_name__						       =    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."

      __magic_name__						       =    []
      __magic_name__						       =    CrossEntropyLoss(reduction='''none'''      )

      for start_index in logging.tqdm(range(0			,				len(a__      )			,				a__      )      ):
           __magic_name__						       =    min(start_index + batch_size			,				len(a__      )      )
           __magic_name__						       =    encoded_texts[start_index:end_index]
           __magic_name__						       =    attn_masks[start_index:end_index]

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

           __magic_name__						       =    encoded_batch

           with torch.no_grad():
                __magic_name__						       =    model(a__			,				attention_mask=a__      ).logits

           __magic_name__						       =    out_logits[..., :-1, :].contiguous()
           __magic_name__						       =    labels[..., 1:].contiguous()
           __magic_name__						       =    attn_mask[..., 1:].contiguous()

           __magic_name__						       =    torch.expa(
               (loss_fct(shift_logits.transpose(1			,				2      )			,				a__      ) * shift_attention_mask_batch).sum(1      )
               / shift_attention_mask_batch.sum(1      )      )

           ppls += perplexity_batch.tolist()

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






