
from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


lowerCamelCase_  :	Optional[Any] 				=					logging.get_logger(__name__)







def     A__   (  lowerCamelCase  )					->		List[int]:
				if isinstance(lowerCamelCase       ,      np.ndarray  ):
								return list(tensor.shape  )

				UpperCamelCase_:							Union[str, Any]		=  tf.shape(lowerCamelCase  )

				if tensor.shape == tf.TensorShape(lowerCamelCase  ):
								return dynamic

				UpperCamelCase_:							Tuple		=  tensor.shape.as_list()

				return [dynamic[i] if s is None else s for i, s in enumerate(lowerCamelCase  )]







def     A__   (  lowerCamelCase       ,      lowerCamelCase = None       ,      lowerCamelCase = None  )					->		tf.Tensor:
				return tf.nn.softmax(logits=logits + 1E-9       ,      axis=lowerCamelCase       ,      name=lowerCamelCase  )







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase=1E-5       ,      lowerCamelCase=-1  )					->		List[str]:
				# This is a very simplified functional layernorm, designed to duplicate
				# the functionality of PyTorch nn.functional.layer_norm when this is needed to port
				# models in Transformers.

				if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCamelCase       ,      lowerCamelCase  ):
								raise NotImplementedError("""Only 1D weight and bias tensors are supported for now, with only a single axis."""  )

				# Get mean and variance on the axis to be normalized
				UpperCamelCase_,				UpperCamelCase_:							List[str]		=  tf.nn.moments(lowerCamelCase       ,      axes=[axis]       ,      keepdims=lowerCamelCase  )

				if axis != -1:
								# Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
								# on every dimension except axis
								UpperCamelCase_:							Union[str, Any]		=  [1] * inputs.shape.rank
								UpperCamelCase_:							str		=  shape_list(lowerCamelCase  )[axis]
								UpperCamelCase_:							Optional[int]		=  tf.reshape(lowerCamelCase       ,      lowerCamelCase  )
								UpperCamelCase_:							Tuple		=  tf.reshape(lowerCamelCase       ,      lowerCamelCase  )

				# Compute layer normalization using the batch_normalization
				# function.
				UpperCamelCase_:							int		=  tf.nn.batch_normalization(
				    lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      offset=lowerCamelCase       ,      scale=lowerCamelCase       ,      variance_epsilon=lowerCamelCase       ,      )
				return outputs







def     A__   (  lowerCamelCase       ,      lowerCamelCase=0       ,      lowerCamelCase=-1  )					->		Any:
				# Replicates the behavior of torch.flatten in TF

				# If end_dim or start_dim is negative, count them from the end
				if end_dim < 0:
								end_dim += input.shape.rank
				if start_dim < 0:
								start_dim += input.shape.rank

				if start_dim == end_dim:
								return input

				UpperCamelCase_:							List[str]		=  tf.shape(lowerCamelCase  )
				UpperCamelCase_:							str		=  tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]  )
				UpperCamelCase_:							int		=  tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]       ,      axis=0  )
				return tf.reshape(lowerCamelCase       ,      lowerCamelCase  )







