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

UpperCAmelCase_							: Optional[int] =							'\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_							: List[Any] =							'\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 			UpperCAmelCase__    (							datasets.Metric			):



    def 	lowerCamelCase_	(						self   :							Optional[int]  ):
          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   :							List[str],__A   :							Dict,__A   :							List[Any],__A   :							int = 1_6,__A   :							bool = True,__A   :							int=None  ):
          if device is not None:
                assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
                if device == "gpu":
                      _lowerCamelCase					: int		    = "cuda"
          else:
                _lowerCamelCase					: int		    = "cuda" if torch.cuda.is_available() else "cpu"

          _lowerCamelCase					: Union[str, Any]		    = AutoModelForCausalLM.from_pretrained(__A  )
          _lowerCamelCase					: Tuple		    = model.to(__A  )

          _lowerCamelCase					: Union[str, Any]		    = 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:
                _lowerCamelCase					: Tuple		    = 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"
                _lowerCamelCase					: int		    = model.config.max_length - 1
          else:
                _lowerCamelCase					: Tuple		    = model.config.max_length

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

          _lowerCamelCase					: Optional[Any]		    = encodings["input_ids"]
          _lowerCamelCase					: Dict		    = 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."

          _lowerCamelCase					: str		    = []
          _lowerCamelCase					: str		    = CrossEntropyLoss(reduction="none"  )

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

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

                _lowerCamelCase					: Dict		    = encoded_batch

                with torch.no_grad():
                      _lowerCamelCase					: str		    = model(__A,attention_mask=__A  ).logits

                _lowerCamelCase					: List[str]		    = out_logits[..., :-1, :].contiguous()
                _lowerCamelCase					: Optional[int]		    = labels[..., 1:].contiguous()
                _lowerCamelCase					: Dict		    = attn_mask[..., 1:].contiguous()

                _lowerCamelCase					: str		    = 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  )}



import os
import tempfile
import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch


if is_torch_available():
     import torch
     from torch import nn

     from transformers import (
         Adafactor,
         AdamW,
         get_constant_schedule,
         get_constant_schedule_with_warmup,
         get_cosine_schedule_with_warmup,
         get_cosine_with_hard_restarts_schedule_with_warmup,
         get_inverse_sqrt_schedule,
         get_linear_schedule_with_warmup,
         get_polynomial_decay_schedule_with_warmup,
     )
def 							__lowerCamelCase		(					UpperCAmelCase_		:						str					,    UpperCAmelCase_		:						Union[str, Any]=10		):




      """simple docstring"""





      a		:Tuple									=			[]
      for _ in range(UpperCAmelCase_		):
            lrs.append(scheduler.get_lr()[0]		)
            scheduler.step()
      return lrs
def 							__lowerCamelCase		(					UpperCAmelCase_		:						str					,    UpperCAmelCase_		:						Tuple=10		):




      """simple docstring"""





      a		:List[Any]									=			[]
      for step in range(UpperCAmelCase_		):
            lrs.append(scheduler.get_lr()[0]		)
            scheduler.step()
            if step == num_steps // 2:
                  with tempfile.TemporaryDirectory() as tmpdirname:
                        a		:Union[str, Any]									=			os.path.join(UpperCAmelCase_					,    '''schedule.bin'''		)
                        torch.save(scheduler.state_dict()					,    UpperCAmelCase_		)

                        a		:int									=			torch.load(UpperCAmelCase_		)
                        scheduler.load_state_dict(UpperCAmelCase_		)
      return lrs







@require_torch
class 						_snake_case    ( unittest.TestCase				):




 def 			SCREAMING_SNAKE_CASE__							(						self   ,    _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase       ):
       self.assertEqual(len(_lowerCamelCase       )   ,    len(_lowerCamelCase       )       )
       for a, b in zip(_lowerCamelCase   ,    _lowerCamelCase       ):
             self.assertAlmostEqual(_lowerCamelCase   ,    _lowerCamelCase   ,    delta=_lowerCamelCase       )




 def 			SCREAMING_SNAKE_CASE__							(						self       ):
       a		:List[str]									=			torch.tensor([0.1, -0.2, -0.1]   ,    requires_grad=_lowerCamelCase       )
       a		:int									=			torch.tensor([0.4, 0.2, -0.5]       )
       a		:int									=			nn.MSELoss()
       # No warmup, constant schedule, no gradient clipping
       a		:Tuple									=			AdamW(params=[w]   ,    lr=2e-1   ,    weight_decay=0.0       )
       for _ in range(100       ):
             a		:int									=			criterion(_lowerCamelCase   ,    _lowerCamelCase       )
             loss.backward()
             optimizer.step()
             w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
             w.grad.zero_()
       self.assertListAlmostEqual(w.tolist()   ,    [0.4, 0.2, -0.5]   ,    tol=1e-2       )




 def 			SCREAMING_SNAKE_CASE__							(						self       ):
       a		:List[Any]									=			torch.tensor([0.1, -0.2, -0.1]   ,    requires_grad=_lowerCamelCase       )
       a		:Union[str, Any]									=			torch.tensor([0.4, 0.2, -0.5]       )
       a		:List[Any]									=			nn.MSELoss()
       # No warmup, constant schedule, no gradient clipping
       a		:Any									=			Adafactor(
           params=[w]   ,    lr=1e-2   ,    eps=(1e-30, 1e-3)   ,    clip_threshold=1.0   ,    decay_rate=-0.8   ,    betaa=_lowerCamelCase   ,    weight_decay=0.0   ,    relative_step=_lowerCamelCase   ,    scale_parameter=_lowerCamelCase   ,    warmup_init=_lowerCamelCase   ,    )
       for _ in range(1000       ):
             a		:str									=			criterion(_lowerCamelCase   ,    _lowerCamelCase       )
             loss.backward()
             optimizer.step()
             w.grad.detach_()  # No zero_grad() function on simple tensors. we do it ourselves.
             w.grad.zero_()
       self.assertListAlmostEqual(w.tolist()   ,    [0.4, 0.2, -0.5]   ,    tol=1e-2       )







