



'''simple docstring'''





from __future__ import annotations

import unittest

from transformers import AutoTokenizer, MBartConfig, 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, TFMBartForConditionalGeneration, TFMBartModel






@require_tf
class __A			:



 '''simple docstring'''







 __lowerCamelCase    :       Tuple          =       MBartConfig
 __lowerCamelCase    :       Optional[int]          =       {}
 __lowerCamelCase    :       Any          =       'gelu'



 def __init__(self ,   A ,   A=13 ,   A=7 ,   A=True ,   A=False ,   A=99 ,   A=32 ,   A=2 ,   A=4 ,   A=37 ,   A=0.1 ,   A=0.1 ,   A=20 ,   A=2 ,   A=1 ,   A=0 ,   )    ->     Tuple:


      """simple docstring"""



      _a      =  parent
      _a      =  batch_size
      _a      =  seq_length
      _a      =  is_training
      _a      =  use_labels
      _a      =  vocab_size
      _a      =  hidden_size
      _a      =  num_hidden_layers
      _a      =  num_attention_heads
      _a      =  intermediate_size
      _a      =  hidden_dropout_prob
      _a      =  attention_probs_dropout_prob
      _a      =  max_position_embeddings
      _a      =  eos_token_id
      _a      =  pad_token_id
      _a      =  bos_token_id



 def 					a__  (self       )    ->     Optional[int]:


      """simple docstring"""



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

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

      _a      =  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      =  prepare_mbart_inputs_dict(snake_case_ ,   snake_case_ ,   snake_case_       )
      return config, inputs_dict



 def 					a__  (self ,   A ,   A       )    ->     List[str]:


      """simple docstring"""



      _a      =  TFMBartModel(config=snake_case_       ).get_decoder()
      _a      =  inputs_dict["""input_ids"""]

      _a      =  input_ids[:1, :]
      _a      =  inputs_dict["""attention_mask"""][:1, :]
      _a      =  inputs_dict["""head_mask"""]
      _a      =  1

      # first forward pass
      _a      =  model(snake_case_ ,   attention_mask=snake_case_ ,   head_mask=snake_case_ ,   use_cache=snake_case_       )

      _a      =  outputs.to_tuple()
      _a      =  past_key_values[1]





