






'''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


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

'''

__lowerCamelCase   :					Dict   							=					'''\
MAUVE is a library built on PyTorch and HuggingFace Transformers to measure the gap between neural text and human text with the eponymous MAUVE measure.

MAUVE summarizes both Type I and Type II errors measured softly using Kullback–Leibler (KL) divergences.

For details, see the MAUVE paper: https://arxiv.org/abs/2102.01454 (Neurips, 2021).

This metrics is a wrapper around the official implementation of MAUVE:
https://github.com/krishnap25/mauve
'''

__lowerCamelCase   :					Optional[Any]   							=					'''
Calculates MAUVE scores between two lists of generated text and reference text.
Args:
    predictions: list of generated text to score. Each predictions
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
Optional Args:
    num_buckets: the size of the histogram to quantize P and Q. Options: \'auto\' (default) or an integer
    pca_max_data: the number data points to use for PCA dimensionality reduction prior to clustering. If -1, use all the data. Default -1
    kmeans_explained_var: amount of variance of the data to keep in dimensionality reduction by PCA. Default 0.9
    kmeans_num_redo: number of times to redo k-means clustering (the best objective is kept). Default 5
    kmeans_max_iter: maximum number of k-means iterations. Default 500
    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\'].
    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
    max_text_length: maximum number of tokens to consider. Default 1024
    divergence_curve_discretization_size: Number of points to consider on the divergence curve. Default 25
    mauve_scaling_factor: "c" from the paper. Default 5.
    verbose: If True (default), print running time updates
    seed: random seed to initialize k-means cluster assignments.
Returns:
    mauve: MAUVE score, a number between 0 and 1. Larger values indicate that P and Q are closer,
    frontier_integral: Frontier Integral, a number between 0 and 1. Smaller values indicate that P and Q are closer,
    divergence_curve: a numpy.ndarray of shape (m, 2); plot it with matplotlib to view the divergence curve,
    p_hist: a discrete distribution, which is a quantized version of the text distribution p_text,
    q_hist: same as above, but with q_text.
Examples:

    >>> # faiss segfaults in doctest for some reason, so the .compute call is not tested with doctest
    >>> import datasets
    >>> mauve = datasets.load_metric(\'mauve\')
    >>> predictions = ["hello there", "general kenobi"]
    >>> references = ["hello there", "general kenobi"]
    >>> out = mauve.compute(predictions=predictions, references=references) # doctest: +SKIP
    >>> print(out.mauve) # doctest: +SKIP
    1.0
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION							)
class    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:List[Any]				)				->  int:


										'''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 							_A	(		self			:Dict       ,							lowerCAmelCase__			:Union[str, Any]       ,							lowerCAmelCase__			:Dict       ,							lowerCAmelCase__			:Any=None       ,							lowerCAmelCase__			:List[str]=None       ,							lowerCAmelCase__			:int=None       ,							lowerCAmelCase__			:List[str]=None       ,							lowerCAmelCase__			:int="auto"       ,							lowerCAmelCase__			:Optional[int]=-1       ,							lowerCAmelCase__			:Union[str, Any]=0.9       ,							lowerCAmelCase__			:Any=5       ,							lowerCAmelCase__			:Optional[int]=500       ,							lowerCAmelCase__			:Optional[Any]="gpt2-large"       ,							lowerCAmelCase__			:str=-1       ,							lowerCAmelCase__			:List[str]=1_024       ,							lowerCAmelCase__			:Union[str, Any]=25       ,							lowerCAmelCase__			:Optional[int]=5       ,							lowerCAmelCase__			:Any=True       ,							lowerCAmelCase__			:Dict=25       ,							)				->  Optional[Any]:


										'''simple docstring'''




										snake_case_				:					Optional[Any]   =       compute_mauve(
										    p_text=lowerCAmelCase__       ,							q_text=lowerCAmelCase__       ,							p_features=lowerCAmelCase__       ,							q_features=lowerCAmelCase__       ,							p_tokens=lowerCAmelCase__       ,							q_tokens=lowerCAmelCase__       ,							num_buckets=lowerCAmelCase__       ,							pca_max_data=lowerCAmelCase__       ,							kmeans_explained_var=lowerCAmelCase__       ,							kmeans_num_redo=lowerCAmelCase__       ,							kmeans_max_iter=lowerCAmelCase__       ,							featurize_model_name=lowerCAmelCase__       ,							device_id=lowerCAmelCase__       ,							max_text_length=lowerCAmelCase__       ,							divergence_curve_discretization_size=lowerCAmelCase__       ,							mauve_scaling_factor=lowerCAmelCase__       ,							verbose=lowerCAmelCase__       ,							seed=lowerCAmelCase__       ,							)
										return out












