



'''simple docstring'''

import unittest

from transformers import PegasusConfig, PegasusTokenizer, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
							import os

							# The slow tests are often failing with OOM error on GPU
							# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
							# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
							__lowerCAmelCase		     =  '''platform'''
							import jax
							import jax.numpy as jnp
							import numpy as np

							from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel

@require_flax
class       __magic_name__		:
							lowerCAmelCase			:       List[Any]  							=   PegasusConfig
							lowerCAmelCase			:       int  							=   {}
							lowerCAmelCase			:       Dict  							=   'gelu'







							def __init__(				self   :			Any      ,_UpperCAmelCase   :			Tuple      ,_UpperCAmelCase   :			str=13      ,_UpperCAmelCase   :			List[Any]=7      ,_UpperCAmelCase   :			List[Any]=True      ,_UpperCAmelCase   :			str=False      ,_UpperCAmelCase   :			List[Any]=99      ,_UpperCAmelCase   :			Optional[Any]=32      ,_UpperCAmelCase   :			Tuple=5      ,_UpperCAmelCase   :			str=4      ,_UpperCAmelCase   :			Tuple=37      ,_UpperCAmelCase   :			str=0.1      ,_UpperCAmelCase   :			Union[str, Any]=0.1      ,_UpperCAmelCase   :			List[Any]=20      ,_UpperCAmelCase   :			str=2      ,_UpperCAmelCase   :			Tuple=1      ,_UpperCAmelCase   :			Tuple=0      ,):
									_a	: List[str]								=				parent
									_a	: Union[str, Any]								=				batch_size
									_a	: Optional[int]								=				seq_length
									_a	: Dict								=				is_training
									_a	: str								=				use_labels
									_a	: Dict								=				vocab_size
									_a	: Optional[int]								=				hidden_size
									_a	: Any								=				num_hidden_layers
									_a	: Optional[int]								=				num_attention_heads
									_a	: Dict								=				intermediate_size

									_a	: str								=				hidden_dropout_prob
									_a	: Optional[Any]								=				attention_probs_dropout_prob
									_a	: Optional[Any]								=				max_position_embeddings
									_a	: Optional[Any]								=				eos_token_id
									_a	: Optional[int]								=				pad_token_id
									_a	: int								=				bos_token_id







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a	: Any								=				ids_tensor([self.batch_size, self.seq_length - 1]      ,self.vocab_size						).clip(3      ,self.vocab_size						)
									_a	: str								=				np.expand_dims(np.array([self.eos_token_id] * self.batch_size						)      ,1						)
									_a	: List[str]								=				np.concatenate([input_ids, eos_tensor]      ,axis=1						)

									_a	: Optional[int]								=				ids_tensor([self.batch_size, self.seq_length]      ,self.vocab_size						)

									_a	: int								=				self.config_cls(
									    vocab_size=self.vocab_size      ,d_model=self.hidden_size      ,encoder_layers=self.num_hidden_layers      ,decoder_layers=self.num_hidden_layers      ,encoder_attention_heads=self.num_attention_heads      ,decoder_attention_heads=self.num_attention_heads      ,encoder_ffn_dim=self.intermediate_size      ,decoder_ffn_dim=self.intermediate_size      ,dropout=self.hidden_dropout_prob      ,attention_dropout=self.attention_probs_dropout_prob      ,max_position_embeddings=self.max_position_embeddings      ,eos_token_ids=[2]      ,bos_token_id=self.bos_token_id      ,pad_token_id=self.pad_token_id      ,decoder_start_token_id=self.pad_token_id      ,**self.config_updates      ,)
									_a	: Optional[Any]								=				prepare_pegasus_inputs_dict(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)
									return config, inputs_dict







							def 				__lowercase     (				self   :			Union[str, Any]      ,_UpperCAmelCase   :			Optional[Any]      ,_UpperCAmelCase   :			Any      ,_UpperCAmelCase   :			int						):
									_a	: Dict								=				20
									_a	: Optional[int]								=				model_class_name(_UpperCAmelCase						)

									_a	: Optional[int]								=				model.encode(inputs_dict['input_ids']						)

									_a			,   _a	: Union[str, Any]								=				(
									    inputs_dict['decoder_input_ids'],
									    inputs_dict['decoder_attention_mask'],
									)

									_a	: Optional[int]								=				model.init_cache(decoder_input_ids.shape[0]      ,_UpperCAmelCase      ,_UpperCAmelCase						)
									_a	: Dict								=				jnp.ones((decoder_input_ids.shape[0], max_decoder_length)      ,dtype='i4'						)

									_a	: Optional[int]								=				jnp.broadcast_to(
									    jnp.arange(decoder_input_ids.shape[-1] - 1						)[None, :]      ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)      ,)
									_a	: List[Any]								=				model.decode(
									    decoder_input_ids[:, :-1]      ,_UpperCAmelCase      ,decoder_attention_mask=_UpperCAmelCase      ,past_key_values=_UpperCAmelCase      ,decoder_position_ids=_UpperCAmelCase      ,)

									_a	: Dict								=				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,dtype='i4'						)
									_a	: List[Any]								=				model.decode(
									    decoder_input_ids[:, -1:]      ,_UpperCAmelCase      ,decoder_attention_mask=_UpperCAmelCase      ,past_key_values=outputs_cache.past_key_values      ,decoder_position_ids=_UpperCAmelCase      ,)

									_a	: List[str]								=				model.decode(_UpperCAmelCase      ,_UpperCAmelCase						)

									_a	: Optional[int]								=				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
									self.parent.assertTrue(diff < 1E-3      ,msg=F"""Max diff is {diff}"""						)







							def 				__lowercase     (				self   :			Optional[int]      ,_UpperCAmelCase   :			Tuple      ,_UpperCAmelCase   :			Dict      ,_UpperCAmelCase   :			List[Any]						):
									_a	: int								=				20
									_a	: Any								=				model_class_name(_UpperCAmelCase						)

									_a	: List[str]								=				model.encode(inputs_dict['input_ids']						)

									_a			,   _a	: Optional[Any]								=				(
									    inputs_dict['decoder_input_ids'],
									    inputs_dict['decoder_attention_mask'],
									)

									_a	: Tuple								=				jnp.concatenate(
									    [
									        decoder_attention_mask,
									        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])						),
									    ]      ,axis=-1      ,)

									_a	: int								=				model.init_cache(decoder_input_ids.shape[0]      ,_UpperCAmelCase      ,_UpperCAmelCase						)
									_a	: Any								=				jnp.broadcast_to(
									    jnp.arange(decoder_input_ids.shape[-1] - 1						)[None, :]      ,(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)      ,)

									_a	: int								=				model.decode(
									    decoder_input_ids[:, :-1]      ,_UpperCAmelCase      ,decoder_attention_mask=_UpperCAmelCase      ,past_key_values=_UpperCAmelCase      ,decoder_position_ids=_UpperCAmelCase      ,)
									_a	: Optional[Any]								=				jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]      ,dtype='i4'						)
									_a	: Optional[Any]								=				model.decode(
									    decoder_input_ids[:, -1:]      ,_UpperCAmelCase      ,past_key_values=outputs_cache.past_key_values      ,decoder_attention_mask=_UpperCAmelCase      ,decoder_position_ids=_UpperCAmelCase      ,)

									_a	: Optional[Any]								=				model.decode(_UpperCAmelCase      ,_UpperCAmelCase      ,decoder_attention_mask=_UpperCAmelCase						)

									_a	: str								=				np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])						)						)
									self.parent.assertTrue(diff < 1E-3      ,msg=F"""Max diff is {diff}"""						)



