


"""simple docstring"""
import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test





class        __A       (unittest.TestCase):





							'''simple docstring'''

							@parameterized.expand([(None,), ("""foo.json""",)]    )
							def 						lowerCAmelCase    (			self							: Any						,    UpperCAmelCase_							: Any    )   ->Any:



														"""simple docstring"""



														snake_case_          =						GenerationConfig(
														    do_sample=UpperCAmelCase_						,    temperature=0.7						,    length_penalty=1.0						,    bad_words_ids=[[1, 2, 3], [4, 5]]						,    )
														with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(UpperCAmelCase_						,    config_name=UpperCAmelCase_    )
																					snake_case_          =						GenerationConfig.from_pretrained(UpperCAmelCase_						,    config_name=UpperCAmelCase_    )

														# Checks parameters that were specified
														self.assertEqual(loaded_config.do_sample						,    UpperCAmelCase_    )
														self.assertEqual(loaded_config.temperature						,    0.7    )
														self.assertEqual(loaded_config.length_penalty						,    1.0    )
														self.assertEqual(loaded_config.bad_words_ids						,    [[1, 2, 3], [4, 5]]    )

														# Checks parameters that were not specified (defaults)
														self.assertEqual(loaded_config.top_k						,    50    )
														self.assertEqual(loaded_config.max_length						,    20    )
														self.assertEqual(loaded_config.max_time						,    UpperCAmelCase_    )



							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->Tuple:



														"""simple docstring"""



														snake_case_          =						AutoConfig.from_pretrained("""gpt2"""    )
														snake_case_          =						GenerationConfig.from_model_config(UpperCAmelCase_    )
														snake_case_          =						GenerationConfig()

														# The generation config has loaded a few non-default parameters from the model config
														self.assertNotEqual(UpperCAmelCase_						,    UpperCAmelCase_    )

														# One of those parameters is eos_token_id -- check if it matches
														self.assertNotEqual(generation_config_from_model.eos_token_id						,    default_generation_config.eos_token_id    )
														self.assertEqual(generation_config_from_model.eos_token_id						,    model_config.eos_token_id    )



							def 						lowerCAmelCase    (			self							: str    )   ->Optional[int]:



														"""simple docstring"""



														snake_case_          =						GenerationConfig()
														snake_case_          =						{
														    """max_new_tokens""": 1_024,
														    """foo""": """bar""",
														}
														snake_case_          =						copy.deepcopy(UpperCAmelCase_    )
														snake_case_          =						generation_config.update(**UpperCAmelCase_    )

														# update_kwargs was not modified (no side effects)
														self.assertEqual(UpperCAmelCase_						,    UpperCAmelCase_    )

														# update_kwargs was used to update the config on valid attributes
														self.assertEqual(generation_config.max_new_tokens						,    1_024    )

														# `.update()` returns a dictionary of unused kwargs
														self.assertEqual(UpperCAmelCase_						,    {"""foo""": """bar"""}    )



							def 						lowerCAmelCase    (			self							: Union[str, Any]    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						GenerationConfig()
														snake_case_          =						"""bar"""

														with tempfile.TemporaryDirectory("""test-generation-config"""    ) as tmp_dir:
																					generation_config.save_pretrained(UpperCAmelCase_    )

																					snake_case_          =						GenerationConfig.from_pretrained(UpperCAmelCase_    )
														# update_kwargs was used to update the config on valid attributes
														self.assertEqual(new_config.foo						,    """bar"""    )

														snake_case_          =						GenerationConfig.from_model_config(UpperCAmelCase_    )
														assert not hasattr(UpperCAmelCase_						,    """foo"""    )  # no new kwargs should be initialized if from config



							def 						lowerCAmelCase    (			self							: int    )   ->int:



														"""simple docstring"""



														snake_case_          =						GenerationConfig()
														self.assertEqual(default_config.temperature						,    1.0    )
														self.assertEqual(default_config.do_sample						,    UpperCAmelCase_    )
														self.assertEqual(default_config.num_beams						,    1    )

														snake_case_          =						GenerationConfig(
														    do_sample=UpperCAmelCase_						,    temperature=0.7						,    length_penalty=1.0						,    bad_words_ids=[[1, 2, 3], [4, 5]]						,    )
														self.assertEqual(config.temperature						,    0.7    )
														self.assertEqual(config.do_sample						,    UpperCAmelCase_    )
														self.assertEqual(config.num_beams						,    1    )

														with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(UpperCAmelCase_    )
																					snake_case_          =						GenerationConfig.from_pretrained(UpperCAmelCase_						,    temperature=1.0    )

														self.assertEqual(loaded_config.temperature						,    1.0    )
														self.assertEqual(loaded_config.do_sample						,    UpperCAmelCase_    )
														self.assertEqual(loaded_config.num_beams						,    1    )  # default value





@is_staging_test
class        __A       (unittest.TestCase):





							'''simple docstring'''

							@classmethod
							def 						lowerCAmelCase    (			cls							: List[Any]    )   ->Tuple:



														"""simple docstring"""



														snake_case_          =						TOKEN
														HfFolder.save_token(UpperCAmelCase_    )



							@classmethod
							def 						lowerCAmelCase    (			cls							: str    )   ->List[Any]:



														"""simple docstring"""



														try:
																					delete_repo(token=cls._token						,    repo_id="""test-generation-config"""    )
														except HTTPError:
																					pass

														try:
																					delete_repo(token=cls._token						,    repo_id="""valid_org/test-generation-config-org"""    )
														except HTTPError:
																					pass



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->int:



														"""simple docstring"""



														snake_case_          =						GenerationConfig(
														    do_sample=UpperCAmelCase_						,    temperature=0.7						,    length_penalty=1.0						,    )
														config.push_to_hub("""test-generation-config"""						,    use_auth_token=self._token    )

														snake_case_          =						GenerationConfig.from_pretrained(F"""{USER}/test-generation-config"""    )
														for k, v in config.to_dict().items():
																					if k != "transformers_version":
																												self.assertEqual(UpperCAmelCase_						,    getattr(UpperCAmelCase_						,    UpperCAmelCase_    )    )

        # Reset repo
														delete_repo(token=self._token						,    repo_id="""test-generation-config"""    )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(
																					    UpperCAmelCase_						,    repo_id="""test-generation-config"""						,    push_to_hub=UpperCAmelCase_						,    use_auth_token=self._token    )

														snake_case_          =						GenerationConfig.from_pretrained(F"""{USER}/test-generation-config"""    )
														for k, v in config.to_dict().items():
																					if k != "transformers_version":
																												self.assertEqual(UpperCAmelCase_						,    getattr(UpperCAmelCase_						,    UpperCAmelCase_    )    )



							def 						lowerCAmelCase    (			self							: Optional[int]    )   ->Union[str, Any]:



														"""simple docstring"""



														snake_case_          =						GenerationConfig(
														    do_sample=UpperCAmelCase_						,    temperature=0.7						,    length_penalty=1.0						,    )
														config.push_to_hub("""valid_org/test-generation-config-org"""						,    use_auth_token=self._token    )

														snake_case_          =						GenerationConfig.from_pretrained("""valid_org/test-generation-config-org"""    )
														for k, v in config.to_dict().items():
																					if k != "transformers_version":
																												self.assertEqual(UpperCAmelCase_						,    getattr(UpperCAmelCase_						,    UpperCAmelCase_    )    )

        # Reset repo
														delete_repo(token=self._token						,    repo_id="""valid_org/test-generation-config-org"""    )

														# Push to hub via save_pretrained
														with tempfile.TemporaryDirectory() as tmp_dir:
																					config.save_pretrained(
																					    UpperCAmelCase_						,    repo_id="""valid_org/test-generation-config-org"""						,    push_to_hub=UpperCAmelCase_						,    use_auth_token=self._token    )

														snake_case_          =						GenerationConfig.from_pretrained("""valid_org/test-generation-config-org"""    )
														for k, v in config.to_dict().items():
																					if k != "transformers_version":
																												self.assertEqual(UpperCAmelCase_						,    getattr(UpperCAmelCase_						,    UpperCAmelCase_    )    )







"""simple docstring"""
import faiss  # noqa: F401 # Here to have a nice missing dependency error message early on
import numpy  # noqa: F401 # Here to have a nice missing dependency error message early on
import requests  # noqa: F401 # Here to have a nice missing dependency error message early on
import sklearn  # noqa: F401 # Here to have a nice missing dependency error message early on
import tqdm  # noqa: F401 # Here to have a nice missing dependency error message early on
from mauve import compute_mauve  # From: mauve-text

import datasets


__SCREAMING_SNAKE_CASE							:      Dict						=      '\\n@inproceedings{pillutla-etal:mauve:neurips2021,\n  title={MAUVE: Measuring the Gap Between Neural Text and Human Text using Divergence Frontiers},\n  author={Pillutla, Krishna and Swayamdipta, Swabha and Zellers, Rowan and Thickstun, John and Welleck, Sean and Choi, Yejin and Harchaoui, Zaid},\n  booktitle = {NeurIPS},\n  year      = {2021}\n}\n\n'

__SCREAMING_SNAKE_CASE							:      Optional[int]						=      '\\nMAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.\n\nMAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.\n\nFor details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).\n\nThis metrics is a wrapper around the official implementation of MAUVE:\nhttps://github.com/krishnap25/mauve\n'

__SCREAMING_SNAKE_CASE							:      Tuple						=      '\nCalculates MAUVE scores between two lists of generated text and reference text.\nArgs:\n    predictions: list of generated text to score. Each predictions\n        should be a string with tokens separated by spaces.\n    references: list of reference for each prediction. Each\n        reference should be a string with tokens separated by spaces.\nOptional Args:\n    num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer\n    pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1\n    kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9\n    kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5\n    kmeans_max_iter: maximum number of k-means iterations. Default 500\n    featurize_model_name: name of the model from which features are obtained. Default \'gpt2-large\' Use one of [\'gpt2\', \'gpt2-medium\', \'gpt2-large\', \'gpt2-xl\'].\n    device_id: Device for featurization. Supply a GPU id (e.g. 0 or 3) to use GPU. If no GPU with this id is found, use CPU\n    max_text_length: maximum number of tokens to consider. Default 1024\n    divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25\n    mauve_scaling_factor: "c" from the paper. Default 5.\n    verbose: If True (default), print running time updates\n    seed: random seed to initialize k-means cluster assignments.\nReturns:\n    mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,\n    frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,\n    divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,\n    p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,\n    q_hist: same as above, but with q_text.\nExamples:\n\n    >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest\n    >>> import datasets\n    >>> mauve = datasets.load_metric(\'mauve\')\n    >>> predictions = ["hello there", "general kenobi"]\n    >>> references = ["hello there", "general kenobi"]\n    >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP\n    >>> print(out.mauve) # doctest: +SKIP\n    1.0\n'





@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,						_KWARGS_DESCRIPTION)
class        __A       (datasets.Metric):





							'''simple docstring'''

							def 						lowerCAmelCase    (			self							: Tuple    )   ->Union[str, Any]:



														"""simple docstring"""



														return datasets.MetricInfo(
														    description=_DESCRIPTION						,    citation=_CITATION						,    homepage="""https://github.com/krishnap25/mauve"""						,    inputs_description=_KWARGS_DESCRIPTION						,    features=datasets.Features(
														        {
														            """predictions""": datasets.Value("""string"""						,    id="""sequence"""    ),
														            """references""": datasets.Value("""string"""						,    id="""sequence"""    ),
														        }    )						,    codebase_urls=["""https://github.com/krishnap25/mauve"""]						,    reference_urls=[
														        """https://arxiv.org/abs/2102.01454""",
														        """https://github.com/krishnap25/mauve""",
														    ]						,    )



							def 						lowerCAmelCase    (			self							: Optional[int]						,    UpperCAmelCase_							: Tuple						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: Optional[Any]=None						,    UpperCAmelCase_							: Optional[Any]=None						,    UpperCAmelCase_							: List[Any]=None						,    UpperCAmelCase_							: Any=None						,    UpperCAmelCase_							: int="auto"						,    UpperCAmelCase_							: Dict=-1						,    UpperCAmelCase_							: Optional[Any]=0.9						,    UpperCAmelCase_							: Dict=5						,    UpperCAmelCase_							: Optional[int]=500						,    UpperCAmelCase_							: Any="gpt2-large"						,    UpperCAmelCase_							: Union[str, Any]=-1						,    UpperCAmelCase_							: Optional[Any]=1_024						,    UpperCAmelCase_							: Dict=25						,    UpperCAmelCase_							: Optional[Any]=5						,    UpperCAmelCase_							: int=True						,    UpperCAmelCase_							: Union[str, Any]=25						,    )   ->List[Any]:



														"""simple docstring"""



														snake_case_          =						compute_mauve(
														    p_text=UpperCAmelCase_						,    q_text=UpperCAmelCase_						,    p_features=UpperCAmelCase_						,    q_features=UpperCAmelCase_						,    p_tokens=UpperCAmelCase_						,    q_tokens=UpperCAmelCase_						,    num_buckets=UpperCAmelCase_						,    pca_max_data=UpperCAmelCase_						,    kmeans_explained_var=UpperCAmelCase_						,    kmeans_num_redo=UpperCAmelCase_						,    kmeans_max_iter=UpperCAmelCase_						,    featurize_model_name=UpperCAmelCase_						,    device_id=UpperCAmelCase_						,    max_text_length=UpperCAmelCase_						,    divergence_curve_discretization_size=UpperCAmelCase_						,    mauve_scaling_factor=UpperCAmelCase_						,    verbose=UpperCAmelCase_						,    seed=UpperCAmelCase_						,    )
														return out



