
"""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					:	List[Any]							=		'''
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					:	Union[str, 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 		a_						( datasets.Metric	):







    def      _snake_case					(			self			:       Any     )		->List[str]:






        '''simple docstring'''






        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]     ,					__UpperCamelCase			:       Tuple     ,					__UpperCamelCase			:       List[Any]     ,					__UpperCamelCase			:       int = 16     ,					__UpperCamelCase			:       bool = True     ,					__UpperCamelCase			:       Any=None     )		->Union[str, Any]:






        '''simple docstring'''






        if device is not None:
            assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
            if device == "gpu":
                _UpperCAmelCase          =   """cuda"""
        else:
            _UpperCAmelCase          =   """cuda""" if torch.cuda.is_available() else """cpu"""

        _UpperCAmelCase          =   AutoModelForCausalLM.from_pretrained(__UpperCamelCase     )
        _UpperCAmelCase          =   model.to(__UpperCamelCase     )

        _UpperCAmelCase          =   AutoTokenizer.from_pretrained(__UpperCamelCase     )

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

        _UpperCAmelCase          =   tokenizer(
            __UpperCamelCase     ,					add_special_tokens=__UpperCamelCase     ,					padding=__UpperCamelCase     ,					truncation=__UpperCamelCase     ,					max_length=__UpperCamelCase     ,					return_tensors="""pt"""     ,					return_attention_mask=__UpperCamelCase     ,					).to(__UpperCamelCase     )

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

        _UpperCAmelCase          =   []
        _UpperCAmelCase          =   CrossEntropyLoss(reduction="""none"""     )

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

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

            _UpperCAmelCase          =   encoded_batch

            with torch.no_grad():
                _UpperCAmelCase          =   model(__UpperCamelCase     ,					attention_mask=__UpperCamelCase     ).logits

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

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

            ppls += perplexity_batch.tolist()

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

"""simple docstring"""



import argparse
import os
import re

import packaging.version


a					:	str							=		'''examples/'''
a					:	List[str]							=		{
    '''examples''': (re.compile(r'''^check_min_version\("[^"]+"\)\s*$''', re.MULTILINE), '''check_min_version("VERSION")\n'''),
    '''init''': (re.compile(r'''^__version__\s+=\s+"([^"]+)"\s*$''', re.MULTILINE), '''__version__ = "VERSION"\n'''),
    '''setup''': (re.compile(r'''^(\s*)version\s*=\s*"[^"]+",''', re.MULTILINE), r'''\1version="VERSION",'''),
    '''doc''': (re.compile(r'''^(\s*)release\s*=\s*"[^"]+"$''', re.MULTILINE), '''release = "VERSION"\n'''),
}
a					:	Tuple							=		{
    '''init''': '''src/diffusers/__init__.py''',
    '''setup''': '''setup.py''',
}
a					:	List[str]							=		'''README.md'''


def  _UpperCamelCase	(						_A					,      _A					,      _A      )    ->  Dict:





    """simple docstring"""

    with open(_A					,      """r"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        _UpperCAmelCase          =   f.read()
    _UpperCAmelCase    ,_UpperCAmelCase          =   REPLACE_PATTERNS[pattern]
    _UpperCAmelCase          =   replace.replace("""VERSION"""					,      _A      )
    _UpperCAmelCase          =   re_pattern.sub(_A					,      _A      )
    with open(_A					,      """w"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        f.write(_A      )


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





    """simple docstring"""

    for folder, directories, fnames in os.walk(_A      ):
        # Removing some of the folders with non-actively maintained examples from the walk
        if "research_projects" in directories:
            directories.remove("""research_projects"""      )
        if "legacy" in directories:
            directories.remove("""legacy"""      )
        for fname in fnames:
            if fname.endswith(""".py"""      ):
                update_version_in_file(os.path.join(_A					,      _A      )					,      _A					,      pattern="""examples"""      )


def  _UpperCamelCase	(						_A					,      _A=False      )    ->  int:





    """simple docstring"""

    for pattern, fname in REPLACE_FILES.items():
        update_version_in_file(_A					,      _A					,      _A      )
    if not patch:
        update_version_in_examples(_A      )


def  _UpperCamelCase	(						)    ->  Any:





    """simple docstring"""

    _UpperCAmelCase          =   """🤗 Transformers currently provides the following architectures"""
    _UpperCAmelCase          =   """1. Want to contribute a new model?"""
    with open(_A					,      """r"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        _UpperCAmelCase          =   f.readlines()

    # Find the start of the list.
    _UpperCAmelCase          =   0
    while not lines[start_index].startswith(_start_prompt      ):
        start_index += 1
    start_index += 1

    _UpperCAmelCase          =   start_index
    # Update the lines in the model list.
    while not lines[index].startswith(_end_prompt      ):
        if lines[index].startswith("""1."""      ):
            _UpperCAmelCase          =   lines[index].replace(
                """https://huggingface.co/docs/diffusers/main/model_doc"""					,      """https://huggingface.co/docs/diffusers/model_doc"""					,      )
        index += 1

    with open(_A					,      """w"""					,      encoding="""utf-8"""					,      newline="""\n"""      ) as f:
        f.writelines(_A      )


def  _UpperCamelCase	(						)    ->  Optional[int]:





    """simple docstring"""

    with open(REPLACE_FILES["""init"""]					,      """r"""      ) as f:
        _UpperCAmelCase          =   f.read()
    _UpperCAmelCase          =   REPLACE_PATTERNS["""init"""][0].search(_A      ).groups()[0]
    return packaging.version.parse(_A      )


def  _UpperCamelCase	(						_A=False      )    ->  List[Any]:





    """simple docstring"""

    _UpperCAmelCase          =   get_version()
    if patch and default_version.is_devrelease:
        raise ValueError("""Can't create a patch version from the dev branch, checkout a released version!"""      )
    if default_version.is_devrelease:
        _UpperCAmelCase          =   default_version.base_version
    elif patch:
        _UpperCAmelCase          =   F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}"""
    else:
        _UpperCAmelCase          =   F"""{default_version.major}.{default_version.minor + 1}.0"""

    # Now let's ask nicely if that's the right one.
    _UpperCAmelCase          =   input(F"""Which version are you releasing? [{default_version}]"""      )
    if len(_A      ) == 0:
        _UpperCAmelCase          =   default_version

    print(F"""Updating version to {version}."""      )
    global_version_update(_A					,      patch=_A      )


def  _UpperCamelCase	(						)    ->  List[Any]:





    """simple docstring"""

    _UpperCAmelCase          =   get_version()
    _UpperCAmelCase          =   F"""{current_version.major}.{current_version.minor + 1}.0.dev0"""
    _UpperCAmelCase          =   current_version.base_version

    # Check with the user we got that right.
    _UpperCAmelCase          =   input(F"""Which version are we developing now? [{dev_version}]"""      )
    if len(_A      ) == 0:
        _UpperCAmelCase          =   dev_version

    print(F"""Updating version to {version}."""      )
    global_version_update(_A      )


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
 a					:	Dict							=		argparse.ArgumentParser()
 parser.add_argument('''--post_release''', action='''store_true''', help='''Whether this is pre or post release.''')
 parser.add_argument('''--patch''', action='''store_true''', help='''Whether or not this is a patch release.''')
 a					:	Tuple							=		parser.parse_args()
 if not args.post_release:
  pre_release_work(patch=args.patch)
 elif args.patch:
  print('''Nothing to do after a patch :-)''')
 else:
  post_release_work()