def 	__lowerCamelCase	( lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_		,     lowerCAmelCase_=None		,     lowerCAmelCase_=None		,     )     -> List[str]:
		if attention_mask is None:
				_a	: List[str]								=				np.not_equal(lowerCAmelCase_		,     config.pad_token_id    ).astype(np.inta    )
		if decoder_attention_mask is None:
				_a	: int								=				np.concatenate(
				    [
				        np.ones(decoder_input_ids[:, :1].shape		,     dtype=np.inta    ),
				        np.not_equal(decoder_input_ids[:, 1:]		,     config.pad_token_id    ).astype(np.inta    ),
				    ]		,     axis=-1		,     )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": decoder_attention_mask,
		}

@require_flax
class       __magic_name__		(       _UpperCamelCase     ,		unittest.TestCase  ):
							lowerCAmelCase			:       List[str]  							=   (
							    (
							        FlaxPegasusForConditionalGeneration,
							        FlaxPegasusModel,
							    )
							    if is_flax_available()
							    else ()
							)
							lowerCAmelCase			:       Any  							=   (FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
							lowerCAmelCase			:       List[Any]  							=   True
							lowerCAmelCase			:       List[str]  							=   False
							lowerCAmelCase			:       List[Any]  							=   False
							lowerCAmelCase			:       List[str]  							=   False







							def 				__lowercase     (				self   :			str						):
									_a	: Union[str, Any]								=				FlaxPegasusModelTester(self						)
									_a	: str								=				ConfigTester(self      ,config_class=_UpperCAmelCase						)







							def 				__lowercase     (				self   :			List[str]						):
									self.config_tester.run_common_tests()







							def 				__lowercase     (				self   :			str						):
									_a			,   _a	: Dict								=				self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
											self.model_tester.check_use_cache_forward(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			str						):
									_a			,   _a	: Optional[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
											self.model_tester.check_use_cache_forward_with_attn_mask(_UpperCAmelCase      ,_UpperCAmelCase      ,_UpperCAmelCase						)







							def 				__lowercase     (				self   :			Any						):
									_a			,   _a	: List[Any]								=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__						):
													_a	: str								=				self._prepare_for_class(_UpperCAmelCase      ,_UpperCAmelCase						)
													_a	: List[str]								=				model_class(_UpperCAmelCase						)

													@jax.jit
													def encode_jitted(_UpperCAmelCase   :			int      ,_UpperCAmelCase   :			int=None      ,**_UpperCAmelCase   :			Tuple						):
															return model.encode(input_ids=_UpperCAmelCase      ,attention_mask=_UpperCAmelCase						)

													with self.subTest('JIT Enabled'						):
															_a	: str								=				encode_jitted(**_UpperCAmelCase						).to_tuple()

													with self.subTest('JIT Disabled'						):
															with jax.disable_jit():
																	_a	: Dict								=				encode_jitted(**_UpperCAmelCase						).to_tuple()

													self.assertEqual(len(_UpperCAmelCase						)      ,len(_UpperCAmelCase						)						)
													for jitted_output, output in zip(_UpperCAmelCase      ,_UpperCAmelCase						):
															self.assertEqual(jitted_output.shape      ,output.shape						)







							def 				__lowercase     (				self   :			Optional[Any]						):
									_a			,   _a	: Any								=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											with self.subTest(model_class.__name__						):
													_a	: int								=				model_class(_UpperCAmelCase						)
													_a	: List[str]								=				model.encode(inputs_dict['input_ids']      ,inputs_dict['attention_mask']						)

													_a	: str								=				{
													    'decoder_input_ids': inputs_dict['decoder_input_ids'],
													    'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
													    'encoder_outputs': encoder_outputs,
													}

													@jax.jit
													def decode_jitted(_UpperCAmelCase   :			int      ,_UpperCAmelCase   :			List[str]      ,_UpperCAmelCase   :			Tuple						):
															return model.decode(
															    decoder_input_ids=_UpperCAmelCase      ,decoder_attention_mask=_UpperCAmelCase      ,encoder_outputs=_UpperCAmelCase      ,)

													with self.subTest('JIT Enabled'						):
															_a	: Any								=				decode_jitted(**_UpperCAmelCase						).to_tuple()

													with self.subTest('JIT Disabled'						):
															with jax.disable_jit():
																	_a	: Optional[Any]								=				decode_jitted(**_UpperCAmelCase						).to_tuple()

													self.assertEqual(len(_UpperCAmelCase						)      ,len(_UpperCAmelCase						)						)
													for jitted_output, output in zip(_UpperCAmelCase      ,_UpperCAmelCase						):
															self.assertEqual(jitted_output.shape      ,output.shape						)







							@slow
							def 				__lowercase     (				self   :			Any						):
									for model_class_name in self.all_model_classes:
											_a	: Union[str, Any]								=				model_class_name.from_pretrained('google/pegasus-large'      ,from_pt=_UpperCAmelCase						)
											_a	: Tuple								=				np.ones((1, 1)						)
											_a	: Union[str, Any]								=				model(_UpperCAmelCase						)
											self.assertIsNotNone(_UpperCAmelCase						)







							@slow
							def 				__lowercase     (				self   :			Union[str, Any]						):
									_a	: str								=				FlaxPegasusForConditionalGeneration.from_pretrained('google/pegasus-xsum'						)
									_a	: Dict								=				PegasusTokenizer.from_pretrained('google/pegasus-xsum'						)

									_a	: List[str]								=				[
									    ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
									    ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
									]

									_a	: Optional[Any]								=				[
									    'California\'s largest electricity provider has turned off power to hundreds of thousands of customers.',
									    'Pop group N-Dubz have revealed they were surprised to get four nominations for this year\'s Mobo Awards.',
									]

									_a	: str								=				tokenizer(_UpperCAmelCase      ,return_tensors='np'      ,truncation=_UpperCAmelCase      ,max_length=512      ,padding=_UpperCAmelCase						)
									_a	: str								=				model.generate(**_UpperCAmelCase      ,num_beams=2						).sequences
									_a	: Tuple								=				tokenizer.batch_decode(_UpperCAmelCase      ,skip_special_tokens=_UpperCAmelCase						)
									assert tgt_text == decoded









'''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		     =  '''\
@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		     =  '''\
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		     =  '''
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       __magic_name__		(       datasets.Metric  ):







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




