"""simple docstring"""






from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import (
						    TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
						    TFTransfoXLForSequenceClassification,
						    TFTransfoXLLMHeadModel,
						    TFTransfoXLModel,
						)
class 				snake_case       :




					"""simple docstring"""

					def __init__(				self   :	List[Any]    ,lowerCamelCase__   :	List[str]    ,):
									UpperCAmelCase__             =							parent
									UpperCAmelCase__             =							13
									UpperCAmelCase__             =							7
									UpperCAmelCase__             =							30
									UpperCAmelCase__             =							self.seq_length + self.mem_len
									UpperCAmelCase__             =							15
									UpperCAmelCase__             =							True
									UpperCAmelCase__             =							True
									UpperCAmelCase__             =							99
									UpperCAmelCase__             =							[10, 50, 80]
									UpperCAmelCase__             =							32
									UpperCAmelCase__             =							32
									UpperCAmelCase__             =							4
									UpperCAmelCase__             =							8
									UpperCAmelCase__             =							128
									UpperCAmelCase__             =							2
									UpperCAmelCase__             =							2
									UpperCAmelCase__             =							None
									UpperCAmelCase__             =							1
									UpperCAmelCase__             =							0
									UpperCAmelCase__             =							3
									UpperCAmelCase__             =							self.vocab_size - 1
									UpperCAmelCase__             =							0.0_1







					def 		__lowerCAmelCase						(				self   :	Tuple			):
									UpperCAmelCase__             =							ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size			)
									UpperCAmelCase__             =							ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size			)

									UpperCAmelCase__             =							None
									if self.use_labels:
													UpperCAmelCase__             =							ids_tensor([self.batch_size, self.seq_length]    ,self.vocab_size			)

									UpperCAmelCase__             =							TransfoXLConfig(
									    vocab_size=self.vocab_size    ,mem_len=self.mem_len    ,clamp_len=self.clamp_len    ,cutoffs=self.cutoffs    ,d_model=self.hidden_size    ,d_embed=self.d_embed    ,n_head=self.num_attention_heads    ,d_head=self.d_head    ,d_inner=self.d_inner    ,div_val=self.div_val    ,n_layer=self.num_hidden_layers    ,eos_token_id=self.eos_token_id    ,pad_token_id=self.vocab_size - 1    ,init_range=self.init_range    ,num_labels=self.num_labels    ,)

									return (config, input_ids_a, input_ids_a, lm_labels)







					def 		__lowerCAmelCase						(				self   :	Union[str, Any]			):
									random.seed(self.seed			)
									tf.random.set_seed(self.seed			)







					def 		__lowerCAmelCase						(				self   :	Any    ,lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	Any    ,lowerCamelCase__   :	Optional[Any]    ,lowerCamelCase__   :	Optional[Any]			):
									UpperCAmelCase__             =							TFTransfoXLModel(lowerCamelCase__			)

									UpperCAmelCase__      ,	UpperCAmelCase__             =							model(lowerCamelCase__			).to_tuple()

									UpperCAmelCase__             =							{'input_ids': input_ids_a, 'mems': mems_a}

									UpperCAmelCase__      ,	UpperCAmelCase__             =							model(lowerCamelCase__			).to_tuple()

									self.parent.assertEqual(hidden_states_a.shape    ,(self.batch_size, self.seq_length, self.hidden_size)			)
									self.parent.assertEqual(hidden_states_a.shape    ,(self.batch_size, self.seq_length, self.hidden_size)			)
									self.parent.assertListEqual(
									    [mem.shape for mem in mems_a]    ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers    ,)
									self.parent.assertListEqual(
									    [mem.shape for mem in mems_a]    ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers    ,)







					def 		__lowerCAmelCase						(				self   :	List[Any]    ,lowerCamelCase__   :	List[str]    ,lowerCamelCase__   :	Any    ,lowerCamelCase__   :	Union[str, Any]    ,lowerCamelCase__   :	Tuple			):
									UpperCAmelCase__             =							TFTransfoXLLMHeadModel(lowerCamelCase__			)

									UpperCAmelCase__      ,	UpperCAmelCase__             =							model(lowerCamelCase__			).to_tuple()

									UpperCAmelCase__             =							{'input_ids': input_ids_a, 'labels': lm_labels}
									UpperCAmelCase__      ,	UpperCAmelCase__             =							model(lowerCamelCase__			).to_tuple()

									UpperCAmelCase__      ,	UpperCAmelCase__             =							model([input_ids_a, mems_a]			).to_tuple()

									UpperCAmelCase__             =							{'input_ids': input_ids_a, 'mems': mems_a, 'labels': lm_labels}

									UpperCAmelCase__      ,	UpperCAmelCase__             =							model(lowerCamelCase__			).to_tuple()

									self.parent.assertEqual(lm_logits_a.shape    ,(self.batch_size, self.seq_length, self.vocab_size)			)
									self.parent.assertListEqual(
									    [mem.shape for mem in mems_a]    ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers    ,)

									self.parent.assertEqual(lm_logits_a.shape    ,(self.batch_size, self.seq_length, self.vocab_size)			)
									self.parent.assertListEqual(
									    [mem.shape for mem in mems_a]    ,[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers    ,)







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	Tuple    ,lowerCamelCase__   :	Optional[int]    ,lowerCamelCase__   :	Any			):
									UpperCAmelCase__             =							TFTransfoXLForSequenceClassification(lowerCamelCase__			)
									UpperCAmelCase__             =							model(lowerCamelCase__			)
									self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)			)







					def 		__lowerCAmelCase						(				self   :	List[Any]			):
									UpperCAmelCase__             =							self.prepare_config_and_inputs()
									((UpperCAmelCase__)      ,	(UpperCAmelCase__)      ,	(UpperCAmelCase__)      ,	(UpperCAmelCase__))             =							config_and_inputs
									UpperCAmelCase__             =							{'input_ids': input_ids_a}
									return config, inputs_dict






