






import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("""4.31.0""")

require_version("""datasets>=1.8.0""", """To fix: pip install -r examples/pytorch/text-classification/requirements.txt""")

_a    :   Optional[int]        =			logging.getLogger(__name__)







@dataclass
class 	_UpperCAmelCase  :




      """simple docstring"""



      A          =    field(
          default=1_28				,							metadata={
              '''help''': (
                  '''The maximum total input sequence length after tokenization. Sequences longer '''
                  '''than this will be truncated, sequences shorter will be padded.'''
              )
          }				,							)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Overwrite the cached preprocessed datasets or not.'''}		)
      A          =    field(
          default=_A				,							metadata={
              '''help''': (
                  '''Whether to pad all samples to `max_seq_length`. '''
                  '''If False, will pad the samples dynamically when batching to the maximum length in the batch.'''
              )
          }				,							)
      A          =    field(
          default=_A				,							metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of training examples to this '''
                  '''value if set.'''
              )
          }				,							)
      A          =    field(
          default=_A				,							metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
                  '''value if set.'''
              )
          }				,							)
      A          =    field(
          default=_A				,							metadata={
              '''help''': (
                  '''For debugging purposes or quicker training, truncate the number of prediction examples to this '''
                  '''value if set.'''
              )
          }				,							)







@dataclass
class 	_UpperCAmelCase  :




      """simple docstring"""



      A          =    field(
          default=_A				,							metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}		)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Evaluation language. Also train language if `train_language` is set to None.'''}		)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Train language if it is different from the evaluation language.'''}		)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}		)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''}		)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}				,							)
      A          =    field(
          default=_A				,							metadata={'''help''': '''arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()'''}				,							)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Whether to use one of the fast tokenizer (backed by the tokenizers library) or not.'''}				,							)
      A          =    field(
          default='''main'''				,							metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}				,							)
      A          =    field(
          default=_A				,							metadata={
              '''help''': (
                  '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
                  '''with private models).'''
              )
          }				,							)
      A          =    field(
          default=_A				,							metadata={'''help''': '''Will enable to load a pretrained model whose head dimensions are different.'''}				,							)





def 				snake_case__							(							):
    # See all possible arguments in src/transformers/training_args.py
    # or by passing the --help flag to this script.
    # We now keep distinct sets of args, for a cleaner separation of concerns.

    lowerCAmelCase__   :Union[str, Any]      							=				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
    lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__   :Union[str, Any]      							=				parser.parse_args_into_dataclasses()

    # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
    # information sent is the one passed as arguments along with your Python/PyTorch versions.
    send_example_telemetry("run_xnli"    ,			UpperCAmelCase       )

    # Setup logging
    logging.basicConfig(
        format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"    ,			datefmt="%m/%d/%Y %H:%M:%S"    ,			handlers=[logging.StreamHandler(sys.stdout       )]    ,			)

    if training_args.should_log:
        # The default of training_args.log_level is passive, so we set log level at info here to have that default.
        transformers.utils.logging.set_verbosity_info()

    lowerCAmelCase__   :int      							=				training_args.get_process_log_level()
    logger.setLevel(UpperCAmelCase       )
    datasets.utils.logging.set_verbosity(UpperCAmelCase       )
    transformers.utils.logging.set_verbosity(UpperCAmelCase       )
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()

    # Log on each process the small summary:
    logger.warning(
        F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
        + F'''distributed training: {bool(training_args.local_rank != -1       )}, 16-bits training: {training_args.fpaa}'''       )
    logger.info(F'''Training/evaluation parameters {training_args}'''       )

    # Detecting last checkpoint.
    lowerCAmelCase__   :Tuple      							=				None
    if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
        lowerCAmelCase__   :List[str]      							=				get_last_checkpoint(training_args.output_dir       )
        if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
            raise ValueError(
                F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
                "Use --overwrite_output_dir to overcome."       )
        elif last_checkpoint is not None:
            logger.info(
                F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
                "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."       )

    # Set seed before initializing model.
    set_seed(training_args.seed       )

    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # Downloading and loading xnli dataset from the hub.
    if training_args.do_train:
        if model_args.train_language is None:
            lowerCAmelCase__   :Tuple      							=				load_dataset(
                "xnli"    ,			model_args.language    ,			split="train"    ,			cache_dir=model_args.cache_dir    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
        else:
            lowerCAmelCase__   :Optional[int]      							=				load_dataset(
                "xnli"    ,			model_args.train_language    ,			split="train"    ,			cache_dir=model_args.cache_dir    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
        lowerCAmelCase__   :Dict      							=				train_dataset.features["label"].names

    if training_args.do_eval:
        lowerCAmelCase__   :Any      							=				load_dataset(
            "xnli"    ,			model_args.language    ,			split="validation"    ,			cache_dir=model_args.cache_dir    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
        lowerCAmelCase__   :List[str]      							=				eval_dataset.features["label"].names

    if training_args.do_predict:
        lowerCAmelCase__   :Dict      							=				load_dataset(
            "xnli"    ,			model_args.language    ,			split="test"    ,			cache_dir=model_args.cache_dir    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
        lowerCAmelCase__   :Optional[int]      							=				predict_dataset.features["label"].names

    # Labels
    lowerCAmelCase__   :List[Any]      							=				len(UpperCAmelCase       )

    # Load pretrained model and tokenizer
    # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
    # download model & vocab.
    lowerCAmelCase__   :Optional[int]      							=				AutoConfig.from_pretrained(
        model_args.config_name if model_args.config_name else model_args.model_name_or_path    ,			num_labels=UpperCAmelCase    ,			idalabel={str(UpperCAmelCase       ): label for i, label in enumerate(UpperCAmelCase       )}    ,			labelaid={label: i for i, label in enumerate(UpperCAmelCase       )}    ,			finetuning_task="xnli"    ,			cache_dir=model_args.cache_dir    ,			revision=model_args.model_revision    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
    lowerCAmelCase__   :Dict      							=				AutoTokenizer.from_pretrained(
        model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path    ,			do_lower_case=model_args.do_lower_case    ,			cache_dir=model_args.cache_dir    ,			use_fast=model_args.use_fast_tokenizer    ,			revision=model_args.model_revision    ,			use_auth_token=True if model_args.use_auth_token else None    ,			)
    lowerCAmelCase__   :str      							=				AutoModelForSequenceClassification.from_pretrained(
        model_args.model_name_or_path    ,			from_tf=bool(".ckpt" in model_args.model_name_or_path       )    ,			config=UpperCAmelCase    ,			cache_dir=model_args.cache_dir    ,			revision=model_args.model_revision    ,			use_auth_token=True if model_args.use_auth_token else None    ,			ignore_mismatched_sizes=model_args.ignore_mismatched_sizes    ,			)

    # Preprocessing the datasets
    # Padding strategy
    if data_args.pad_to_max_length:
        lowerCAmelCase__   :Dict      							=				"max_length"
    else:
        # We will pad later, dynamically at batch creation, to the max sequence length in each batch
        lowerCAmelCase__   :Dict      							=				False

    def preprocess_function(UpperCAmelCase							:  str       ):
        # Tokenize the texts
        return tokenizer(
            examples["premise"]    ,			examples["hypothesis"]    ,			padding=UpperCAmelCase    ,			max_length=data_args.max_seq_length    ,			truncation=UpperCAmelCase    ,			)

    if training_args.do_train:
        if data_args.max_train_samples is not None:
            lowerCAmelCase__   :Tuple      							=				min(len(UpperCAmelCase       )    ,			data_args.max_train_samples       )
            lowerCAmelCase__   :str      							=				train_dataset.select(range(UpperCAmelCase       )       )
        with training_args.main_process_first(desc="train dataset map pre-processing"       ):
            lowerCAmelCase__   :Dict      							=				train_dataset.map(
                UpperCAmelCase    ,			batched=UpperCAmelCase    ,			load_from_cache_file=not data_args.overwrite_cache    ,			desc="Running tokenizer on train dataset"    ,			)
        # Log a few random samples from the training set:
        for index in random.sample(range(len(UpperCAmelCase       )       )    ,			3       ):
            logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.'''       )

    if training_args.do_eval:
        if data_args.max_eval_samples is not None:
            lowerCAmelCase__   :int      							=				min(len(UpperCAmelCase       )    ,			data_args.max_eval_samples       )
            lowerCAmelCase__   :int      							=				eval_dataset.select(range(UpperCAmelCase       )       )
        with training_args.main_process_first(desc="validation dataset map pre-processing"       ):
            lowerCAmelCase__   :Dict      							=				eval_dataset.map(
                UpperCAmelCase    ,			batched=UpperCAmelCase    ,			load_from_cache_file=not data_args.overwrite_cache    ,			desc="Running tokenizer on validation dataset"    ,			)

    if training_args.do_predict:
        if data_args.max_predict_samples is not None:
            lowerCAmelCase__   :Optional[Any]      							=				min(len(UpperCAmelCase       )    ,			data_args.max_predict_samples       )
            lowerCAmelCase__   :str      							=				predict_dataset.select(range(UpperCAmelCase       )       )
        with training_args.main_process_first(desc="prediction dataset map pre-processing"       ):
            lowerCAmelCase__   :int      							=				predict_dataset.map(
                UpperCAmelCase    ,			batched=UpperCAmelCase    ,			load_from_cache_file=not data_args.overwrite_cache    ,			desc="Running tokenizer on prediction dataset"    ,			)

    # Get the metric function
    lowerCAmelCase__   :List[Any]      							=				evaluate.load("xnli"       )

    # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
    # predictions and label_ids field) and has to return a dictionary string to float.
    def compute_metrics(UpperCAmelCase							:  EvalPrediction       ):
        lowerCAmelCase__   :int      							=				p.predictions[0] if isinstance(p.predictions    ,			UpperCAmelCase       ) else p.predictions
        lowerCAmelCase__   :Dict      							=				np.argmax(UpperCAmelCase    ,			axis=1       )
        return metric.compute(predictions=UpperCAmelCase    ,			references=p.label_ids       )

    # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
    if data_args.pad_to_max_length:
        lowerCAmelCase__   :Tuple      							=				default_data_collator
    elif training_args.fpaa:
        lowerCAmelCase__   :Union[str, Any]      							=				DataCollatorWithPadding(UpperCAmelCase    ,			pad_to_multiple_of=8       )
    else:
        lowerCAmelCase__   :str      							=				None

    # Initialize our Trainer
    lowerCAmelCase__   :Union[str, Any]      							=				Trainer(
        model=UpperCAmelCase    ,			args=UpperCAmelCase    ,			train_dataset=train_dataset if training_args.do_train else None    ,			eval_dataset=eval_dataset if training_args.do_eval else None    ,			compute_metrics=UpperCAmelCase    ,			tokenizer=UpperCAmelCase    ,			data_collator=UpperCAmelCase    ,			)

    # Training
    if training_args.do_train:
        lowerCAmelCase__   :List[str]      							=				None
        if training_args.resume_from_checkpoint is not None:
            lowerCAmelCase__   :List[Any]      							=				training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            lowerCAmelCase__   :str      							=				last_checkpoint
        lowerCAmelCase__   :List[Any]      							=				trainer.train(resume_from_checkpoint=UpperCAmelCase       )
        lowerCAmelCase__   :Union[str, Any]      							=				train_result.metrics
        lowerCAmelCase__   :int      							=				(
            data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase       )
        )
        lowerCAmelCase__   :str      							=				min(UpperCAmelCase    ,			len(UpperCAmelCase       )       )

        trainer.save_model()  # Saves the tokenizer too for easy upload

        trainer.log_metrics("train"    ,			UpperCAmelCase       )
        trainer.save_metrics("train"    ,			UpperCAmelCase       )
        trainer.save_state()

    # Evaluation
    if training_args.do_eval:
        logger.info("*** Evaluate ***"       )
        lowerCAmelCase__   :int      							=				trainer.evaluate(eval_dataset=UpperCAmelCase       )

        lowerCAmelCase__   :Union[str, Any]      							=				data_args.max_eval_samples if data_args.max_eval_samples is not None else len(UpperCAmelCase       )
        lowerCAmelCase__   :Optional[Any]      							=				min(UpperCAmelCase    ,			len(UpperCAmelCase       )       )

        trainer.log_metrics("eval"    ,			UpperCAmelCase       )
        trainer.save_metrics("eval"    ,			UpperCAmelCase       )

    # Prediction
    if training_args.do_predict:
        logger.info("*** Predict ***"       )
        lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__   :List[Any]      							=				trainer.predict(UpperCAmelCase    ,			metric_key_prefix="predict"       )

        lowerCAmelCase__   :List[Any]      							=				(
            data_args.max_predict_samples if data_args.max_predict_samples is not None else len(UpperCAmelCase       )
        )
        lowerCAmelCase__   :List[Any]      							=				min(UpperCAmelCase    ,			len(UpperCAmelCase       )       )

        trainer.log_metrics("predict"    ,			UpperCAmelCase       )
        trainer.save_metrics("predict"    ,			UpperCAmelCase       )

        lowerCAmelCase__   :Optional[int]      							=				np.argmax(UpperCAmelCase    ,			axis=1       )
        lowerCAmelCase__   :List[str]      							=				os.path.join(training_args.output_dir    ,			"predictions.txt"       )
        if trainer.is_world_process_zero():
            with open(UpperCAmelCase    ,			"w"       ) as writer:
                writer.write("index\tprediction\n"       )
                for index, item in enumerate(UpperCAmelCase       ):
                    lowerCAmelCase__   :Tuple      							=				label_list[item]
                    writer.write(F'''{index}\t{item}\n'''       )


