


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 _lowerCamelCase:
       lowercase_					:      Tuple       					=     MBartConfig
       lowercase_					:      Optional[Any]       					=     {}
       lowercase_					:      List[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=20, lowerCamelCase=2, lowerCamelCase=1, lowerCamelCase=0, )			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				str 						=						parent
           _lowercase			:				str 						=						batch_size
           _lowercase			:				Union[str, Any] 						=						seq_length
           _lowercase			:				Dict 						=						is_training
           _lowercase			:				str 						=						use_labels
           _lowercase			:				List[Any] 						=						vocab_size
           _lowercase			:				Dict 						=						hidden_size
           _lowercase			:				Tuple 						=						num_hidden_layers
           _lowercase			:				int 						=						num_attention_heads
           _lowercase			:				int 						=						intermediate_size
           _lowercase			:				Tuple 						=						hidden_dropout_prob
           _lowercase			:				int 						=						attention_probs_dropout_prob
           _lowercase			:				Union[str, Any] 						=						max_position_embeddings
           _lowercase			:				Optional[Any] 						=						eos_token_id
           _lowercase			:				Optional[int] 						=						pad_token_id
           _lowercase			:				Any 						=						bos_token_id
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

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

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

           _lowercase			:				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, )
           _lowercase			:				str 						=						prepare_mbart_inputs_dict(lowerCamelCase, lowerCamelCase, lowerCamelCase)
           return config, inputs_dict




       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase)			->  Any:




           """simple docstring"""

           _lowercase			:				str 						=						TFMBartModel(config=lowerCamelCase).get_decoder()
           _lowercase			:				Union[str, Any] 						=						inputs_dict['input_ids']

           _lowercase			:				str 						=						input_ids[:1, :]
           _lowercase			:				Optional[int] 						=						inputs_dict['attention_mask'][:1, :]
           _lowercase			:				Tuple 						=						inputs_dict['head_mask']
           _lowercase			:				Tuple 						=						1

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

           _lowercase						,							_lowercase			:				Union[str, Any] 						=						outputs.to_tuple()
           _lowercase			:				Optional[int] 						=						past_key_values[1]



def 							UpperCamelCase_( lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_				,					lowerCamelCase_=None				,					lowerCamelCase_=None				,					lowerCamelCase_=None				,					lowerCamelCase_=None				,					lowerCamelCase_=None				,					)       ->		Optional[Any]:
    if attention_mask is None:
        _lowercase			:				Dict 						=						tf.cast(tf.math.not_equal(lowerCamelCase_				,					config.pad_token_id					)				,					tf.inta					)
    if decoder_attention_mask is None:
        _lowercase			:				List[Any] 						=						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:
        _lowercase			:				List[Any] 						=						tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
    if decoder_head_mask is None:
        _lowercase			:				int 						=						tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
    if cross_attn_head_mask is None:
        _lowercase			:				Tuple 						=						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 _lowerCamelCase(		_a,					_a,					unittest.TestCase  ):
       lowercase_					:      Optional[int]       					=     (TFMBartForConditionalGeneration, TFMBartModel) if is_tf_available() else ()
       lowercase_					:      Optional[Any]       					=     (TFMBartForConditionalGeneration,) if is_tf_available() else ()
       lowercase_					:      Optional[int]       					=     (
           {
               """conversational""": TFMBartForConditionalGeneration,
               """feature-extraction""": TFMBartModel,
               """summarization""": TFMBartForConditionalGeneration,
               """text2text-generation""": TFMBartForConditionalGeneration,
               """translation""": TFMBartForConditionalGeneration,
           }
           if is_tf_available()
           else {}
       )
       lowercase_					:      Optional[Any]       					=     True
       lowercase_					:      Union[str, Any]       					=     False
       lowercase_					:      Dict       					=     False
       def      UpperCamelCase	(   self, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase, lowerCamelCase)			->  List[Any]:




           """simple docstring"""

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

           return False
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           _lowercase			:				List[str] 						=						TFMBartModelTester(self)
           _lowercase			:				List[Any] 						=						ConfigTester(self, config_class=lowerCamelCase)
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           self.config_tester.run_common_tests()




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						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 _lowerCamelCase(		unittest.TestCase  ):
       lowercase_					:      Tuple       					=     [
           """ UN Chief Says There Is No Military Solution in Syria""",
       ]
       lowercase_					:      int       					=     [
           """Şeful ONU declară că nu există o soluţie militară în Siria""",
       ]
       lowercase_					:      Optional[Any]       					=     """facebook/mbart-large-en-ro"""
       @cached_property
       def      UpperCamelCase	(   self)			->  Any:




           """simple docstring"""

           return AutoTokenizer.from_pretrained(self.model_name)
       @cached_property
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
           return model
       def      UpperCamelCase	(   self, **lowerCamelCase)			->  List[str]:




           """simple docstring"""

           _lowercase			:				str 						=						self.translate_src_text(**lowerCamelCase)
           self.assertListEqual(self.expected_text, lowerCamelCase)
       def      UpperCamelCase	(   self, **lowerCamelCase)			->  List[str]:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						self.tokenizer(self.src_text, **lowerCamelCase, return_tensors='tf')
           _lowercase			:				int 						=						self.model.generate(
               model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2)
           _lowercase			:				List[Any] 						=						self.tokenizer.batch_decode(lowerCamelCase, skip_special_tokens=lowerCamelCase)
           return generated_words




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




           """simple docstring"""

           self._assert_generated_batch_equal_expected()