@require_tf
class 				snake_case       ( __UpperCAmelCase      ,    __UpperCAmelCase      ,    unittest.TestCase				):




					"""simple docstring"""

					snake_case__				    = (
					    (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
					)
					snake_case__				    = () if is_tf_available() else ()
					snake_case__				    = (
					    {
					        "feature-extraction": TFTransfoXLModel,
					        "text-classification": TFTransfoXLForSequenceClassification,
					        "text-generation": TFTransfoXLLMHeadModel,
					        "zero-shot": TFTransfoXLForSequenceClassification,
					    }
					    if is_tf_available()
					    else {}
					)
					# TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
					snake_case__				    = False
					snake_case__				    = False
					snake_case__				    = False
					snake_case__				    = False







					def 		__lowerCAmelCase						(				self   :	Dict    ,lowerCamelCase__   :	List[str]    ,lowerCamelCase__   :	Dict    ,lowerCamelCase__   :	Optional[int]    ,lowerCamelCase__   :	Dict    ,lowerCamelCase__   :	str			):
									if pipeline_test_casse_name == "TextGenerationPipelineTests":
													# Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
													# `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
													# tokenizer.
													return True

									return False







					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									UpperCAmelCase__             =							TFTransfoXLModelTester(self			)
									UpperCAmelCase__             =							ConfigTester(self    ,config_class=lowerCamelCase__    ,d_embed=37			)







					def 		__lowerCAmelCase						(				self   :	int			):
									self.config_tester.run_common_tests()







					def 		__lowerCAmelCase						(				self   :	Tuple			):
									self.model_tester.set_seed()
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_transfo_xl_model(*lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	int			):
									self.model_tester.set_seed()
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_transfo_xl_lm_head(*lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*lowerCamelCase__			)







					def 		__lowerCAmelCase						(				self   :	Tuple			):
									UpperCAmelCase__      ,	UpperCAmelCase__             =							self.model_tester.prepare_config_and_inputs_for_common()
									UpperCAmelCase__             =							[TFTransfoXLForSequenceClassification]

									for model_class in self.all_model_classes:
													UpperCAmelCase__             =							model_class(lowerCamelCase__			)
													assert isinstance(model.get_input_embeddings()    ,tf.keras.layers.Layer			)
													if model_class in list_other_models_with_output_ebd:
																	UpperCAmelCase__             =							model.get_output_embeddings()
																	assert isinstance(lowerCamelCase__    ,tf.keras.layers.Layer			)
																	UpperCAmelCase__             =							model.get_bias()
																	assert name is None
													else:
																	UpperCAmelCase__             =							model.get_output_embeddings()
																	assert x is None
																	UpperCAmelCase__             =							model.get_bias()
																	assert name is None







					def 		__lowerCAmelCase						(				self   :	List[str]			):
									# TODO JP: Make TransfoXL XLA compliant
									pass







					@slow
					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													UpperCAmelCase__             =							TFTransfoXLModel.from_pretrained(lowerCamelCase__			)
													self.assertIsNotNone(lowerCamelCase__			)







					@unittest.skip(reason='This model doesn\'t play well with fit() due to not returning a single loss.'			)
					def 		__lowerCAmelCase						(				self   :	str			):
									pass






@require_tf
class 				snake_case       ( unittest.TestCase				):




					"""simple docstring"""

					@unittest.skip('Skip test until #12651 is resolved.'			)
					@slow
					def 		__lowerCAmelCase						(				self   :	Optional[Any]			):
									UpperCAmelCase__             =							TFTransfoXLLMHeadModel.from_pretrained('transfo-xl-wt103'			)
									# fmt: off
									UpperCAmelCase__             =							tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]]    ,dtype=tf.intaa			)  # noqa: E231
									# fmt: on
									#  In 1991 , the remains of Russian Tsar Nicholas II and his family
									#  ( except for Alexei and Maria ) are discovered .
									#  The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
									#  remainder of the story . 1883 Western Siberia ,
									#  a young Grigori Rasputin is asked by his father and a group of men to perform magic .
									#  Rasputin has a vision and denounces one of the men as a horse thief . Although his
									#  father initially slaps him for making such an accusation , Rasputin watches as the
									#  man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
									#  the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
									#  with people , even a bishop , begging for his blessing . <eod> </s> <eos>

									# fmt: off
									UpperCAmelCase__             =							[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0]  # noqa: E231
									# fmt: on
									#  In 1991, the remains of Russian Tsar Nicholas II and his family (
									#  except for Alexei and Maria ) are discovered. The voice of young son,
									#  Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
									#  1883 Western Siberia, a young Grigori Rasputin is asked by his father
									#  and a group of men to perform magic. Rasputin has a vision and
									#  denounces one of the men as a horse thief. Although his father initially
									#  slaps him for making such an accusation, Rasputin watches as the man
									#  is chased outside and beaten. Twenty years later, Rasputin sees a vision
									#  of the Virgin Mary, prompting him to become a priest.
									#  Rasputin quickly becomes famous, with people, even a bishop, begging for
									#  his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
									# Nicholas II and his family were discovered. The voice of <unk> young son,
									# Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

									UpperCAmelCase__             =							model.generate(lowerCamelCase__    ,max_length=200    ,do_sample=lowerCamelCase__			)
									self.assertListEqual(output_ids[0].numpy().tolist()    ,lowerCamelCase__			)




