






from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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 TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel




@require_tf
class 				__A     :





				"""simple docstring"""







				UpperCamelCase__ :      List[Any]			 =PegasusConfig
				UpperCamelCase__ :      Optional[int]			 ={}
				UpperCamelCase__ :      Any			 ="gelu"


				def __init__( self							,  lowerCamelCase__							,  lowerCamelCase__=13							,  lowerCamelCase__=7							,  lowerCamelCase__=True							,  lowerCamelCase__=False							,  lowerCamelCase__=99							,  lowerCamelCase__=32							,  lowerCamelCase__=2							,  lowerCamelCase__=4							,  lowerCamelCase__=37							,  lowerCamelCase__=0.1							,  lowerCamelCase__=0.1							,  lowerCamelCase__=40							,  lowerCamelCase__=2							,  lowerCamelCase__=1							,  lowerCamelCase__=0							,  ):




									"""simple docstring"""

									__UpperCamelCase      :					str       		=parent
									__UpperCamelCase      :					str       		=batch_size
									__UpperCamelCase      :					Any       		=seq_length
									__UpperCamelCase      :					Optional[Any]       		=is_training
									__UpperCamelCase      :					Dict       		=use_labels
									__UpperCamelCase      :					List[Any]       		=vocab_size
									__UpperCamelCase      :					str       		=hidden_size
									__UpperCamelCase      :					List[str]       		=num_hidden_layers
									__UpperCamelCase      :					str       		=num_attention_heads
									__UpperCamelCase      :					Optional[int]       		=intermediate_size

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


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[Any]       		=ids_tensor([self.batch_size, self.seq_length - 1]							,  self.vocab_size    )
									__UpperCamelCase      :					Any       		=tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size    )							,  1    )
									__UpperCamelCase      :					int       		=tf.concat([input_ids, eos_tensor]							,  axis=1    )

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

									__UpperCamelCase      :					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							,  )
									__UpperCamelCase      :					List[str]       		=prepare_pegasus_inputs_dict(UpperCAmelCase__							,  UpperCAmelCase__							,  UpperCAmelCase__    )
									return config, inputs_dict







				def       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__    ):




									"""simple docstring"""

									__UpperCamelCase      :					Tuple       		=TFPegasusModel(config=UpperCAmelCase__    ).get_decoder()
									__UpperCamelCase      :					str       		=inputs_dict['input_ids']

									__UpperCamelCase      :					str       		=input_ids[:1, :]
									__UpperCamelCase      :					Tuple       		=inputs_dict['attention_mask'][:1, :]
									__UpperCamelCase      :					List[Any]       		=inputs_dict['head_mask']
									__UpperCamelCase      :					Optional[Any]       		=1

									# first forward pass
									__UpperCamelCase      :					Union[str, Any]       		=model(UpperCAmelCase__							,  attention_mask=UpperCAmelCase__							,  head_mask=UpperCAmelCase__							,  use_cache=UpperCAmelCase__    )

									__UpperCamelCase		,				__UpperCamelCase      :					Union[str, Any]       		=outputs.to_tuple()

									# create hypothetical next token and extent to next_input_ids
									__UpperCamelCase      :					Any       		=ids_tensor((self.batch_size, 3)							,  config.vocab_size    )
									__UpperCamelCase      :					List[str]       		=tf.cast(ids_tensor((self.batch_size, 3)							,  2    )							,  tf.inta    )

									# append to next input_ids and
									__UpperCamelCase      :					Dict       		=tf.concat([input_ids, next_tokens]							,  axis=-1    )
									__UpperCamelCase      :					Any       		=tf.concat([attention_mask, next_attn_mask]							,  axis=-1    )

									__UpperCamelCase      :					int       		=model(UpperCAmelCase__							,  attention_mask=UpperCAmelCase__    )[0]
									__UpperCamelCase      :					List[Any]       		=model(UpperCAmelCase__							,  attention_mask=UpperCAmelCase__							,  past_key_values=UpperCAmelCase__    )[0]

									self.parent.assertEqual(next_tokens.shape[1]							,  output_from_past.shape[1]    )

									# select random slice
									__UpperCamelCase      :					Optional[int]       		=int(ids_tensor((1,)							,  output_from_past.shape[-1]    )    )
									__UpperCamelCase      :					int       		=output_from_no_past[:, -3:, random_slice_idx]
									__UpperCamelCase      :					Optional[Any]       		=output_from_past[:, :, random_slice_idx]

									# test that outputs are equal for slice
									tf.debugging.assert_near(UpperCAmelCase__							,  UpperCAmelCase__							,  rtol=1E-3    )