def     A__   (  lowerCamelCase  )					->		tf.Tensor:
				if not isinstance(lowerCamelCase       ,      tf.Tensor  ):
								UpperCamelCase_:							List[Any]		=  tf.convert_to_tensor(lowerCamelCase  )  # Catches stray NumPy inputs
				if encoder_attention_mask.shape.rank == 3:
								UpperCamelCase_:							int		=  encoder_attention_mask[:, None, :, :]
				if encoder_attention_mask.shape.rank == 2:
								UpperCamelCase_:							Optional[Any]		=  encoder_attention_mask[:, None, None, :]
				# T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
				# Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
				# /transformer/transformer_layers.py#L270
				# encoder_extended_attention_mask = (encoder_extended_attention_mask ==
				# encoder_extended_attention_mask.transpose(-1, -2))
				UpperCamelCase_:							Dict		=  (
				    tf.cast(1       ,      encoder_attention_mask.dtype  ) - encoder_extended_attention_mask
				) * encoder_extended_attention_mask.dtype.min

				return encoder_extended_attention_mask







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase = "input_ids"  )					->		None:
				tf.debugging.assert_less(
				    lowerCamelCase       ,      tf.cast(lowerCamelCase       ,      dtype=tensor.dtype  )       ,      message=(
				        F'''The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCamelCase  )}) must be smaller than the embedding '''
				        F'''layer\'s input dimension ({embed_dim}). The likely cause is some problem at tokenization time.'''
				    )       ,      )







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase  )					->		Optional[Any]:
				UpperCamelCase_:							List[Any]		=  6_45_12
				# Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
				# because in that case even chunking the array would not make the saving
				# possible.
				UpperCamelCase_:							Union[str, Any]		=  [x for x in data if len(lowerCamelCase  ) > HDF5_OBJECT_HEADER_LIMIT]

				# Expecting this to never be true.
				if bad_attributes:
								raise RuntimeError(
								    """The following attributes cannot be saved to HDF5 file because """
								    F'''they are larger than {HDF5_OBJECT_HEADER_LIMIT} '''
								    F'''bytes: {bad_attributes}'''  )

				UpperCamelCase_:							List[Any]		=  np.asarray(lowerCamelCase  )

				UpperCamelCase_:							Optional[Any]		=  1
				UpperCamelCase_:							Tuple		=  np.array_split(lowerCamelCase       ,      lowerCamelCase  )

				# This will never loop forever thanks to the test above.
				while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data  ):
								num_chunks += 1
								UpperCamelCase_:							Tuple		=  np.array_split(lowerCamelCase       ,      lowerCamelCase  )

				if num_chunks > 1:
								for chunk_id, chunk_data in enumerate(lowerCamelCase  ):
												UpperCamelCase_:							Optional[int]		=  chunk_data
				else:
								UpperCamelCase_:							Tuple		=  data







def     A__   (  lowerCamelCase       ,      lowerCamelCase  )					->		Optional[int]:
				if name in group.attrs:
								UpperCamelCase_:							Optional[Any]		=  [n.decode("""utf8"""  ) if hasattr(lowerCamelCase       ,      """decode"""  ) else n for n in group.attrs[name]]
				else:
								UpperCamelCase_:							List[Any]		=  []
								UpperCamelCase_:							Tuple		=  0
								while "%s%d" % (name, chunk_id) in group.attrs:
												data.extend(
												    [n.decode("""utf8"""  ) if hasattr(lowerCamelCase       ,      """decode"""  ) else n for n in group.attrs["""%s%d""" % (name, chunk_id)]]  )
												chunk_id += 1
				return data







def     A__   (  lowerCamelCase  )					->		Dict:

				def _expand_single_ad_tensor(lowerCamelCase  ):
								if isinstance(lowerCamelCase       ,      tf.Tensor  ) and t.shape.rank == 1:
												return tf.expand_dims(lowerCamelCase       ,      axis=-1  )
								return t

				return tf.nest.map_structure(_expand_single_ad_tensor       ,      lowerCamelCase  )








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     _UpperCamelCase			:






			'''simple docstring'''

			__UpperCamelCase :  str    =	PegasusConfig
			__UpperCamelCase :  str    =	{}
			__UpperCamelCase :  Optional[Any]    =	"""gelu"""

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

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

			def  lowerCAmelCase__		(    self	:    str ):
							UpperCamelCase_:							List[Any]		=  ids_tensor([self.batch_size, self.seq_length - 1]  ,		self.vocab_size )
							UpperCamelCase_:							int		=  tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size )  ,		1 )
							UpperCamelCase_:							List[Any]		=  tf.concat([input_ids, eos_tensor]  ,		axis=1 )

							UpperCamelCase_:							List[Any]		=  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(snake_case_  ,		snake_case_  ,		snake_case_ )
							return config, inputs_dict




			def  lowerCAmelCase__		(    self	:    Any  ,		snake_case_	:    List[str]  ,		snake_case_	:    Dict ):
							UpperCamelCase_:							Any		=  TFPegasusModel(config=snake_case_ ).get_decoder()
							UpperCamelCase_:							Any		=  inputs_dict["""input_ids"""]

							UpperCamelCase_:							int		=  input_ids[:1, :]
							UpperCamelCase_:							List[str]		=  inputs_dict["""attention_mask"""][:1, :]
							UpperCamelCase_:							Tuple		=  inputs_dict["""head_mask"""]
							UpperCamelCase_:							int		=  1

							# first forward pass
							UpperCamelCase_:							Dict		=  model(snake_case_  ,		attention_mask=snake_case_  ,		head_mask=snake_case_  ,		use_cache=snake_case_ )

							UpperCamelCase_,				UpperCamelCase_:							List[str]		=  outputs.to_tuple()

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

							# append to next input_ids and
							UpperCamelCase_:							Union[str, Any]		=  tf.concat([input_ids, next_tokens]  ,		axis=-1 )
							UpperCamelCase_:							Optional[int]		=  tf.concat([attention_mask, next_attn_mask]  ,		axis=-1 )

							UpperCamelCase_:							List[Any]		=  model(snake_case_  ,		attention_mask=snake_case_ )[0]
							UpperCamelCase_:							Dict		=  model(snake_case_  ,		attention_mask=snake_case_  ,		past_key_values=snake_case_ )[0]

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

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

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







