


"""simple docstring"""
import tensorflow as tf

from ...tf_utils import shape_list





class        __A       (tf.keras.layers.Layer):





       '''simple docstring'''

       def __init__(			self							: Tuple						,    UpperCAmelCase_							: List[str]						,    UpperCAmelCase_							: List[Any]						,    UpperCAmelCase_							: str						,    UpperCAmelCase_							: List[Any]						,    UpperCAmelCase_							: Optional[int]=1						,    UpperCAmelCase_							: int=False						,    **UpperCAmelCase_							: Optional[Any]    )   ->List[Any]:



              """simple docstring"""



              super().__init__(**lowerCAmelCase__    )

              snake_case_          =						vocab_size
              snake_case_          =						d_embed
              snake_case_          =						d_proj

              snake_case_          =						cutoffs + [vocab_size]
              snake_case_          =						[0] + self.cutoffs
              snake_case_          =						div_val

              snake_case_          =						self.cutoffs[0]
              snake_case_          =						len(self.cutoffs    ) - 1
              snake_case_          =						self.shortlist_size + self.n_clusters
              snake_case_          =						keep_order

              snake_case_          =						[]
              snake_case_          =						[]



       def 						lowerCAmelCase    (			self							: List[str]						,    UpperCAmelCase_							: List[str]    )   ->Dict:



              """simple docstring"""



              if self.n_clusters > 0:
                     snake_case_          =						self.add_weight(
                         shape=(self.n_clusters, self.d_embed)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name="""cluster_weight"""    )
                     snake_case_          =						self.add_weight(
                         shape=(self.n_clusters,)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name="""cluster_bias"""    )

              if self.div_val == 1:
                     for i in range(len(self.cutoffs    )    ):
                            if self.d_proj != self.d_embed:
                                   snake_case_          =						self.add_weight(
                                       shape=(self.d_embed, self.d_proj)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_projs_._{i}"""						,    )
                                   self.out_projs.append(lowerCAmelCase__    )
                            else:
                                   self.out_projs.append(lowerCAmelCase__    )
                            snake_case_          =						self.add_weight(
                                shape=(self.vocab_size, self.d_embed)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_layers_._{i}_._weight"""						,    )
                            snake_case_          =						self.add_weight(
                                shape=(self.vocab_size,)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_layers_._{i}_._bias"""						,    )
                            self.out_layers.append((weight, bias)    )
              else:
                     for i in range(len(self.cutoffs    )    ):
                            snake_case_    ,  snake_case_          =						self.cutoff_ends[i], self.cutoff_ends[i + 1]
                            snake_case_          =						self.d_embed // (self.div_val**i)

                            snake_case_          =						self.add_weight(
                                shape=(d_emb_i, self.d_proj)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_projs_._{i}"""    )
                            self.out_projs.append(lowerCAmelCase__    )
                            snake_case_          =						self.add_weight(
                                shape=(r_idx - l_idx, d_emb_i)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_layers_._{i}_._weight"""						,    )
                            snake_case_          =						self.add_weight(
                                shape=(r_idx - l_idx,)						,    initializer="""zeros"""						,    trainable=lowerCAmelCase__						,    name=F"""out_layers_._{i}_._bias"""						,    )
                            self.out_layers.append((weight, bias)    )
              super().build(lowerCAmelCase__    )



       @staticmethod
       def 						lowerCAmelCase    (			UpperCAmelCase_							: int						,    UpperCAmelCase_							: Any						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: Optional[int]=None    )   ->Dict:



              """simple docstring"""



              snake_case_          =						x
              if proj is not None:
                     snake_case_          =						tf.einsum("""ibd,ed->ibe"""						,    lowerCAmelCase__						,    lowerCAmelCase__    )
              return tf.einsum("""ibd,nd->ibn"""						,    lowerCAmelCase__						,    lowerCAmelCase__    ) + b



       @staticmethod
       def 						lowerCAmelCase    (			UpperCAmelCase_							: Optional[int]						,    UpperCAmelCase_							: str    )   ->Optional[int]:



              """simple docstring"""



              snake_case_          =						shape_list(lowerCAmelCase__    )
              snake_case_          =						tf.range(lp_size[0]						,    dtype=target.dtype    )
              snake_case_          =						tf.stack([r, target]						,    1    )
              return tf.gather_nd(lowerCAmelCase__						,    lowerCAmelCase__    )



       def 						lowerCAmelCase    (			self							: Any						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: Union[str, Any]						,    UpperCAmelCase_							: Dict=True						,    UpperCAmelCase_							: Union[str, Any]=False    )   ->List[str]:



              """simple docstring"""



              snake_case_          =						0
              if self.n_clusters == 0:
                     snake_case_          =						self._logit(lowerCAmelCase__						,    self.out_layers[0][0]						,    self.out_layers[0][1]						,    self.out_projs[0]    )
                     if target is not None:
                            snake_case_          =						tf.nn.sparse_softmax_cross_entropy_with_logits(labels=lowerCAmelCase__						,    logits=lowerCAmelCase__    )
                     snake_case_          =						tf.nn.log_softmax(lowerCAmelCase__						,    axis=-1    )
              else:
                     snake_case_          =						shape_list(lowerCAmelCase__    )
                     snake_case_          =						[]
                     snake_case_          =						tf.zeros(hidden_sizes[:2]    )
                     for i in range(len(self.cutoffs    )    ):
                            snake_case_    ,  snake_case_          =						self.cutoff_ends[i], self.cutoff_ends[i + 1]
                            if target is not None:
                                   snake_case_          =						(target >= l_idx) & (target < r_idx)
                                   snake_case_          =						tf.where(lowerCAmelCase__    )
                                   snake_case_          =						tf.boolean_mask(lowerCAmelCase__						,    lowerCAmelCase__    ) - l_idx

                            if self.div_val == 1:
                                   snake_case_          =						self.out_layers[0][0][l_idx:r_idx]
                                   snake_case_          =						self.out_layers[0][1][l_idx:r_idx]
                            else:
                                   snake_case_          =						self.out_layers[i][0]
                                   snake_case_          =						self.out_layers[i][1]

                            if i == 0:
                                   snake_case_          =						tf.concat([cur_W, self.cluster_weight]						,    0    )
                                   snake_case_          =						tf.concat([cur_b, self.cluster_bias]						,    0    )

                                   snake_case_          =						self._logit(lowerCAmelCase__						,    lowerCAmelCase__						,    lowerCAmelCase__						,    self.out_projs[0]    )
                                   snake_case_          =						tf.nn.log_softmax(lowerCAmelCase__    )
                                   out.append(head_logprob[..., : self.cutoffs[0]]    )
                                   if target is not None:
                                          snake_case_          =						tf.boolean_mask(lowerCAmelCase__						,    lowerCAmelCase__    )
                                          snake_case_          =						self._gather_logprob(lowerCAmelCase__						,    lowerCAmelCase__    )
                            else:
                                   snake_case_          =						self._logit(lowerCAmelCase__						,    lowerCAmelCase__						,    lowerCAmelCase__						,    self.out_projs[i]    )
                                   snake_case_          =						tf.nn.log_softmax(lowerCAmelCase__    )
                                   snake_case_          =						self.cutoffs[0] + i - 1  # No probability for the head cluster
                                   snake_case_          =						head_logprob[..., cluster_prob_idx, None] + tail_logprob
                                   out.append(lowerCAmelCase__    )
                                   if target is not None:
                                          snake_case_          =						tf.boolean_mask(lowerCAmelCase__						,    lowerCAmelCase__    )
                                          snake_case_          =						tf.boolean_mask(lowerCAmelCase__						,    lowerCAmelCase__    )
                                          snake_case_          =						self._gather_logprob(lowerCAmelCase__						,    lowerCAmelCase__    )
                                          cur_logprob += cur_head_logprob[:, self.cutoff_ends[1] + i - 1]
                            if target is not None:
                                   loss += tf.scatter_nd(lowerCAmelCase__						,    -cur_logprob						,    shape_list(lowerCAmelCase__    )    )
                     snake_case_          =						tf.concat(lowerCAmelCase__						,    axis=-1    )

              if target is not None:
                     if return_mean:
                            snake_case_          =						tf.reduce_mean(lowerCAmelCase__    )
                     # Add the training-time loss value to the layer using `self.add_loss()`.
                     self.add_loss(lowerCAmelCase__    )

                     # Log the loss as a metric (we could log arbitrary metrics,
                     # including different metrics for training and inference.
                     self.add_metric(lowerCAmelCase__						,    name=self.name						,    aggregation="""mean""" if return_mean else """"""    )

              return out







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