def 							A     (       a_							,a_							,a_							,a_=None							,a_=None							,a_=None							,a_=None							,a_=None							,)     ->						Tuple:


					if attention_mask is None:
										__UpperCamelCase      :					Dict       		=tf.cast(tf.math.not_equal(UpperCamelCase_							,config.pad_token_id					)							,tf.inta					)
					if decoder_attention_mask is None:
										__UpperCamelCase      :					Optional[int]       		=tf.concat(
										    [
										        tf.ones(decoder_input_ids[:, :1].shape							,dtype=tf.inta					),
										        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]							,config.pad_token_id					)							,tf.inta					),
										    ]							,axis=-1							,)
					if head_mask is None:
										__UpperCamelCase      :					Union[str, Any]       		=tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
					if decoder_head_mask is None:
										__UpperCamelCase      :					Any       		=tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
					if cross_attn_head_mask is None:
										__UpperCamelCase      :					Optional[int]       		=tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
					return {
					    "input_ids": input_ids,
					    "decoder_input_ids": decoder_input_ids,
					    "attention_mask": attention_mask,
					    "decoder_attention_mask": decoder_attention_mask,
					    "head_mask": head_mask,
					    "decoder_head_mask": decoder_head_mask,
					    "cross_attn_head_mask": cross_attn_head_mask,
					}