import os
from argparse import ArgumentParser, Namespace

from ..data import SingleSentenceClassificationProcessor as Processor
from ..pipelines import TextClassificationPipeline
from ..utils import is_tf_available, is_torch_available, logging
from . import BaseTransformersCLICommand


if not is_tf_available() and not is_torch_available():
				raise RuntimeError("At least one of PyTorch or TensorFlow 2.0+ should be installed to use CLI training")

# TF training parameters
SCREAMING_SNAKE_CASE__     :     Union[str, Any]		    =       False
SCREAMING_SNAKE_CASE__     :     Optional[int]		    =       False

def lowercase    (  SCREAMING_SNAKE_CASE )			->							List[Any]:


			'''simple docstring'''







			return TrainCommand(SCREAMING_SNAKE_CASE )



class       a_       (     SCREAMING_SNAKE_CASE__     ):





	@staticmethod
	def 						A_(							SCREAMING_SNAKE_CASE      )  ->					Optional[int]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						parser.add_parser('train'      ,     help='CLI tool to train a model on a task.'      )

				train_parser.add_argument(
				    '--train_data'      ,     type=SCREAMING_SNAKE_CASE      ,     required=SCREAMING_SNAKE_CASE      ,     help='path to train (and optionally evaluation) dataset as a csv with tab separated labels and sentences.'      ,     )
				train_parser.add_argument(
				    '--column_label'      ,     type=SCREAMING_SNAKE_CASE      ,     default=0      ,     help='Column of the dataset csv file with example labels.'      )
				train_parser.add_argument(
				    '--column_text'      ,     type=SCREAMING_SNAKE_CASE      ,     default=1      ,     help='Column of the dataset csv file with example texts.'      )
				train_parser.add_argument(
				    '--column_id'      ,     type=SCREAMING_SNAKE_CASE      ,     default=2      ,     help='Column of the dataset csv file with example ids.'      )
				train_parser.add_argument(
				    '--skip_first_row'      ,     action='store_true'      ,     help='Skip the first row of the csv file (headers).'      )

				train_parser.add_argument('--validation_data'      ,     type=SCREAMING_SNAKE_CASE      ,     default=''      ,     help='path to validation dataset.'      )
				train_parser.add_argument(
				    '--validation_split'      ,     type=SCREAMING_SNAKE_CASE      ,     default=0.1      ,     help='if validation dataset is not provided, fraction of train dataset to use as validation dataset.'      ,     )

				train_parser.add_argument('--output'      ,     type=SCREAMING_SNAKE_CASE      ,     default='./'      ,     help='path to saved the trained model.'      )

				train_parser.add_argument(
				    '--task'      ,     type=SCREAMING_SNAKE_CASE      ,     default='text_classification'      ,     help='Task to train the model on.'      )
				train_parser.add_argument(
				    '--model'      ,     type=SCREAMING_SNAKE_CASE      ,     default='bert-base-uncased'      ,     help='Model\'s name or path to stored model.'      )
				train_parser.add_argument('--train_batch_size'      ,     type=SCREAMING_SNAKE_CASE      ,     default=32      ,     help='Batch size for training.'      )
				train_parser.add_argument('--valid_batch_size'      ,     type=SCREAMING_SNAKE_CASE      ,     default=64      ,     help='Batch size for validation.'      )
				train_parser.add_argument('--learning_rate'      ,     type=SCREAMING_SNAKE_CASE      ,     default=3e-5      ,     help='Learning rate.'      )
				train_parser.add_argument('--adam_epsilon'      ,     type=SCREAMING_SNAKE_CASE      ,     default=1e-08      ,     help='Epsilon for Adam optimizer.'      )
				train_parser.set_defaults(func=SCREAMING_SNAKE_CASE      )





	def __init__(							self      ,     SCREAMING_SNAKE_CASE      )  ->					List[Any]:




				"""simple docstring"""



				SCREAMING_SNAKE_CASE_								=						logging.get_logger('transformers-cli/training'      )

				SCREAMING_SNAKE_CASE_								=						'tf' if is_tf_available() else 'torch'

				os.makedirs(args.output      ,     exist_ok=SCREAMING_SNAKE_CASE      )
				SCREAMING_SNAKE_CASE_								=						args.output

				SCREAMING_SNAKE_CASE_								=						args.column_label
				SCREAMING_SNAKE_CASE_								=						args.column_text
				SCREAMING_SNAKE_CASE_								=						args.column_id

				self.logger.info(f'Loading {args.task} pipeline for {args.model}'      )
				if args.task == "text_classification":
							SCREAMING_SNAKE_CASE_								=						TextClassificationPipeline.from_pretrained(args.model      )
				elif args.task == "token_classification":
							raise NotImplementedError
				elif args.task == "question_answering":
							raise NotImplementedError

				self.logger.info(f'Loading dataset from {args.train_data}'      )
				SCREAMING_SNAKE_CASE_								=						Processor.create_from_csv(
				    args.train_data      ,     column_label=args.column_label      ,     column_text=args.column_text      ,     column_id=args.column_id      ,     skip_first_row=args.skip_first_row      ,     )
				SCREAMING_SNAKE_CASE_								=						None
				if args.validation_data:
							self.logger.info(f'Loading validation dataset from {args.validation_data}'      )
							SCREAMING_SNAKE_CASE_								=						Processor.create_from_csv(
							    args.validation_data      ,     column_label=args.column_label      ,     column_text=args.column_text      ,     column_id=args.column_id      ,     skip_first_row=args.skip_first_row      ,     )

				SCREAMING_SNAKE_CASE_								=						args.validation_split
				SCREAMING_SNAKE_CASE_								=						args.train_batch_size
				SCREAMING_SNAKE_CASE_								=						args.valid_batch_size
				SCREAMING_SNAKE_CASE_								=						args.learning_rate
				SCREAMING_SNAKE_CASE_								=						args.adam_epsilon





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				if self.framework == "tf":
							return self.run_tf()
				return self.run_torch()





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




				"""simple docstring"""



				raise NotImplementedError





	def 						A_(							self      )  ->					Dict:




				"""simple docstring"""



				self.pipeline.fit(
				    self.train_dataset      ,     validation_data=self.valid_dataset      ,     validation_split=self.validation_split      ,     learning_rate=self.learning_rate      ,     adam_epsilon=self.adam_epsilon      ,     train_batch_size=self.train_batch_size      ,     valid_batch_size=self.valid_batch_size      ,     )

				# Save trained pipeline
				self.pipeline.save_pretrained(self.output      )