if __name__ == "__main__":
 main()











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




      """simple docstring"""



      A          =    MBartConfig
      A          =    {}
      A          =    '''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=20    ,	_lowerCAmelCase=2    ,	_lowerCAmelCase=1    ,	_lowerCAmelCase=0    ,	):



          '''simple docstring'''
          lowerCAmelCase__   :Optional[int]      							=				parent
          lowerCAmelCase__   :Dict      							=				batch_size
          lowerCAmelCase__   :Optional[int]      							=				seq_length
          lowerCAmelCase__   :Any      							=				is_training
          lowerCAmelCase__   :List[Any]      							=				use_labels
          lowerCAmelCase__   :Optional[int]      							=				vocab_size
          lowerCAmelCase__   :Optional[int]      							=				hidden_size
          lowerCAmelCase__   :Optional[Any]      							=				num_hidden_layers
          lowerCAmelCase__   :List[str]      							=				num_attention_heads
          lowerCAmelCase__   :List[str]      							=				intermediate_size
          lowerCAmelCase__   :List[str]      							=				hidden_dropout_prob
          lowerCAmelCase__   :Optional[Any]      							=				attention_probs_dropout_prob
          lowerCAmelCase__   :Tuple      							=				max_position_embeddings
          lowerCAmelCase__   :Optional[Any]      							=				eos_token_id
          lowerCAmelCase__   :int      							=				pad_token_id
          lowerCAmelCase__   :Any      							=				bos_token_id
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				ids_tensor([self.batch_size, self.seq_length - 1]    ,	self.vocab_size		)
          lowerCAmelCase__   :List[Any]      							=				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size		)    ,	1		)
          lowerCAmelCase__   :Union[str, Any]      							=				tf.concat([input_ids, eos_tensor]    ,	axis=1		)

          lowerCAmelCase__   :str      							=				ids_tensor([self.batch_size, self.seq_length]    ,	self.vocab_size		)

          lowerCAmelCase__   :Dict      							=				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    ,	)
          lowerCAmelCase__   :Union[str, Any]      							=				prepare_mbart_inputs_dict(_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase		)
          return config, inputs_dict



      def 			snake_case_      (   self    ,	_lowerCAmelCase    ,	_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__   :int      							=				TFMBartModel(config=_lowerCAmelCase		).get_decoder()
          lowerCAmelCase__   :Tuple      							=				inputs_dict["input_ids"]

          lowerCAmelCase__   :Dict      							=				input_ids[:1, :]
          lowerCAmelCase__   :Dict      							=				inputs_dict["attention_mask"][:1, :]
          lowerCAmelCase__   :List[str]      							=				inputs_dict["head_mask"]
          lowerCAmelCase__   :Optional[Any]      							=				1

          # first forward pass
          lowerCAmelCase__   :List[Any]      							=				model(_lowerCAmelCase    ,	attention_mask=_lowerCAmelCase    ,	head_mask=_lowerCAmelCase    ,	use_cache=_lowerCAmelCase		)

          lowerCAmelCase__							,lowerCAmelCase__   :Any      							=				outputs.to_tuple()
          lowerCAmelCase__   :Tuple      							=				past_key_values[1]





def 				snake_case__							(							UpperCAmelCase							:  Union[str, Any]    ,			UpperCAmelCase							:  Optional[Any]    ,			UpperCAmelCase							:  Optional[int]    ,			UpperCAmelCase							:  int=None    ,			UpperCAmelCase							:  Optional[Any]=None    ,			UpperCAmelCase							:  Any=None    ,			UpperCAmelCase							:  Dict=None    ,			UpperCAmelCase							:  Dict=None    ,			):
    if attention_mask is None:
        lowerCAmelCase__   :str      							=				tf.cast(tf.math.not_equal(UpperCAmelCase    ,			config.pad_token_id       )    ,			tf.inta       )
    if decoder_attention_mask is None:
        lowerCAmelCase__   :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:
        lowerCAmelCase__   :str      							=				tf.ones((config.encoder_layers, config.encoder_attention_heads)       )
    if decoder_head_mask is None:
        lowerCAmelCase__   :Tuple      							=				tf.ones((config.decoder_layers, config.decoder_attention_heads)       )
    if cross_attn_head_mask is None:
        lowerCAmelCase__   :Optional[Any]      							=				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"""



      A          =    (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
      A          =    (TFMBartForConditionalGeneration,) if is_tf_available() else ()
      A          =    (
          {
              '''conversational''': TFMBartForConditionalGeneration,
              '''feature-extraction''': TFMBartModel,
              '''summarization''': TFMBartForConditionalGeneration,
              '''text2text-generation''': TFMBartForConditionalGeneration,
              '''translation''': TFMBartForConditionalGeneration,
          }
          if is_tf_available()
          else {}
      )
      A          =    True
      A          =    False
      A          =    False
      def 			snake_case_      (   self    ,	_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase    ,	_lowerCAmelCase		):



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

          return False
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :List[str]      							=				TFMBartModelTester(self		)
          lowerCAmelCase__   :Union[str, Any]      							=				ConfigTester(self    ,	config_class=_lowerCAmelCase		)
      def 			snake_case_      (   self		):



          '''simple docstring'''
          self.config_tester.run_common_tests()



      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				self.model_tester.prepare_config_and_inputs_for_common()
          self.model_tester.check_decoder_model_past_large_inputs(*_lowerCAmelCase		)







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




      """simple docstring"""



      A          =    [
          ''' UN Chief Says There Is No Military Solution in Syria''',
      ]
      A          =    [
          '''Şeful ONU declară că nu există o soluţie militară în Siria''',
      ]
      A          =    '''facebook/mbart-large-en-ro'''
      @cached_property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          return AutoTokenizer.from_pretrained(self.model_name		)
      @cached_property
      def 			snake_case_      (   self		):



          '''simple docstring'''
          lowerCAmelCase__   :Union[str, Any]      							=				TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name		)
          return model
      def 			snake_case_      (   self    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				self.translate_src_text(**_lowerCAmelCase		)
          self.assertListEqual(self.expected_text    ,	_lowerCAmelCase		)
      def 			snake_case_      (   self    ,	**_lowerCAmelCase		):



          '''simple docstring'''
          lowerCAmelCase__   :Tuple      							=				self.tokenizer(self.src_text    ,	**_lowerCAmelCase    ,	return_tensors="tf"		)
          lowerCAmelCase__   :str      							=				self.model.generate(
              model_inputs.input_ids    ,	attention_mask=model_inputs.attention_mask    ,	num_beams=2		)
          lowerCAmelCase__   :int      							=				self.tokenizer.batch_decode(_lowerCAmelCase    ,	skip_special_tokens=_lowerCAmelCase		)
          return generated_words



      @slow
      def 			snake_case_      (   self		):



          '''simple docstring'''
          self._assert_generated_batch_equal_expected()