@require_tf
class 				__A     (			a      ,     a      ,     unittest.TestCase ):





				"""simple docstring"""







				UpperCamelCase__ :      Dict			 =(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
				UpperCamelCase__ :      str			 =(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
				UpperCamelCase__ :      Optional[int]			 =(
				    {
				        "conversational": TFPegasusForConditionalGeneration,
				        "feature-extraction": TFPegasusModel,
				        "summarization": TFPegasusForConditionalGeneration,
				        "text2text-generation": TFPegasusForConditionalGeneration,
				        "translation": TFPegasusForConditionalGeneration,
				    }
				    if is_tf_available()
				    else {}
				)
				UpperCamelCase__ :      List[Any]			 =True
				UpperCamelCase__ :      Union[str, Any]			 =False
				UpperCamelCase__ :      Dict			 =False


				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					List[str]       		=TFPegasusModelTester(self    )
									__UpperCamelCase      :					Optional[int]       		=ConfigTester(self							,  config_class=UpperCAmelCase__    )


				def       __lowercase							( self    ):




									"""simple docstring"""

									self.config_tester.run_common_tests()







				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Tuple       		=self.model_tester.prepare_config_and_inputs_for_common()
									self.model_tester.check_decoder_model_past_large_inputs(*UpperCAmelCase__    )




@require_sentencepiece
@require_tokenizers
@require_tf
class 				__A     (			unittest.TestCase ):





				"""simple docstring"""







				UpperCamelCase__ :      Tuple			 =[
				    " 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!\" ",
				]
				UpperCamelCase__ :      List[str]			 =[
				    "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to"
				    " reduce the risk of wildfires.",
				    "N-Dubz have revealed they\'re \"grateful\" to have been nominated for four Mobo Awards.",
				]  # differs slightly from pytorch, likely due to numerical differences in linear layers
				UpperCamelCase__ :      Dict			 ="google/pegasus-xsum"


				@cached_property
				def       __lowercase							( self    ):




									"""simple docstring"""

									return AutoTokenizer.from_pretrained(self.model_name    )


				@cached_property
				def       __lowercase							( self    ):




									"""simple docstring"""

									__UpperCamelCase      :					Union[str, Any]       		=TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name    )
									return model


				def       __lowercase							( self							,  **lowerCamelCase__    ):




									"""simple docstring"""

									__UpperCamelCase      :					Optional[Any]       		=self.translate_src_text(**UpperCAmelCase__    )
									assert self.expected_text == generated_words


				def       __lowercase							( self							,  **lowerCamelCase__    ):




									"""simple docstring"""

									__UpperCamelCase      :					Union[str, Any]       		=self.tokenizer(self.src_text							,  **UpperCAmelCase__							,  padding=UpperCAmelCase__							,  return_tensors='tf'    )
									__UpperCamelCase      :					Optional[Any]       		=self.model.generate(
									    model_inputs.input_ids							,  attention_mask=model_inputs.attention_mask							,  num_beams=2							,  use_cache=UpperCAmelCase__							,  )
									__UpperCamelCase      :					Tuple       		=self.tokenizer.batch_decode(generated_ids.numpy()							,  skip_special_tokens=UpperCAmelCase__    )
									return generated_words







				@slow
				def       __lowercase							( self    ):




									"""simple docstring"""

									self._assert_generated_batch_equal_expected()




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







 __UpperCAmelCase	:					Tuple   		=	XGLMConfig
 __UpperCAmelCase	:					Optional[Any]   		=	{}
 __UpperCAmelCase	:					Union[str, Any]   		=	"gelu"


 def __init__(			self							:			Optional[int],					UpperCAmelCase__							:			List[str],					UpperCAmelCase__							:			Optional[int]=1_4,					UpperCAmelCase__							:			str=7,					UpperCAmelCase__							:			Optional[Any]=True,					UpperCAmelCase__							:			List[Any]=True,					UpperCAmelCase__							:			int=True,					UpperCAmelCase__							:			List[str]=9_9,					UpperCAmelCase__							:			Union[str, Any]=3_2,					UpperCAmelCase__							:			Union[str, Any]=2,					UpperCAmelCase__							:			Union[str, Any]=4,					UpperCAmelCase__							:			Tuple=3_7,					UpperCAmelCase__							:			List[Any]="gelu",					UpperCAmelCase__							:			List[str]=0.1,					UpperCAmelCase__							:			Optional[int]=0.1,					UpperCAmelCase__							:			Tuple=5_1_2,					UpperCAmelCase__							:			Optional[Any]=0.02,					):
    __lowercase								=						parent
    __lowercase								=						batch_size
    __lowercase								=						seq_length
    __lowercase								=						is_training
    __lowercase								=						use_input_mask
    __lowercase								=						use_labels
    __lowercase								=						vocab_size
    __lowercase								=						d_model
    __lowercase								=						num_hidden_layers
    __lowercase								=						num_attention_heads
    __lowercase								=						ffn_dim
    __lowercase								=						activation_function
    __lowercase								=						activation_dropout
    __lowercase								=						attention_dropout
    __lowercase								=						max_position_embeddings
    __lowercase								=						initializer_range
    __lowercase								=						None
    __lowercase								=						0
    __lowercase								=						2
    __lowercase								=						1


 def 					_lowercase (			self							:			Union[str, Any]	):
    return XGLMConfig.from_pretrained("facebook/xglm-564M"	)


 def 					_lowercase (			self							:			Tuple	):
    __lowercase								=						tf.clip_by_value(
        ids_tensor([self.batch_size, self.seq_length],					self.vocab_size	),					clip_value_min=0,					clip_value_max=3	)

    __lowercase								=						None
    if self.use_input_mask:
       __lowercase								=						random_attention_mask([self.batch_size, self.seq_length]	)

    __lowercase								=						self.get_config()

    __lowercase								=						floats_tensor([self.num_hidden_layers, self.num_attention_heads],					2	)

    return (
        config,
        input_ids,
        input_mask,
        head_mask,
    )


 def 					_lowercase (			self							:			List[Any]	):
    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=UpperCAmelCase__,					bos_token_id=self.bos_token_id,					eos_token_id=self.eos_token_id,					pad_token_id=self.pad_token_id,					return_dict=UpperCAmelCase__,					)



 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						self.prepare_config_and_inputs()

    (
        (
        __lowercase
    )		,(
        __lowercase
    )		,(
        __lowercase
    )		,(
        __lowercase
    )		,
    )								=						config_and_inputs

    __lowercase								=						{
        "input_ids": input_ids,
        "head_mask": head_mask,
    }

    return config, inputs_dict







