





'''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_		:  Optional[Any]		 =						"\\n\n"

A_		:  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"

A_		:  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 					__snake_case  (					datasets.Metric							):






   '''simple docstring'''





   def 		__UpperCamelCase						(							self       ):
    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 		__UpperCamelCase						(							self	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE	,		__SCREAMING_SNAKE_CASE = 1_6	,		__SCREAMING_SNAKE_CASE = True	,		__SCREAMING_SNAKE_CASE=None       ):
    if device is not None:
     assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
     if device == "gpu":
      snake_case__     :					int    =  """cuda"""
    else:
     snake_case__     :					Any    =  """cuda""" if torch.cuda.is_available() else """cpu"""

    snake_case__     :					int    =  AutoModelForCausalLM.from_pretrained(__SCREAMING_SNAKE_CASE       )
    snake_case__     :					Dict    =  model.to(__SCREAMING_SNAKE_CASE       )

    snake_case__     :					List[Any]    =  AutoTokenizer.from_pretrained(__SCREAMING_SNAKE_CASE       )

    # 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:
     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(__SCREAMING_SNAKE_CASE       ) > 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"
     snake_case__     :					Dict    =  model.config.max_length - 1
    else:
     snake_case__     :					List[str]    =  model.config.max_length

    snake_case__     :					str    =  tokenizer(
        __SCREAMING_SNAKE_CASE	,		add_special_tokens=__SCREAMING_SNAKE_CASE	,		padding=__SCREAMING_SNAKE_CASE	,		truncation=__SCREAMING_SNAKE_CASE	,		max_length=__SCREAMING_SNAKE_CASE	,		return_tensors="""pt"""	,		return_attention_mask=__SCREAMING_SNAKE_CASE	,		).to(__SCREAMING_SNAKE_CASE       )

    snake_case__     :					Any    =  encodings["""input_ids"""]
    snake_case__     :					Union[str, 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."

    snake_case__     :					int    =  []
    snake_case__     :					Optional[Any]    =  CrossEntropyLoss(reduction="""none"""       )

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

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

     snake_case__     :					Union[str, Any]    =  encoded_batch

     with torch.no_grad():
      snake_case__     :					Any    =  model(__SCREAMING_SNAKE_CASE	,		attention_mask=__SCREAMING_SNAKE_CASE       ).logits

     snake_case__     :					Optional[Any]    =  out_logits[..., :-1, :].contiguous()
     snake_case__     :					Tuple    =  labels[..., 1:].contiguous()
     snake_case__     :					Tuple    =  attn_mask[..., 1:].contiguous()

     snake_case__     :					Optional[Any]    =  torch.expa(
         (loss_fct(shift_logits.transpose(1	,		2       )	,		__SCREAMING_SNAKE_CASE       ) * shift_attention_mask_batch).sum(1       )
         / shift_attention_mask_batch.sum(1       )       )

     ppls += perplexity_batch.tolist()

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











# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


SCREAMING_SNAKE_CASE__							:      List[str]         =    Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(4_2)

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    {"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

SCREAMING_SNAKE_CASE__							:      Any         =    """zero2"""
SCREAMING_SNAKE_CASE__							:      Dict         =    """zero3"""
SCREAMING_SNAKE_CASE__							:      str         =    [ZEROa, ZEROa]






def    _A	(   lowerCamelCase				,			lowerCamelCase				,			lowerCamelCase ):
   # customize the test name generator function as we want both params to appear in the sub-test
   # name, as by default it shows only the first param
   a__						:    Optional[Any]   		=	parameterized.to_safe_name("_".join(str(lowerCamelCase ) for x in param.args ) )
   return F"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    list(itertools.product(stages, models.keys()))







@slow
@require_deepspeed
@require_torch_gpu
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	Dict:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	str:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      self.run_and_check(
          stage=snake_case       ,      model=snake_case       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )





   def 						_snake_case			(			self       ,      snake_case   )					->	str:
      """simple docstring"""





      pass





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = True       ,      snake_case = True       ,      snake_case = True       ,      )					->	str:
      """simple docstring"""





      a__						:    Tuple   		=	models[model]

      a__						:    int   		=	self.run_trainer(
          stage=snake_case       ,      model_name=snake_case       ,      eval_steps=snake_case       ,      num_train_epochs=1       ,      distributed=snake_case       ,      fpaa=snake_case       ,      )

      self.do_checks(snake_case   )

      return output_dir





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = 1       ,      snake_case = True       ,      snake_case = True       ,      )					->	Optional[Any]:
      """simple docstring"""





      a__						:    str   		=	self.get_auto_remove_tmp_dir("./xxx"       ,      after=snake_case   )
      a__						:    List[Any]   		=	F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(snake_case   )}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

      if fpaa:
         args.extend(["--fp16"]   )

      # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
      # hence the separate config files
      a__						:    str   		=	F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
      a__						:    Dict   		=	[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
      a__						:    Optional[int]   		=	self.get_launcher(snake_case   )

      a__						:    Optional[int]   		=	launcher + script + args + ds_args
      # keep for quick debug
      # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
      execute_subprocess_async(snake_case       ,      env=self.get_env()   )

      return output_dir





   def 						_snake_case			(			self       ,      snake_case=False   )					->	List[Any]:
      """simple docstring"""





      a__						:    Union[str, Any]   		=	min(2       ,      get_gpu_count()   ) if distributed else 1
      return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()

