




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	:		Union[str, Any]							       =   """\\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"""

_lowerCamelCase	:		Any							       =   """\\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"""

_lowerCamelCase	:		Union[str, Any]							       =   """\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 				UpperCamelCase_    ( datasets.Metric     ):

    '''simple docstring'''






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





           '''simple docstring'''

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


#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes        # name
# #SBATCH --nodes=2                    # nodes
# #SBATCH --ntasks-per-node=1          # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10           # number of cores per tasks
# #SBATCH --gres=gpu:4                 # number of gpus
# #SBATCH --time 0:05:00               # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out           # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#

import fcntl
import os
import socket

import torch
import torch.distributed as dist






def        __lowerCAmelCase       (*__lowerCAmelCase      ):
		with open(__lowerCAmelCase					,       "r"      ) as fh:
				fcntl.flock(__lowerCAmelCase					,       fcntl.LOCK_EX      )
				try:
						print(*__lowerCAmelCase      )
				finally:
						fcntl.flock(__lowerCAmelCase					,       fcntl.LOCK_UN      )


lowerCamelCase__					=   int(os.environ['LOCAL_RANK'])
torch.cuda.set_device(local_rank)
lowerCamelCase__					=   torch.device('cuda', local_rank)
lowerCamelCase__					=   socket.gethostname()

lowerCamelCase__					=   F'''[{hostname}-{local_rank}]'''

try:
						# test distributed
						dist.init_process_group('nccl')
						dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
						dist.barrier()

						# test cuda is available and can allocate memory
						torch.cuda.is_available()
						torch.ones(1).cuda(local_rank)

						# global rank
						lowerCamelCase__					=   dist.get_rank()
						lowerCamelCase__					=   dist.get_world_size()

						printflock(F'''{gpu} is OK (global rank: {rank}/{world_size})''')

						dist.barrier()
						if rank == 0:
												printflock(F'''pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}''')

except Exception:
						printflock(F'''{gpu} is broken''')
						raise



