






"""simple docstring"""

from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
					import tensorflow as tf

					from transformers.models.xglm.modeling_tf_xglm import (
					    TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TFXGLMForCausalLM,
					    TFXGLMModel,
					)


@require_tf
class 		__lowerCamelCase				:





		'''simple docstring'''






		a_	:				List[str]            =							XGLMConfig
		a_	:				Optional[Any]            =							{}
		a_	:				Optional[int]            =							"""gelu"""





		def __init__(   self							:	Union[str, Any]						,			a_							:	str						,			a_							:	Optional[Any]=14						,			a_							:	Union[str, Any]=7						,			a_							:	List[Any]=True						,			a_							:	Any=True						,			a_							:	int=True						,			a_							:	Any=99						,			a_							:	Union[str, Any]=32						,			a_							:	List[Any]=2						,			a_							:	Optional[Any]=4						,			a_							:	Optional[Any]=37						,			a_							:	int="gelu"						,			a_							:	int=0.1						,			a_							:	Any=0.1						,			a_							:	List[str]=5_12						,			a_							:	List[Any]=0.02						,			):
				lowerCAmelCase_   :							Tuple									=			parent
				lowerCAmelCase_   :							Optional[Any]									=			batch_size
				lowerCAmelCase_   :							List[Any]									=			seq_length
				lowerCAmelCase_   :							Union[str, Any]									=			is_training
				lowerCAmelCase_   :							Tuple									=			use_input_mask
				lowerCAmelCase_   :							List[str]									=			use_labels
				lowerCAmelCase_   :							Union[str, Any]									=			vocab_size
				lowerCAmelCase_   :							Tuple									=			d_model
				lowerCAmelCase_   :							Any									=			num_hidden_layers
				lowerCAmelCase_   :							Union[str, Any]									=			num_attention_heads
				lowerCAmelCase_   :							Optional[Any]									=			ffn_dim
				lowerCAmelCase_   :							List[Any]									=			activation_function
				lowerCAmelCase_   :							str									=			activation_dropout
				lowerCAmelCase_   :							List[str]									=			attention_dropout
				lowerCAmelCase_   :							List[str]									=			max_position_embeddings
				lowerCAmelCase_   :							Dict									=			initializer_range
				lowerCAmelCase_   :							List[Any]									=			None
				lowerCAmelCase_   :							str									=			0
				lowerCAmelCase_   :							Any									=			2
				lowerCAmelCase_   :							Any									=			1





		def    lowerCamelCase       (   self							:	int	):
				return XGLMConfig.from_pretrained("facebook/xglm-564M"	)





		def    lowerCamelCase       (   self							:	List[str]	):
				lowerCAmelCase_   :							Union[str, Any]									=			tf.clip_by_value(
				    ids_tensor([self.batch_size, self.seq_length]						,			self.vocab_size	)						,			clip_value_min=0						,			clip_value_max=3	)

				lowerCAmelCase_   :							List[str]									=			None
				if self.use_input_mask:
						lowerCAmelCase_   :							List[Any]									=			random_attention_mask([self.batch_size, self.seq_length]	)

				lowerCAmelCase_   :							str									=			self.get_config()

				lowerCAmelCase_   :							List[Any]									=			floats_tensor([self.num_hidden_layers, self.num_attention_heads]						,			2	)

				return (
				    config,
				    input_ids,
				    input_mask,
				    head_mask,
				)





		def    lowerCamelCase       (   self							:	str	):
				return XGLMConfig(
				    vocab_size=self.vocab_size						,			d_model=self.hidden_size						,			num_layers=self.num_hidden_layers						,			attention_heads=self.num_attention_heads						,			ffn_dim=self.ffn_dim						,			activation_function=self.activation_function						,			activation_dropout=self.activation_dropout						,			attention_dropout=self.attention_dropout						,			max_position_embeddings=self.max_position_embeddings						,			initializer_range=self.initializer_range						,			use_cache=__lowerCamelCase						,			bos_token_id=self.bos_token_id						,			eos_token_id=self.eos_token_id						,			pad_token_id=self.pad_token_id						,			return_dict=__lowerCamelCase						,			)





		def    lowerCamelCase       (   self							:	Union[str, Any]	):
				lowerCAmelCase_   :							Optional[Any]									=			self.prepare_config_and_inputs()

				(
				    lowerCAmelCase_      
				)   :							Optional[Any]									=			config_and_inputs

				lowerCAmelCase_   :							str									=			{
				    """input_ids""": input_ids,
				    """head_mask""": head_mask,
				}

				return config, inputs_dict