def     A__   (  lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase       ,      lowerCamelCase=None       ,      lowerCamelCase=None       ,      lowerCamelCase=None       ,      lowerCamelCase=None       ,      lowerCamelCase=None       ,      )					->		Optional[int]:
				if attention_mask is None:
								UpperCamelCase_:							Union[str, Any]		=  tf.cast(tf.math.not_equal(lowerCamelCase       ,      config.pad_token_id  )       ,      tf.inta  )
				if decoder_attention_mask is None:
								UpperCamelCase_:							str		=  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_:							Tuple		=  tf.ones((config.encoder_layers, config.encoder_attention_heads)  )
				if decoder_head_mask is None:
								UpperCamelCase_:							Dict		=  tf.ones((config.decoder_layers, config.decoder_attention_heads)  )
				if cross_attn_head_mask is None:
								UpperCamelCase_:							str		=  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     _UpperCamelCase			(   _A       ,    _A       ,    unittest.TestCase					):






			'''simple docstring'''

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

			def  lowerCAmelCase__		(    self	:    Dict ):
							UpperCamelCase_:							Tuple		=  TFPegasusModelTester(self )
							UpperCamelCase_:							List[Any]		=  ConfigTester(self  ,		config_class=snake_case_ )

			def  lowerCAmelCase__		(    self	:    Dict ):
							self.config_tester.run_common_tests()




			def  lowerCAmelCase__		(    self	:    Optional[int] ):
							UpperCamelCase_:							Union[str, Any]		=  self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_decoder_model_past_large_inputs(*snake_case_ )




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






			'''simple docstring'''

			__UpperCamelCase :  Union[str, Any]    =	[
			    """ 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 :  Optional[int]    =	[
			    """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 :  Union[str, Any]    =	"""google/pegasus-xsum"""

			@cached_property
			def  lowerCAmelCase__		(    self	:    Dict ):
							return AutoTokenizer.from_pretrained(self.model_name )

			@cached_property
			def  lowerCAmelCase__		(    self	:    int ):
							UpperCamelCase_:							List[Any]		=  TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name )
							return model

			def  lowerCAmelCase__		(    self	:    Union[str, Any]  ,		**snake_case_	:    Optional[int] ):
							UpperCamelCase_:							str		=  self.translate_src_text(**snake_case_ )
							assert self.expected_text == generated_words

			def  lowerCAmelCase__		(    self	:    Optional[Any]  ,		**snake_case_	:    int ):
							UpperCamelCase_:							Tuple		=  self.tokenizer(self.src_text  ,		**snake_case_  ,		padding=snake_case_  ,		return_tensors="""tf""" )
							UpperCamelCase_:							Tuple		=  self.model.generate(
							    model_inputs.input_ids  ,		attention_mask=model_inputs.attention_mask  ,		num_beams=2  ,		use_cache=snake_case_  ,		)
							UpperCamelCase_:							Tuple		=  self.tokenizer.batch_decode(generated_ids.numpy()  ,		skip_special_tokens=snake_case_ )
							return generated_words




			@slow
			def  lowerCAmelCase__		(    self	:    Optional[Any] ):
							self._assert_generated_batch_equal_expected()