@require_torch
class 						_snake_case    ( unittest.TestCase				):
 SCREAMING_SNAKE_CASE__ =			nn.Linear(50		,       50				) if is_torch_available() else None
 SCREAMING_SNAKE_CASE__ =			AdamW(m.parameters()		,       lr=10.0				) if is_torch_available() else None
 SCREAMING_SNAKE_CASE__ =			10




 def 			SCREAMING_SNAKE_CASE__							(						self   ,    _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase   ,    _lowerCamelCase=None       ):
       self.assertEqual(len(_lowerCamelCase       )   ,    len(_lowerCamelCase       )       )
       for a, b in zip(_lowerCamelCase   ,    _lowerCamelCase       ):
             self.assertAlmostEqual(_lowerCamelCase   ,    _lowerCamelCase   ,    delta=_lowerCamelCase   ,    msg=_lowerCamelCase       )




 def 			SCREAMING_SNAKE_CASE__							(						self       ):
       a		:Union[str, Any]									=			{'''num_warmup_steps''': 2, '''num_training_steps''': 10}
       # schedulers doct format
       # function: (sched_args_dict, expected_learning_rates)
       a		:Any									=			{
           get_constant_schedule: ({}, [10.0] * self.num_steps),
           get_constant_schedule_with_warmup: (
               {'''num_warmup_steps''': 4},
               [0.0, 2.5, 5.0, 7.5, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0],
           ),
           get_linear_schedule_with_warmup: (
               {**common_kwargs},
               [0.0, 5.0, 10.0, 8.75, 7.5, 6.25, 5.0, 3.75, 2.5, 1.25],
           ),
           get_cosine_schedule_with_warmup: (
               {**common_kwargs},
               [0.0, 5.0, 10.0, 9.61, 8.53, 6.91, 5.0, 3.08, 1.46, 0.38],
           ),
           get_cosine_with_hard_restarts_schedule_with_warmup: (
               {**common_kwargs, '''num_cycles''': 2},
               [0.0, 5.0, 10.0, 8.53, 5.0, 1.46, 10.0, 8.53, 5.0, 1.46],
           ),
           get_polynomial_decay_schedule_with_warmup: (
               {**common_kwargs, '''power''': 2.0, '''lr_end''': 1e-7},
               [0.0, 5.0, 10.0, 7.656, 5.625, 3.906, 2.5, 1.406, 0.625, 0.156],
           ),
           get_inverse_sqrt_schedule: (
               {'''num_warmup_steps''': 2},
               [0.0, 5.0, 10.0, 8.165, 7.071, 6.325, 5.774, 5.345, 5.0, 4.714],
           ),
       }

       for scheduler_func, data in scheds.items():
             a				,							a		:List[str]									=			data

             a		:str									=			scheduler_func(self.optimizer   ,    **_lowerCamelCase       )
             self.assertEqual(len([scheduler.get_lr()[0]]       )   ,    1       )
             a		:Optional[Any]									=			unwrap_schedule(_lowerCamelCase   ,    self.num_steps       )
             self.assertListAlmostEqual(
                 _lowerCamelCase   ,    _lowerCamelCase   ,    tol=1e-2   ,    msg=F'''failed for {scheduler_func} in normal scheduler'''   ,    )

             a		:List[Any]									=			scheduler_func(self.optimizer   ,    **_lowerCamelCase       )
             if scheduler_func.__name__ != "get_constant_schedule":
                   LambdaScheduleWrapper.wrap_scheduler(_lowerCamelCase       )  # wrap to test picklability of the schedule
             a		:Dict									=			unwrap_and_save_reload_schedule(_lowerCamelCase   ,    self.num_steps       )
             self.assertListEqual(_lowerCamelCase   ,    _lowerCamelCase   ,    msg=F'''failed for {scheduler_func} in save and reload'''       )







class 						_snake_case    :




 def __init__(						self   ,    _lowerCamelCase       ):
       a		:Dict									=			fn




 def __call__(						self   ,    *_lowerCamelCase   ,    **_lowerCamelCase       ):
       return self.fn(*_lowerCamelCase   ,    **_lowerCamelCase       )




 @classmethod
 def 			SCREAMING_SNAKE_CASE__							(						self   ,    _lowerCamelCase       ):
       a		:str									=			list(map(self   ,    scheduler.lr_lambdas       )       )