@require_tf
class 		__lowerCamelCase				( _a ,							_a ,							unittest.TestCase			):





		'''simple docstring'''






		a_	:				int            =							(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
		a_	:				Dict            =							(TFXGLMForCausalLM,) if is_tf_available() else ()
		a_	:				Optional[Any]            =							(
		    {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
		)
		a_	:				List[str]            =							False
		a_	:				Optional[int]            =							False
		a_	:				List[str]            =							False





		def    lowerCamelCase       (   self							:	List[Any]	):
				lowerCAmelCase_   :							Optional[Any]									=			TFXGLMModelTester(self	)
				lowerCAmelCase_   :							List[Any]									=			ConfigTester(self						,			config_class=__lowerCamelCase						,			n_embd=37	)





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





		@slow
		def    lowerCamelCase       (   self							:	int	):
				for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowerCAmelCase_   :							str									=			TFXGLMModel.from_pretrained(__lowerCamelCase	)
						self.assertIsNotNone(__lowerCamelCase	)





		@unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor."	)
		def    lowerCamelCase       (   self							:	Dict	):
				super().test_resize_token_embeddings()







@require_tf
class 		__lowerCamelCase				( unittest.TestCase			):





		'''simple docstring'''






		@slow
		def    lowerCamelCase       (   self							:	Optional[Any]						,			a_							:	Optional[int]=True	):
				lowerCAmelCase_   :							Dict									=			TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)
				lowerCAmelCase_   :							str									=			tf.convert_to_tensor([[2, 2_68, 98_65]]						,			dtype=tf.intaa	)  # The dog
				# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
				# fmt: off
				lowerCAmelCase_   :							int									=			[2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81]
				# fmt: on
				lowerCAmelCase_   :							str									=			model.generate(__lowerCamelCase						,			do_sample=__lowerCamelCase						,			num_beams=1	)
				if verify_outputs:
						self.assertListEqual(output_ids[0].numpy().tolist()						,			__lowerCamelCase	)





		@slow
		def    lowerCamelCase       (   self							:	Tuple	):
				lowerCAmelCase_   :							Tuple									=			XGLMTokenizer.from_pretrained("facebook/xglm-564M"	)
				lowerCAmelCase_   :							Tuple									=			TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)

				tf.random.set_seed(0	)
				lowerCAmelCase_   :							Optional[int]									=			tokenizer("Today is a nice day and"						,			return_tensors="tf"	)
				lowerCAmelCase_   :							str									=			tokenized.input_ids
				# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
				with tf.device(":/CPU:0"	):
						lowerCAmelCase_   :							Any									=			model.generate(__lowerCamelCase						,			do_sample=__lowerCamelCase						,			seed=[7, 0]	)
				lowerCAmelCase_   :							str									=			tokenizer.decode(output_ids[0]						,			skip_special_tokens=__lowerCamelCase	)

				lowerCAmelCase_   :							Union[str, Any]									=			(
				    """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"""
				)
				self.assertEqual(__lowerCamelCase						,			__lowerCamelCase	)





		@slow
		def    lowerCamelCase       (   self							:	int	):
				lowerCAmelCase_   :							List[str]									=			TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)
				lowerCAmelCase_   :							Tuple									=			XGLMTokenizer.from_pretrained("facebook/xglm-564M"	)

				lowerCAmelCase_   :							str									=			"""left"""

				# use different length sentences to test batching
				lowerCAmelCase_   :							Union[str, Any]									=			[
				    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
				    """left-padding, such as in batched generation. The output for the sequence below should be the same """
				    """regardless of whether left padding is applied or not. When""",
				    """Hello, my dog is a little""",
				]

				lowerCAmelCase_   :							str									=			tokenizer(__lowerCamelCase						,			return_tensors="tf"						,			padding=__lowerCamelCase	)
				lowerCAmelCase_   :							Optional[int]									=			inputs["""input_ids"""]

				lowerCAmelCase_   :							Dict									=			model.generate(input_ids=__lowerCamelCase						,			attention_mask=inputs["attention_mask"]						,			max_new_tokens=12	)

				lowerCAmelCase_   :							List[str]									=			tokenizer(sentences[0]						,			return_tensors="tf"	).input_ids
				lowerCAmelCase_   :							List[Any]									=			model.generate(input_ids=__lowerCamelCase						,			max_new_tokens=12	)

				lowerCAmelCase_   :							str									=			tokenizer(sentences[1]						,			return_tensors="tf"	).input_ids
				lowerCAmelCase_   :							str									=			model.generate(input_ids=__lowerCamelCase						,			max_new_tokens=12	)

				lowerCAmelCase_   :							Any									=			tokenizer.batch_decode(__lowerCamelCase						,			skip_special_tokens=__lowerCamelCase	)
				lowerCAmelCase_   :							Union[str, Any]									=			tokenizer.decode(output_non_padded[0]						,			skip_special_tokens=__lowerCamelCase	)
				lowerCAmelCase_   :							List[Any]									=			tokenizer.decode(output_padded[0]						,			skip_special_tokens=__lowerCamelCase	)

				lowerCAmelCase_   :							List[Any]									=			[
				    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
				    """left-padding, such as in batched generation. The output for the sequence below should be the same """
				    """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """
				    """a single""",
				    """Hello, my dog is a little bit of a shy one, but he is very friendly""",
				]
				self.assertListEqual(__lowerCamelCase						,			__lowerCamelCase	)
				self.assertListEqual(__lowerCamelCase						,			[non_padded_sentence, padded_sentence]	)