'''simple docstring'''




import os
import sys
import tempfile

import torch

from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=()     ,__magic_name__=None     ,__magic_name__="no"     ,__magic_name__="29500"						)->    Optional[int]:



			"""simple docstring"""



			snake_case_				:					str   =       False
			snake_case_				:					int   =       False
			if any(key.startswith("KAGGLE"						) for key in os.environ.keys()						):
						snake_case_				:					Any   =       True
			elif "IPython" in sys.modules:
						snake_case_				:					Union[str, Any]   =       "google.colab" in str(sys.modules["IPython"].get_ipython()						)

			try:
						snake_case_				:					Any   =       PrecisionType(mixed_precision.lower()						)
			except ValueError:
						raise ValueError(
						    F'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.'''						)

			if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME"     ,__magic_name__						) is not None):
						# TPU launch
						import torch_xla.distributed.xla_multiprocessing as xmp

						if len(AcceleratorState._shared_state						) > 0:
									raise ValueError(
									    "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside "
									    "your training function. Restart your notebook and make sure no cells initializes an "
									    "`Accelerator`."						)
						if num_processes is None:
									snake_case_				:					Tuple   =       8

						snake_case_				:					Optional[int]   =       PrepareForLaunch(__magic_name__     ,distributed_type="TPU"						)
						print(F'''Launching a training on {num_processes} TPU cores.'''						)
						xmp.spawn(__magic_name__     ,args=__magic_name__     ,nprocs=__magic_name__     ,start_method="fork"						)
			elif in_colab:
						# No need for a distributed launch otherwise as it's either CPU or one GPU.
						if torch.cuda.is_available():
									print("Launching training on one GPU."						)
						else:
									print("Launching training on one CPU."						)
						function(*__magic_name__						)
			else:
						if num_processes is None:
									raise ValueError(
									    "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call."						)

						if num_processes > 1:
									# Multi-GPU launch
									from torch.multiprocessing import start_processes
									from torch.multiprocessing.spawn import ProcessRaisedException

									if len(AcceleratorState._shared_state						) > 0:
												raise ValueError(
												    "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized "
												    "inside your training function. Restart your notebook and make sure no cells initializes an "
												    "`Accelerator`."						)

									if torch.cuda.is_initialized():
												raise ValueError(
												    "To launch a multi-GPU training from your notebook, you need to avoid running any instruction "
												    "using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA "
												    "function."						)

									# torch.distributed will expect a few environment variable to be here. We set the ones common to each
									# process here (the other ones will be set be the launcher).
									with patch_environment(
									    world_size=__magic_name__     ,master_addr="127.0.01"     ,master_port=__magic_name__     ,mixed_precision=__magic_name__						):
												snake_case_				:					Optional[int]   =       PrepareForLaunch(__magic_name__     ,distributed_type="MULTI_GPU"						)
												print(F'''Launching training on {num_processes} GPUs.'''						)
												try:
															start_processes(__magic_name__     ,args=__magic_name__     ,nprocs=__magic_name__     ,start_method="fork"						)
												except ProcessRaisedException as e:
															if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
																		raise RuntimeError(
																		    "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. "
																		    "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. "
																		    "Please review your imports and test them when running the `notebook_launcher()` to identify "
																		    "which one is problematic."						) from e

						else:
									# No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
									if is_mps_available():
												snake_case_				:					Any   =       "1"
												print("Launching training on MPS."						)
									elif torch.cuda.is_available():
												print("Launching training on one GPU."						)
									else:
												print("Launching training on CPU."						)
									function(*__magic_name__						)






def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__=()     ,__magic_name__=2						)->    Dict:



			"""simple docstring"""



			from torch.multiprocessing import start_processes

			with tempfile.NamedTemporaryFile() as tmp_file:
						# torch.distributed will expect a few environment variable to be here. We set the ones common to each
						# process here (the other ones will be set be the launcher).
						with patch_environment(
						    world_size=__magic_name__     ,master_addr="127.0.01"     ,master_port="29500"     ,accelerate_mixed_precision="no"     ,accelerate_debug_rdv_file=tmp_file.name     ,accelerate_use_cpu="yes"     ,):
									snake_case_				:					Any   =       PrepareForLaunch(__magic_name__     ,debug=__magic_name__						)
									start_processes(__magic_name__     ,args=__magic_name__     ,nprocs=__magic_name__     ,start_method="fork"						)




