



"""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       UpperCamelCase__			(   datasets.Metric      ):

			"""simple docstring"""


			def   snake_case__	(      self		)      ->	Optional[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   snake_case__	(      self						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__						,	SCREAMING_SNAKE_CASE__ = 16						,	SCREAMING_SNAKE_CASE__ = True						,	SCREAMING_SNAKE_CASE__=None		)      ->	List[str]:
				if device is not None:
					assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
					if device == "gpu":
						A__											=					"cuda"
				else:
					A__											=					"cuda" if torch.cuda.is_available() else "cpu"

				A__											=					AutoModelForCausalLM.from_pretrained(SCREAMING_SNAKE_CASE__		)
				A__											=					model.to(SCREAMING_SNAKE_CASE__		)

				A__											=					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:
					A__											=					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"
					A__											=					model.config.max_length - 1
				else:
					A__											=					model.config.max_length

				A__											=					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__		)

				A__											=					encodings["input_ids"]
				A__											=					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__											=					[]
				A__											=					CrossEntropyLoss(reduction="none"		)

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

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

					A__											=					encoded_batch

					with torch.no_grad():
						A__											=					model(SCREAMING_SNAKE_CASE__						,	attention_mask=SCREAMING_SNAKE_CASE__		).logits

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

					A__											=					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__		)}










# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


_lowerCamelCase      :						Optional[Any]							=  """Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine"""







def SCREAMING_SNAKE_CASE							(			)  ->			Dict:



       """simple docstring"""

       A__ 					=       _ask_options(
           '''In which compute environment are you running?'''					,							['''This machine''', '''AWS (Amazon SageMaker)''']					,							_convert_compute_environment					,							)
       if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
              A__ 					=       get_sagemaker_input()
       else:
              A__ 					=       get_cluster_input()
       return config







def SCREAMING_SNAKE_CASE							(			lowercase_=None		)  ->			List[Any]:



       """simple docstring"""

       if subparsers is not None:
              A__ 					=       subparsers.add_parser('''config'''					,							description=lowercase_		)
       else:
              A__ 					=       argparse.ArgumentParser('''Accelerate config command'''					,							description=lowercase_		)

       parser.add_argument(
           '''--config_file'''					,							default=lowercase_					,							help=(
               '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
               '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
               '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
               '''with \'huggingface\'.'''
           )					,							)

       if subparsers is not None:
              parser.set_defaults(func=lowercase_		)
       return parser







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			Any:



       """simple docstring"""

       A__ 					=       get_user_input()
       if args.config_file is not None:
              A__ 					=       args.config_file
       else:
              if not os.path.isdir(lowercase_		):
                     os.makedirs(lowercase_		)
              A__ 					=       default_yaml_config_file

       if config_file.endswith('''.json'''		):
              config.to_json_file(lowercase_		)
       else:
              config.to_yaml_file(lowercase_		)
       print(f"""accelerate configuration saved at {config_file}"""		)







def SCREAMING_SNAKE_CASE							(			)  ->			Union[str, Any]:



       """simple docstring"""

       A__ 					=       config_command_parser()
       A__ 					=       parser.parse_args()
       config_command(lowercase_		)


if __name__ == "__main__":
  main()


