
'''simple docstring'''







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				:				Optional[int]   =					PegasusConfig
  __UpperCAmelCase				:				Tuple   =					{}
  __UpperCAmelCase				:				Any   =					'''gelu'''


  def __init__(		self      :     int							,_a      :     Union[str, Any]							,_a      :     List[Any]=13							,_a      :     Optional[Any]=7							,_a      :     Tuple=True							,_a      :     Any=False							,_a      :     List[str]=99							,_a      :     Tuple=32							,_a      :     Any=2							,_a      :     List[str]=4							,_a      :     List[str]=37							,_a      :     Optional[int]=0.1							,_a      :     str=0.1							,_a      :     List[Any]=40							,_a      :     Optional[int]=2							,_a      :     Tuple=1							,_a      :     Any=0							,):


     '''simple docstring'''






     _a				:	str			=   parent
     _a				:	List[str]			=   batch_size
     _a				:	Union[str, Any]			=   seq_length
     _a				:	Dict			=   is_training
     _a				:	int			=   use_labels
     _a				:	str			=   vocab_size
     _a				:	List[Any]			=   hidden_size
     _a				:	Union[str, Any]			=   num_hidden_layers
     _a				:	List[str]			=   num_attention_heads
     _a				:	int			=   intermediate_size

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


  def   __lowercase		(		self      :     str       ):


     '''simple docstring'''






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

     _a				:	Dict			=   ids_tensor([self.batch_size, self.seq_length]							,self.vocab_size       )

     _a				:	Optional[Any]			=   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				:	str			=   prepare_pegasus_inputs_dict(a_							,a_							,a_       )
     return config, inputs_dict


  def   __lowercase		(		self      :     int							,_a      :     Dict							,_a      :     str       ):


     '''simple docstring'''






     _a				:	List[str]			=   TFPegasusModel(config=a_       ).get_decoder()
     _a				:	int			=   inputs_dict["""input_ids"""]

     _a				:	Optional[int]			=   input_ids[:1, :]
     _a				:	List[str]			=   inputs_dict["""attention_mask"""][:1, :]
     _a				:	Union[str, Any]			=   inputs_dict["""head_mask"""]
     _a				:	List[str]			=   1

     # first forward pass
     _a				:	Optional[Any]			=   model(a_							,attention_mask=a_							,head_mask=a_							,use_cache=a_       )

     _a				:	Dict			=   outputs.to_tuple()

     # create hypothetical next token and extent to next_input_ids
     _a				:	Dict			=   ids_tensor((self.batch_size, 3)							,config.vocab_size       )
     _a				:	int			=   tf.cast(ids_tensor((self.batch_size, 3)							,2       )							,tf.inta       )

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

     _a				:	Union[str, Any]			=   model(a_							,attention_mask=a_       )[0]
     _a				:	List[str]			=   model(a_							,attention_mask=a_							,past_key_values=a_       )[0]

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

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

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