@require_tf
class 					_lowerCAmelCase  (	lowercase     ,lowercase     ,unittest.TestCase   ):







 """simple docstring"""







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


 def 					_lowercase (			self							:			Optional[Any]	):
    __lowercase								=						TFXGLMModelTester(self	)
    __lowercase								=						ConfigTester(self,					config_class=UpperCAmelCase__,					n_embd=3_7	)


 def 					_lowercase (			self							:			Any	):
    self.config_tester.run_common_tests()


 @slow
 def 					_lowercase (			self							:			List[str]	):
    for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __lowercase								=						TFXGLMModel.from_pretrained(UpperCAmelCase__	)
       self.assertIsNotNone(UpperCAmelCase__	)



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







@require_tf
class 					_lowerCAmelCase  (	unittest.TestCase   ):







 """simple docstring"""







 @slow
 def 					_lowercase (			self							:			Dict,					UpperCAmelCase__							:			Optional[int]=True	):
    __lowercase								=						TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)
    __lowercase								=						tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]],					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
    __lowercase								=						[2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1]
    # fmt: on
    __lowercase								=						model.generate(UpperCAmelCase__,					do_sample=UpperCAmelCase__,					num_beams=1	)
    if verify_outputs:
       self.assertListEqual(output_ids[0].numpy().tolist(),					UpperCAmelCase__	)


 @slow
 def 					_lowercase (			self							:			List[Any]	):
    __lowercase								=						XGLMTokenizer.from_pretrained("facebook/xglm-564M"	)
    __lowercase								=						TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)

    tf.random.set_seed(0	)
    __lowercase								=						tokenizer("Today is a nice day and",					return_tensors="tf"	)
    __lowercase								=						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"	):
       __lowercase								=						model.generate(UpperCAmelCase__,					do_sample=UpperCAmelCase__,					seed=[7, 0]	)
    __lowercase								=						tokenizer.decode(output_ids[0],					skip_special_tokens=UpperCAmelCase__	)

    __lowercase								=						(
        "Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"
    )
    self.assertEqual(UpperCAmelCase__,					UpperCAmelCase__	)



 @slow
 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						TFXGLMForCausalLM.from_pretrained("facebook/xglm-564M"	)
    __lowercase								=						XGLMTokenizer.from_pretrained("facebook/xglm-564M"	)

    __lowercase								=						"left"

    # use different length sentences to test batching
    __lowercase								=						[
        "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",
    ]

    __lowercase								=						tokenizer(UpperCAmelCase__,					return_tensors="tf",					padding=UpperCAmelCase__	)
    __lowercase								=						inputs["input_ids"]

    __lowercase								=						model.generate(input_ids=UpperCAmelCase__,					attention_mask=inputs["attention_mask"],					max_new_tokens=1_2	)

    __lowercase								=						tokenizer(sentences[0],					return_tensors="tf"	).input_ids
    __lowercase								=						model.generate(input_ids=UpperCAmelCase__,					max_new_tokens=1_2	)

    __lowercase								=						tokenizer(sentences[1],					return_tensors="tf"	).input_ids
    __lowercase								=						model.generate(input_ids=UpperCAmelCase__,					max_new_tokens=1_2	)

    __lowercase								=						tokenizer.batch_decode(UpperCAmelCase__,					skip_special_tokens=UpperCAmelCase__	)
    __lowercase								=						tokenizer.decode(output_non_padded[0],					skip_special_tokens=UpperCAmelCase__	)
    __lowercase								=						tokenizer.decode(output_padded[0],					skip_special_tokens=UpperCAmelCase__	)

    __lowercase								=						[
        "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(UpperCAmelCase__,					UpperCAmelCase__	)
    self.assertListEqual(UpperCAmelCase__,					[non_padded_sentence, padded_sentence]	)