"""simple docstring"""






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

import datasets
from datasets import logging


lowerCAmelCase__  :  List[Any]						     =	'\\n\n'

lowerCAmelCase__  :  Tuple						     =	'\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n'

lowerCAmelCase__  :  str						     =	'\nArgs:\n    model_id (str): model used for calculating Perplexity\n            NOTE: Perplexity can only be calculated for causal language models.\n                    This includes models such as gpt2, causal variations of bert,\n                    causal versions of t5, and more (the full list can be found\n                    in the AutoModelForCausalLM documentation here:\n                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n    input_texts (list of str): input text, each separate text snippet\n        is one list entry.\n    batch_size (int): the batch size to run texts through the model. Defaults to 16.\n    add_start_token (bool): whether to add the start token to the texts,\n        so the perplexity can include the probability of the first word. Defaults to True.\n    device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n    perplexity: dictionary containing the perplexity scores for the texts\n        in the input list, as well as the mean perplexity. If one of the input texts is\n        longer than the max input length of the model, then it is truncated to the\n        max length for the perplexity computation.\nExamples:\n    Example 1:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              add_start_token=False,\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        78.22\n        >>> print(round(results["perplexities"][0], 2))\n        11.11\n\n    Example 2:\n        >>> perplexity = datasets.load_metric("perplexity")\n        >>> input_texts = datasets.load_dataset("wikitext",\n        ...                                     "wikitext-2-raw-v1",\n        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS\n        [...]\n        >>> input_texts = [s for s in input_texts if s!=\'\']\n        >>> results = perplexity.compute(model_id=\'gpt2\',\n        ...                              input_texts=input_texts) # doctest:+ELLIPSIS\n        >>> print(list(results.keys()))\n        [\'perplexities\', \'mean_perplexity\']\n        >>> print(round(results["mean_perplexity"], 2))\n        60.35\n        >>> print(round(results["perplexities"][0], 2))\n        81.12\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,    _KWARGS_DESCRIPTION				)
class 				snake_case       ( datasets.Metric				):




					"""simple docstring"""

					def 		__lowerCAmelCase						(				self   :	str			):
									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 		__lowerCAmelCase						(				self   :	Tuple    ,lowerCamelCase__   :	Optional[int]    ,lowerCamelCase__   :	List[str]    ,lowerCamelCase__   :	int = 16    ,lowerCamelCase__   :	bool = True    ,lowerCamelCase__   :	List[str]=None			):
									if device is not None:
													assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
													if device == "gpu":
																	UpperCAmelCase__             =							'cuda'
									else:
													UpperCAmelCase__             =							'cuda' if torch.cuda.is_available() else 'cpu'

									UpperCAmelCase__             =							AutoModelForCausalLM.from_pretrained(lowerCamelCase__			)
									UpperCAmelCase__             =							model.to(lowerCamelCase__			)

									UpperCAmelCase__             =							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:
													UpperCAmelCase__             =							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"
													UpperCAmelCase__             =							model.config.max_length - 1
									else:
													UpperCAmelCase__             =							model.config.max_length

									UpperCAmelCase__             =							tokenizer(
									    lowerCamelCase__    ,add_special_tokens=lowerCamelCase__    ,padding=lowerCamelCase__    ,truncation=lowerCamelCase__    ,max_length=lowerCamelCase__    ,return_tensors='pt'    ,return_attention_mask=lowerCamelCase__    ,).to(lowerCamelCase__			)

									UpperCAmelCase__             =							encodings['input_ids']
									UpperCAmelCase__             =							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."

									UpperCAmelCase__             =							[]
									UpperCAmelCase__             =							CrossEntropyLoss(reduction='none'			)

									for start_index in logging.tqdm(range(0    ,len(lowerCamelCase__			)    ,lowerCamelCase__			)			):
													UpperCAmelCase__             =							min(start_index + batch_size    ,len(lowerCamelCase__			)			)
													UpperCAmelCase__             =							encoded_texts[start_index:end_index]
													UpperCAmelCase__             =							attn_masks[start_index:end_index]

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

													UpperCAmelCase__             =							encoded_batch

													with torch.no_grad():
																	UpperCAmelCase__             =							model(lowerCamelCase__    ,attention_mask=lowerCamelCase__			).logits

													UpperCAmelCase__             =							out_logits[..., :-1, :].contiguous()
													UpperCAmelCase__             =							labels[..., 1:].contiguous()
													UpperCAmelCase__             =							attn_mask[..., 1:].contiguous()

													UpperCAmelCase__             =							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__			)}