def 					UpperCAmelCase_		(__a      :    Tuple ,	__a      :    Optional[Any] ,	__a      :    Optional[int] ,	__a      :    Optional[Any]=None ,	__a      :    str=None ,	__a      :    int=None ,	__a      :    List[Any]=None ,	__a      :    Union[str, Any]=None ,	):






   """simple docstring"""

   if attention_mask is None:
      _a				:	List[Any]			=   tf.cast(tf.math.not_equal(lowerCAmelCase_ ,	config.pad_token_id ) ,	tf.inta )
   if decoder_attention_mask is None:
      _a				:	Dict			=   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:
      _a				:	List[Any]			=   tf.ones((config.encoder_layers, config.encoder_attention_heads) )
   if decoder_head_mask is None:
      _a				:	List[str]			=   tf.ones((config.decoder_layers, config.decoder_attention_heads) )
   if cross_attn_head_mask is None:
      _a				:	List[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__	( _lowerCamelCase    ,				_lowerCamelCase    ,				unittest.TestCase	):





  """simple docstring"""

  __UpperCAmelCase				:				Tuple   =					(TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
  __UpperCAmelCase				:				Any   =					(TFPegasusForConditionalGeneration,) if is_tf_available() else ()
  __UpperCAmelCase				:				List[Any]   =					(
      {
          '''conversational''': TFPegasusForConditionalGeneration,
          '''feature-extraction''': TFPegasusModel,
          '''summarization''': TFPegasusForConditionalGeneration,
          '''text2text-generation''': TFPegasusForConditionalGeneration,
          '''translation''': TFPegasusForConditionalGeneration,
      }
      if is_tf_available()
      else {}
  )
  __UpperCAmelCase				:				Optional[Any]   =					True
  __UpperCAmelCase				:				int   =					False
  __UpperCAmelCase				:				Optional[Any]   =					False


  def   __lowercase		(		self      :     Any       ):


     '''simple docstring'''






     _a				:	str			=   TFPegasusModelTester(self       )
     _a				:	Optional[int]			=   ConfigTester(self							,config_class=a_       )


  def   __lowercase		(		self      :     Tuple       ):


     '''simple docstring'''






     self.config_tester.run_common_tests()


  def   __lowercase		(		self      :     List[str]       ):


     '''simple docstring'''






     _a				:	Union[str, Any]			=   self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*a_       )







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





  """simple docstring"""

  __UpperCAmelCase				:				int   =					[
      ''' 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				:				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				:				Optional[Any]   =					'''google/pegasus-xsum'''


  @cached_property
  def   __lowercase		(		self      :     int       ):


     '''simple docstring'''






     return AutoTokenizer.from_pretrained(self.model_name       )


  @cached_property
  def   __lowercase		(		self      :     Dict       ):


     '''simple docstring'''






     _a				:	List[Any]			=   TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name       )
     return model


  def   __lowercase		(		self      :     Tuple							,**_a      :     Any       ):


     '''simple docstring'''






     _a				:	Any			=   self.translate_src_text(**a_       )
     assert self.expected_text == generated_words


  def   __lowercase		(		self      :     str							,**_a      :     List[Any]       ):


     '''simple docstring'''






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


  @slow
  def   __lowercase		(		self      :     List[Any]       ):


     '''simple docstring'''






     self._assert_generated_batch_equal_expected()








'''simple docstring'''






import inspect
import os
import re

from transformers.configuration_utils import PretrainedConfig
from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
A_							: List[str]						 =	"""src/transformers"""


# This is to make sure the transformers module imported is the one in the repo.
A_							: Optional[Any]						 =	direct_transformers_import(PATH_TO_TRANSFORMERS)

A_							: Union[str, Any]						 =	transformers.models.auto.configuration_auto.CONFIG_MAPPING

A_							: Dict						 =	{
    # used to compute the property `self.chunk_length`
    """EncodecConfig""": ["""overlap"""],
    # used as `self.bert_model = BertModel(config, ...)`
    """DPRConfig""": True,
    # not used in modeling files, but it's an important information
    """FSMTConfig""": ["""langs"""],
    # used internally in the configuration class file
    """GPTNeoConfig""": ["""attention_types"""],
    # used internally in the configuration class file
    """EsmConfig""": ["""is_folding_model"""],
    # used during training (despite we don't have training script for these models yet)
    """Mask2FormerConfig""": ["""ignore_value"""],
    # `ignore_value` used during training (despite we don't have training script for these models yet)
    # `norm` used in conversion script (despite not using in the modeling file)
    """OneFormerConfig""": ["""ignore_value""", """norm"""],
    # used during preprocessing and collation, see `collating_graphormer.py`
    """GraphormerConfig""": ["""spatial_pos_max"""],
    # used internally in the configuration class file
    """T5Config""": ["""feed_forward_proj"""],
    # used internally in the configuration class file
    # `tokenizer_class` get default value `T5Tokenizer` intentionally
    """MT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
    """UMT5Config""": ["""feed_forward_proj""", """tokenizer_class"""],
    # used internally in the configuration class file
    """LongT5Config""": ["""feed_forward_proj"""],
    # used internally in the configuration class file
    """SwitchTransformersConfig""": ["""feed_forward_proj"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """BioGptConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """GLPNConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """SegformerConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """CvtConfig""": ["""layer_norm_eps"""],
    # having default values other than `1e-5` - we can't fix them without breaking
    """PerceiverConfig""": ["""layer_norm_eps"""],
    # used internally to calculate the feature size
    """InformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate the feature size
    """TimeSeriesTransformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate the feature size
    """AutoformerConfig""": ["""num_static_real_features""", """num_time_features"""],
    # used internally to calculate `mlp_dim`
    """SamVisionConfig""": ["""mlp_ratio"""],
    # For (head) training, but so far not implemented
    """ClapAudioConfig""": ["""num_classes"""],
    # Not used, but providing useful information to users
    """SpeechT5HifiGanConfig""": ["""sampling_rate"""],
}


# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
    {
        """CLIPSegConfig""": True,
        """DeformableDetrConfig""": True,
        """DetaConfig""": True,
        """DinatConfig""": True,
        """DonutSwinConfig""": True,
        """EfficientFormerConfig""": True,
        """FSMTConfig""": True,
        """JukeboxConfig""": True,
        """LayoutLMv2Config""": True,
        """MaskFormerSwinConfig""": True,
        """MT5Config""": True,
        """NatConfig""": True,
        """OneFormerConfig""": True,
        """PerceiverConfig""": True,
        """RagConfig""": True,
        """SpeechT5Config""": True,
        """SwinConfig""": True,
        """Swin2SRConfig""": True,
        """Swinv2Config""": True,
        """SwitchTransformersConfig""": True,
        """TableTransformerConfig""": True,
        """TapasConfig""": True,
        """TransfoXLConfig""": True,
        """UniSpeechConfig""": True,
        """UniSpeechSatConfig""": True,
        """WavLMConfig""": True,
        """WhisperConfig""": True,
        # TODO: @Arthur (for `alignment_head` and `alignment_layer`)
        """JukeboxPriorConfig""": True,
        # TODO: @Younes (for `is_decoder`)
        """Pix2StructTextConfig""": True,
    }
)




def     snake_case_					(     lowerCAmelCase_       ,   lowerCAmelCase_       ,   lowerCAmelCase_       ,   lowerCAmelCase_		)->		Dict:





       '''simple docstring'''


       _UpperCAmelCase  :						Optional[Any]			     = False
       for attribute in attributes:
              for modeling_source in source_strings:
                     # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
                     if (
                         F'''config.{attribute}''' in modeling_source
                         or F'''getattr(config, "{attribute}"''' in modeling_source
                         or F'''getattr(self.config, "{attribute}"''' in modeling_source
                     ):
                            _UpperCAmelCase  :						Tuple			     = True
                     # Deal with multi-line cases
                     elif (
                         re.search(
                             RF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"'''       ,   lowerCAmelCase_       ,   )
                         is not None
                     ):
                            _UpperCAmelCase  :						Any			     = True
                     # `SequenceSummary` is called with `SequenceSummary(config)`
                     elif attribute in [
                         "summary_type",
                         "summary_use_proj",
                         "summary_activation",
                         "summary_last_dropout",
                         "summary_proj_to_labels",
                         "summary_first_dropout",
                     ]:
                            if "SequenceSummary" in modeling_source:
                                   _UpperCAmelCase  :						List[str]			     = True
                     if attribute_used:
                            break
              if attribute_used:
                     break

    # common and important attributes, even if they do not always appear in the modeling files
       _UpperCAmelCase  :						Dict			     = [
           """bos_index""",
           """eos_index""",
           """pad_index""",
           """unk_index""",
           """mask_index""",
           """image_size""",
           """use_cache""",
           """out_features""",
           """out_indices""",
       ]
       _UpperCAmelCase  :						int			     = ["""encoder_no_repeat_ngram_size"""]

       # Special cases to be allowed
       _UpperCAmelCase  :						Optional[Any]			     = True
       if not attribute_used:
              _UpperCAmelCase  :						List[Any]			     = False
              for attribute in attributes:
                     # Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
                     if attribute in ["is_encoder_decoder"] and default_value is True:
                            _UpperCAmelCase  :						Tuple			     = True
                     elif attribute in ["tie_word_embeddings"] and default_value is False:
                            _UpperCAmelCase  :						Any			     = True

                     # Allow cases without checking the default value in the configuration class
                     elif attribute in attributes_to_allow + attributes_used_in_generation:
                            _UpperCAmelCase  :						Dict			     = True
                     elif attribute.endswith("""_token_id"""		):
                            _UpperCAmelCase  :						Optional[int]			     = True

                     # configuration class specific cases
                     if not case_allowed:
                            _UpperCAmelCase  :						int			     = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__       ,   []		)
                            _UpperCAmelCase  :						Union[str, Any]			     = allowed_cases is True or attribute in allowed_cases

       return attribute_used or case_allowed




def     snake_case_					(     lowerCAmelCase_		)->		Optional[Any]:





       '''simple docstring'''


       _UpperCAmelCase  :						Optional[int]			     = dict(inspect.signature(config_class.__init__		).parameters		)
       _UpperCAmelCase  :						Optional[int]			     = [x for x in list(signature.keys()		) if x not in ["""self""", """kwargs"""]]
       _UpperCAmelCase  :						Optional[int]			     = [signature[param].default for param in parameter_names]

       # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
       # as one variant is used, the test should pass
       _UpperCAmelCase  :						List[Any]			     = {}
       if len(config_class.attribute_map		) > 0:
              _UpperCAmelCase  :						Optional[int]			     = {v: k for k, v in config_class.attribute_map.items()}

       # Get the path to modeling source files
       _UpperCAmelCase  :						int			     = inspect.getsourcefile(lowerCAmelCase_		)
       _UpperCAmelCase  :						str			     = os.path.dirname(lowerCAmelCase_		)
       # Let's check against all frameworks: as long as one framework uses an attribute, we are good.
       _UpperCAmelCase  :						Optional[int]			     = [os.path.join(lowerCAmelCase_       ,   lowerCAmelCase_		) for fn in os.listdir(lowerCAmelCase_		) if fn.startswith("""modeling_"""		)]

       # Get the source code strings
       _UpperCAmelCase  :						str			     = []
       for path in modeling_paths:
              if os.path.isfile(lowerCAmelCase_		):
                     with open(lowerCAmelCase_		) as fp:
                            modeling_sources.append(fp.read()		)

       _UpperCAmelCase  :						Any			     = []
       for config_param, default_value in zip(lowerCAmelCase_       ,   lowerCAmelCase_		):
              # `attributes` here is all the variant names for `config_param`
              _UpperCAmelCase  :						List[str]			     = [config_param]
              # some configuration classes have non-empty `attribute_map`, and both names could be used in the
              # corresponding modeling files. As long as one of them appears, it is fine.
              if config_param in reversed_attribute_map:
                     attributes.append(reversed_attribute_map[config_param]		)

              if not check_attribute_being_used(lowerCAmelCase_       ,   lowerCAmelCase_       ,   lowerCAmelCase_       ,   lowerCAmelCase_		):
                     unused_attributes.append(attributes[0]		)

       return sorted(lowerCAmelCase_		)




def     snake_case_					(     )->		Optional[Any]:





       '''simple docstring'''


       _UpperCAmelCase  :						Dict			     = {}
       for _config_class in list(CONFIG_MAPPING.values()		):
              # Skip deprecated models
              if "models.deprecated" in _config_class.__module__:
                     continue
              # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
              _UpperCAmelCase  :						List[Any]			     = [
                  cls
                  for name, cls in inspect.getmembers(
                      inspect.getmodule(_config_class		)       ,   lambda lowerCAmelCase_		: inspect.isclass(lowerCAmelCase_		)
                      and issubclass(lowerCAmelCase_       ,   lowerCAmelCase_		)
                      and inspect.getmodule(lowerCAmelCase_		) == inspect.getmodule(_config_class		)       ,   )
              ]
              for config_class in config_classes_in_module:
                     _UpperCAmelCase  :						Optional[int]			     = check_config_attributes_being_used(lowerCAmelCase_		)
                     if len(lowerCAmelCase_		) > 0:
                            _UpperCAmelCase  :						Tuple			     = unused_attributes

       if len(lowerCAmelCase_		) > 0:
              _UpperCAmelCase  :						Dict			     = """The following configuration classes contain unused attributes in the corresponding modeling files:\n"""
              for name, attributes in configs_with_unused_attributes.items():
                     error += F'''{name}: {attributes}\n'''

              raise ValueError(lowerCAmelCase_		)


if __name__ == "__main__":
   check_config_attributes()