import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin

class     _SCREAMING_SNAKE_CASE       (			_a		,   unittest.TestCase      ):
	snake_case__							:     Optional[Any]     	=  TransfoXLTokenizer
	snake_case__							:     List[Any]     	=  False
	snake_case__							:     Tuple     	=  False





	def 						_A (		self				:					str	):
		super().setUp()

		UpperCamelCase     :Dict          =	[
		    """<unk>""",
		    """[CLS]""",
		    """[SEP]""",
		    """want""",
		    """unwanted""",
		    """wa""",
		    """un""",
		    """running""",
		    """,""",
		    """low""",
		    """l""",
		]
		UpperCamelCase     :str          =	os.path.join(self.tmpdirname ,  VOCAB_FILES_NAMES["""vocab_file"""]	)
		with open(self.vocab_file ,  """w""" ,  encoding="""utf-8"""	) as vocab_writer:
			vocab_writer.write("""""".join([x + """\n""" for x in vocab_tokens]	)	)





	def 						_A (		self				:					List[str] ,  **__lowerCamelCase				:					Any	):
		UpperCamelCase     :Any          =	True
		return TransfoXLTokenizer.from_pretrained(self.tmpdirname ,  **__lowerCamelCase	)





	def 						_A (		self				:					Any ,  __lowerCamelCase				:					int	):
		UpperCamelCase     :List[Any]          =	"""<unk> UNwanted , running"""
		UpperCamelCase     :int          =	"""<unk> unwanted, running"""
		return input_text, output_text





	def 						_A (		self				:					Tuple	):
		UpperCamelCase     :List[str]          =	TransfoXLTokenizer(vocab_file=self.vocab_file ,  lower_case=__lowerCamelCase	)

		UpperCamelCase     :Any          =	tokenizer.tokenize("""<unk> UNwanted , running"""	)
		self.assertListEqual(__lowerCamelCase ,  ["""<unk>""", """unwanted""", """,""", """running"""]	)

		self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCamelCase	) ,  [0, 4, 8, 7]	)





	def 						_A (		self				:					Optional[Any]	):
		UpperCamelCase     :List[Any]          =	TransfoXLTokenizer(lower_case=__lowerCamelCase	)

		self.assertListEqual(
		    tokenizer.tokenize(""" \tHeLLo ! how  \n Are yoU ?  """	) ,  ["""hello""", """!""", """how""", """are""", """you""", """?"""]	)





	def 						_A (		self				:					Union[str, Any]	):
		UpperCamelCase     :int          =	TransfoXLTokenizer(lower_case=__lowerCamelCase	)

		self.assertListEqual(
		    tokenizer.tokenize(""" \tHeLLo ! how  \n Are yoU ?  """	) ,  ["""HeLLo""", """!""", """how""", """Are""", """yoU""", """?"""]	)





	def 						_A (		self				:					Tuple	):
		UpperCamelCase     :Any          =	TransfoXLTokenizer(lower_case=__lowerCamelCase	)
		UpperCamelCase     :Optional[int]          =	"""Hello (bracket) and side-scrolled [and] Henry's $5,000 with 3.34 m. What's up!?"""
		UpperCamelCase     :Optional[int]          =	[
		    """Hello""",
		    """(""",
		    """bracket""",
		    """)""",
		    """and""",
		    """side""",
		    """@-@""",
		    """scrolled""",
		    """[""",
		    """and""",
		    """]""",
		    """Henry""",
		    """'s""",
		    """$""",
		    """5""",
		    """@,@""",
		    """000""",
		    """with""",
		    """3""",
		    """@.@""",
		    """34""",
		    """m""",
		    """.""",
		    """What""",
		    """'s""",
		    """up""",
		    """!""",
		    """?""",
		]

		self.assertListEqual(tokenizer.tokenize(__lowerCamelCase	) ,  __lowerCamelCase	)

		self.assertEqual(tokenizer.convert_tokens_to_string(__lowerCamelCase	) ,  __lowerCamelCase	)





	def 						_A (		self				:					List[Any]	):
		UpperCamelCase     :Any          =	self.get_tokenizer()
		UpperCamelCase     :List[str]          =	len(__lowerCamelCase	)

		tokenizer.add_tokens(["""new1""", """new2"""]	)
		tokenizer.move_added_token("""new1""" ,  1	)

		# Check that moved token is not copied (duplicate)
		self.assertEqual(len(__lowerCamelCase	) ,  original_len + 2	)
		# Check that token is moved to specified id
		self.assertEqual(tokenizer.encode("""new1"""	) ,  [1]	)
		self.assertEqual(tokenizer.decode([1]	) ,  """new1"""	)
