





"""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
		a		:					Dict	      =     '''platform'''
		import jax
		import jax.numpy as jnp
		import numpy as np

		from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel


@require_flax
class 			__UpperCamelCase							:
							lowerCamelCase  :   Optional[int]    =PegasusConfig
							lowerCamelCase  :   str    ={}
							lowerCamelCase  :   Tuple    ="""gelu"""






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

								a :						Union[str, Any]      =							hidden_dropout_prob
								a :						str      =							attention_probs_dropout_prob
								a :						List[Any]      =							max_position_embeddings
								a :						Union[str, Any]      =							eos_token_id
								a :						Tuple      =							pad_token_id
								a :						Optional[int]      =							bos_token_id






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

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

								a :						Optional[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 :						Any      =							prepare_pegasus_inputs_dict(lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )
								return config, inputs_dict






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					Dict:
								a :						Optional[int]      =							20
								a :						Dict      =							model_class_name(lowerCAmelCase__ )

								a :						Optional[Any]      =							model.encode(inputs_dict["input_ids"] )

								a,			a :						Union[str, Any]      =							(
								    inputs_dict["decoder_input_ids"],
								    inputs_dict["decoder_attention_mask"],
								)

								a :						List[Any]      =							model.init_cache(decoder_input_ids.shape[0] ,   lowerCAmelCase__ ,   lowerCAmelCase__ )
								a :						str      =							jnp.ones((decoder_input_ids.shape[0], max_decoder_length) ,   dtype="i4" )

								a :						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 :						Dict      =							model.decode(
								    decoder_input_ids[:, :-1] ,   lowerCAmelCase__ ,   decoder_attention_mask=lowerCAmelCase__ ,   past_key_values=lowerCAmelCase__ ,   decoder_position_ids=lowerCAmelCase__ ,   )

								a :						Union[str, Any]      =							jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]] ,   dtype="i4" )
								a :						Dict      =							model.decode(
								    decoder_input_ids[:, -1:] ,   lowerCAmelCase__ ,   decoder_attention_mask=lowerCAmelCase__ ,   past_key_values=outputs_cache.past_key_values ,   decoder_position_ids=lowerCAmelCase__ ,   )

								a :						Optional[Any]      =							model.decode(lowerCAmelCase__ ,   lowerCAmelCase__ )

								a :						Union[str, Any]      =							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        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )      ->					Union[str, Any]:
								a :						Optional[Any]      =							20
								a :						List[str]      =							model_class_name(lowerCAmelCase__ )

								a :						Optional[int]      =							model.encode(inputs_dict["input_ids"] )

								a,			a :						List[Any]      =							(
								    inputs_dict["decoder_input_ids"],
								    inputs_dict["decoder_attention_mask"],
								)

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

								a :						Any      =							model.init_cache(decoder_input_ids.shape[0] ,   lowerCAmelCase__ ,   lowerCAmelCase__ )
								a :						Dict      =							jnp.broadcast_to(
								    jnp.arange(decoder_input_ids.shape[-1] - 1 )[None, :] ,   (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1) ,   )

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

								a :						Any      =							model.decode(lowerCAmelCase__ ,   lowerCAmelCase__ ,   decoder_attention_mask=lowerCAmelCase__ )

								a :						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  _SCREAMING_SNAKE_CASE						(      _lowercase		:       Dict       ,			_lowercase		:       int       ,			_lowercase		:       Optional[Any]       ,			_lowercase		:       Dict=None       ,			_lowercase		:       List[Any]=None       ,			)					->Union[str, Any]:






	'''simple docstring'''






	if attention_mask is None:
		a :						List[Any]      =							np.not_equal(_lowercase       ,			config.pad_token_id   ).astype(np.inta   )
	if decoder_attention_mask is None:
		a :						Any      =							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 			__UpperCamelCase							(		a__						,			unittest.TestCase		):
							lowerCamelCase  :   List[str]    =(
							    (
							        FlaxPegasusForConditionalGeneration,
							        FlaxPegasusModel,
							    )
							    if is_flax_available()
							    else ()
							)
							lowerCamelCase  :   int    =(FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
							lowerCamelCase  :   Optional[Any]    =True
							lowerCamelCase  :   Tuple    =False
							lowerCamelCase  :   Optional[Any]    =False
							lowerCamelCase  :   Optional[int]    =False






							def        __a  (  self )      ->					Dict:
								a :						List[str]      =							FlaxPegasusModelTester(self )
								a :						Any      =							ConfigTester(self ,   config_class=lowerCAmelCase__ )






							def        __a  (  self )      ->					Tuple:
								self.config_tester.run_common_tests()






							def        __a  (  self )      ->					List[str]:
								a,			a :						List[str]      =							self.model_tester.prepare_config_and_inputs_for_common()
								for model_class in self.all_model_classes:
									self.model_tester.check_use_cache_forward(lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )






							def        __a  (  self )      ->					List[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(lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ )






							def        __a  (  self )      ->					Optional[int]:
								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 :						Tuple      =							self._prepare_for_class(lowerCAmelCase__ ,   lowerCAmelCase__ )
										a :						Dict      =							model_class(lowerCAmelCase__ )

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

										with self.subTest("JIT Enabled" ):
											a :						Union[str, Any]      =							encode_jitted(**lowerCAmelCase__ ).to_tuple()

										with self.subTest("JIT Disabled" ):
											with jax.disable_jit():
												a :						Union[str, Any]      =							encode_jitted(**lowerCAmelCase__ ).to_tuple()

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






							def        __a  (  self )      ->					str:
								a,			a :						List[str]      =							self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									with self.subTest(model_class.__name__ ):
										a :						Tuple      =							model_class(lowerCAmelCase__ )
										a :						List[str]      =							model.encode(inputs_dict["input_ids"] ,   inputs_dict["attention_mask"] )

										a :						Any      =							{
										    "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(lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ ):
											return model.decode(
											    decoder_input_ids=lowerCAmelCase__ ,   decoder_attention_mask=lowerCAmelCase__ ,   encoder_outputs=lowerCAmelCase__ ,   )

										with self.subTest("JIT Enabled" ):
											a :						List[Any]      =							decode_jitted(**lowerCAmelCase__ ).to_tuple()

										with self.subTest("JIT Disabled" ):
											with jax.disable_jit():
												a :						Union[str, Any]      =							decode_jitted(**lowerCAmelCase__ ).to_tuple()

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






							@slow
							def        __a  (  self )      ->					Optional[Any]:
								for model_class_name in self.all_model_classes:
									a :						int      =							model_class_name.from_pretrained("google/pegasus-large" ,   from_pt=lowerCAmelCase__ )
									a :						Dict      =							np.ones((1, 1) )
									a :						Any      =							model(lowerCAmelCase__ )
									self.assertIsNotNone(lowerCAmelCase__ )






							@slow
							def        __a  (  self )      ->					str:
								a :						Tuple      =							FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum" )
								a :						Optional[Any]      =							PegasusTokenizer.from_pretrained("google/pegasus-xsum" )

								a :						Dict      =							[
								    " 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 :						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 :						Tuple      =							tokenizer(lowerCAmelCase__ ,   return_tensors="np" ,   truncation=lowerCAmelCase__ ,   max_length=512 ,   padding=lowerCAmelCase__ )
								a :						int      =							model.generate(**lowerCAmelCase__ ,   num_beams=2 ).sequences
								a :						Any      =							tokenizer.batch_decode(lowerCAmelCase__ ,   skip_special_tokens=lowerCAmelCase__ )
								assert tgt_text == decoded









"""simple docstring"""




import numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


a		:					List[Any]	      =     '''\

'''

a		:					Optional[int]	      =     '''
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
'''

a		:					List[Any]	      =     '''
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to \'cuda\' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        78.22
        >>> print(round(results["perplexities"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = datasets.load_dataset("wikitext",
        ...                                     "wikitext-2-raw-v1",
        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!=\'\']
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        60.35
        >>> print(round(results["perplexities"][0], 2))
        81.12
'''


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






							def        __a  (  self )      ->					List[Any]:
								return datasets.MetricInfo(
								    description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
								        {
								            "input_texts": datasets.Value("string" ),
								        } ) ,   reference_urls=["https://huggingface.co/docs/transformers/perplexity"] ,   )






							def        __a  (  self ,   lowerCAmelCase__ ,   lowerCAmelCase__ ,   lowerCAmelCase__ = 16 ,   lowerCAmelCase__ = True ,   lowerCAmelCase__=None )      ->					Tuple:
								if device is not None:
									assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
									if device == "gpu":
										a :						Optional[Any]      =							"cuda"
								else:
									a :						str      =							"cuda" if torch.cuda.is_available() else "cpu"

								a :						str      =							AutoModelForCausalLM.from_pretrained(lowerCAmelCase__ )
								a :						int      =							model.to(lowerCAmelCase__ )

								a :						str      =							AutoTokenizer.from_pretrained(lowerCAmelCase__ )

								# if batch_size > 1 (which generally leads to padding being required), and
								# if there is not an already assigned pad_token, assign an existing
								# special token to also be the padding token
								if tokenizer.pad_token is None and batch_size > 1:
									a :						str      =							list(tokenizer.special_tokens_map_extended.values() )
									# check that the model already has at least one special token defined
									assert (
									    len(lowerCAmelCase__ ) > 0
									), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
									# assign one of the special tokens to also be the pad token
									tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} )

								if add_start_token:
									# leave room for <BOS> token to be added:
									assert (
									    tokenizer.bos_token is not None
									), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
									a :						List[Any]      =							model.config.max_length - 1
								else:
									a :						Union[str, Any]      =							model.config.max_length

								a :						Union[str, Any]      =							tokenizer(
								    lowerCAmelCase__ ,   add_special_tokens=lowerCAmelCase__ ,   padding=lowerCAmelCase__ ,   truncation=lowerCAmelCase__ ,   max_length=lowerCAmelCase__ ,   return_tensors="pt" ,   return_attention_mask=lowerCAmelCase__ ,   ).to(lowerCAmelCase__ )

								a :						str      =							encodings["input_ids"]
								a :						Optional[int]      =							encodings["attention_mask"]

								# check that each input is long enough:
								if add_start_token:
									assert torch.all(torch.ge(attn_masks.sum(1 ) ,   1 ) ), "Each input text must be at least one token long."
								else:
									assert torch.all(
									    torch.ge(attn_masks.sum(1 ) ,   2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

								a :						List[Any]      =							[]
								a :						List[Any]      =							CrossEntropyLoss(reduction="none" )

								for start_index in logging.tqdm(range(0 ,   len(lowerCAmelCase__ ) ,   lowerCAmelCase__ ) ):
									a :						Optional[Any]      =							min(start_index + batch_size ,   len(lowerCAmelCase__ ) )
									a :						Any      =							encoded_texts[start_index:end_index]
									a :						List[Any]      =							attn_masks[start_index:end_index]

									if add_start_token:
										a :						int      =							torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(lowerCAmelCase__ )
										a :						str      =							torch.cat([bos_tokens_tensor, encoded_batch] ,   dim=1 )
										a :						str      =							torch.cat(
										    [torch.ones(bos_tokens_tensor.size() ,   dtype=torch.intaa ).to(lowerCAmelCase__ ), attn_mask] ,   dim=1 )

									a :						Any      =							encoded_batch

									with torch.no_grad():
										a :						Optional[int]      =							model(lowerCAmelCase__ ,   attention_mask=lowerCAmelCase__ ).logits

									a :						List[Any]      =							out_logits[..., :-1, :].contiguous()
									a :						int      =							labels[..., 1:].contiguous()
									a :						Union[str, Any]      =							attn_mask[..., 1:].contiguous()

									a :						Dict      =							torch.expa(
									    (loss_fct(shift_logits.transpose(1 ,   2 ) ,   lowerCAmelCase__ ) * shift_attention_mask_batch).sum(1 )
									    / shift_attention_mask_batch.sum(1 ) )

									ppls += perplexity_batch.tolist()

								return {"perplexities": ppls, "mean_perplexity": np.mean(lowerCAmelCase__ )}