def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A=None  ,	__A=None  ,	__A=None  ,	__A=None  ,	__A=None  ,	):



     """simple docstring"""



     if attention_mask is None:
          _a      =  tf.cast(tf.math.not_equal(_lowerCAmelCase  ,	config.pad_token_id)  ,	tf.inta)
     if decoder_attention_mask is None:
          _a      =  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      =  tf.ones((config.encoder_layers, config.encoder_attention_heads))
     if decoder_head_mask is None:
          _a      =  tf.ones((config.decoder_layers, config.decoder_attention_heads))
     if cross_attn_head_mask is None:
          _a      =  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'''







 __lowerCamelCase    :       int          =       (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
 __lowerCamelCase    :       Any          =       (TFMBartForConditionalGeneration,) if is_tf_available() else ()
 __lowerCamelCase    :       Tuple          =       (
     {
         'conversational': TFMBartForConditionalGeneration,
         'feature-extraction': TFMBartModel,
         'summarization': TFMBartForConditionalGeneration,
         'text2text-generation': TFMBartForConditionalGeneration,
         'translation': TFMBartForConditionalGeneration,
     }
     if is_tf_available()
     else {}
 )
 __lowerCamelCase    :       Dict          =       True
 __lowerCamelCase    :       Dict          =       False
 __lowerCamelCase    :       Optional[Any]          =       False



 def 					a__  (self ,   A ,   A ,   A ,   A ,   A       )    ->     List[str]:


      """simple docstring"""



      if pipeline_test_casse_name != "FeatureExtractionPipelineTests":
           # Exception encountered when calling layer '...'
           return True

      return False



 def 					a__  (self       )    ->     int:


      """simple docstring"""



      _a      =  TFMBartModelTester(self       )
      _a      =  ConfigTester(self ,   config_class=snake_case_       )



 def 					a__  (self       )    ->     List[str]:


      """simple docstring"""



      self.config_tester.run_common_tests()



 def 					a__  (self       )    ->     str:


      """simple docstring"""



      _a      =  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 __A			(  unittest.TestCase						):



 '''simple docstring'''







 __lowerCamelCase    :       Any          =       [
     ' UN Chief Says There Is No Military Solution in Syria',
 ]
 __lowerCamelCase    :       Optional[int]          =       [
     'Şeful ONU declară că nu există o soluţie militară în Siria',
 ]
 __lowerCamelCase    :       str          =       'facebook/mbart-large-en-ro'



 @cached_property
 def 					a__  (self       )    ->     Tuple:


      """simple docstring"""



      return AutoTokenizer.from_pretrained(self.model_name       )



 @cached_property
 def 					a__  (self       )    ->     int:


      """simple docstring"""



      _a      =  TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name       )
      return model



 def 					a__  (self ,   **A       )    ->     Dict:


      """simple docstring"""



      _a      =  self.translate_src_text(**snake_case_       )
      self.assertListEqual(self.expected_text ,   snake_case_       )



 def 					a__  (self ,   **A       )    ->     Optional[int]:


      """simple docstring"""



      _a      =  self.tokenizer(self.src_text ,   **snake_case_ ,   return_tensors='''tf'''       )
      _a      =  self.model.generate(
          model_inputs.input_ids ,   attention_mask=model_inputs.attention_mask ,   num_beams=2       )
      _a      =  self.tokenizer.batch_decode(snake_case_ ,   skip_special_tokens=snake_case_       )
      return generated_words



 @slow
 def 					a__  (self       )    ->     Optional[int]:


      """simple docstring"""



      self._assert_generated_batch_equal_expected()








'''simple docstring'''





__a          =		frozenset(
    [
        "prompt",
        "height",
        "width",
        "guidance_scale",
        "negative_prompt",
        "prompt_embeds",
        "negative_prompt_embeds",
        "cross_attention_kwargs",
    ]
)

__a          =		frozenset(["prompt", "negative_prompt"])

__a          =		frozenset([])

__a          =		frozenset(["image"])

__a          =		frozenset(
    [
        "image",
        "height",
        "width",
        "guidance_scale",
    ]
)

__a          =		frozenset(["image"])

__a          =		frozenset(
    [
        "prompt",
        "image",
        "height",
        "width",
        "guidance_scale",
        "negative_prompt",
        "prompt_embeds",
        "negative_prompt_embeds",
    ]
)

__a          =		frozenset(["prompt", "image", "negative_prompt"])

__a          =		frozenset(
    [
        # Text guided image variation with an image mask
        "prompt",
        "image",
        "mask_image",
        "height",
        "width",
        "guidance_scale",
        "negative_prompt",
        "prompt_embeds",
        "negative_prompt_embeds",
    ]
)

__a          =		frozenset(["prompt", "image", "mask_image", "negative_prompt"])

__a          =		frozenset(
    [
        # image variation with an image mask
        "image",
        "mask_image",
        "height",
        "width",
        "guidance_scale",
    ]
)

__a          =		frozenset(["image", "mask_image"])

__a          =		frozenset(
    [
        "example_image",
        "image",
        "mask_image",
        "height",
        "width",
        "guidance_scale",
    ]
)

__a          =		frozenset(["example_image", "image", "mask_image"])

__a          =		frozenset(["class_labels"])

__a          =		frozenset(["class_labels"])

__a          =		frozenset(["batch_size"])

__a          =		frozenset([])

__a          =		frozenset(["batch_size"])

__a          =		frozenset([])

__a          =		frozenset(
    [
        "prompt",
        "audio_length_in_s",
        "guidance_scale",
        "negative_prompt",
        "prompt_embeds",
        "negative_prompt_embeds",
        "cross_attention_kwargs",
    ]
)

__a          =		frozenset(["prompt", "negative_prompt"])
__a          =		frozenset(["input_tokens"])

__a          =		frozenset(["input_tokens"])
