import logging
import os
from dataclasses import dataclass, field
from typing import Dict, Optional

import numpy as np
from utils_multiple_choice import MultipleChoiceDataset, Split, processors

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


_lowerCAmelCase       =		logging.getLogger(__name__)
def 					_snake_case	(  __snake_case  ,     __snake_case						):
					return (preds == labels).mean()
@dataclass
class     lowerCAmelCase_     :
							UpperCAmelCase				   =     field(
							    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} )
							UpperCAmelCase				   =     field(
							    default=__lowercase,  metadata={"help": "Pretrained config name or path if not the same as model_name"} )
							UpperCAmelCase				   =     field(
							    default=__lowercase,  metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} )
							UpperCAmelCase				   =     field(
							    default=__lowercase,  metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"},  )




@dataclass
class     lowerCAmelCase_     :
							UpperCAmelCase				   =     field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys() )} )
							UpperCAmelCase				   =     field(metadata={"help": "Should contain the data files for the task."} )
							UpperCAmelCase				   =     field(
							    default=128,  metadata={
							        "help": (
							            "The maximum total input sequence length after tokenization. Sequences longer "
							            "than this will be truncated, sequences shorter will be padded."
							        )
							    },  )
							UpperCAmelCase				   =     field(
							    default=__lowercase,  metadata={"help": "Overwrite the cached training and evaluation sets"} )




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.

					_UpperCamelCase			     =     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
					_UpperCamelCase     ,    _UpperCamelCase     ,    _UpperCamelCase			     =     parser.parse_args_into_dataclasses()

					if (
					    os.path.exists(training_args.output_dir						)
					    and os.listdir(training_args.output_dir						)
					    and training_args.do_train
					    and not training_args.overwrite_output_dir
					):
										raise ValueError(
										    f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use"""
										    ''' --overwrite_output_dir to overcome.'''						)

					# Setup logging
					logging.basicConfig(
					    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s'''  ,     datefmt='''%m/%d/%Y %H:%M:%S'''  ,     level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN  ,     )
					logger.warning(
					    '''Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s'''  ,     training_args.local_rank  ,     training_args.device  ,     training_args.n_gpu  ,     bool(training_args.local_rank != -1						)  ,     training_args.fpaa  ,     )
					# Set the verbosity to info of the Transformers logger (on main process only):
					if is_main_process(training_args.local_rank						):
										transformers.utils.logging.set_verbosity_info()
										transformers.utils.logging.enable_default_handler()
										transformers.utils.logging.enable_explicit_format()
					logger.info('''Training/evaluation parameters %s'''  ,     __snake_case						)

					# Set seed
					set_seed(training_args.seed						)

					try:
										_UpperCamelCase			     =     processors[data_args.task_name]()
										_UpperCamelCase			     =     processor.get_labels()
										_UpperCamelCase			     =     len(__snake_case						)
					except KeyError:
										raise ValueError('''Task not found: %s''' % (data_args.task_name)						)

					# Load pretrained model and tokenizer
					#
					# Distributed training:
					# The .from_pretrained methods guarantee that only one local process can concurrently
					# download model & vocab.

					_UpperCamelCase			     =     AutoConfig.from_pretrained(
					    model_args.config_name if model_args.config_name else model_args.model_name_or_path  ,     num_labels=__snake_case  ,     finetuning_task=data_args.task_name  ,     cache_dir=model_args.cache_dir  ,     )
					_UpperCamelCase			     =     AutoTokenizer.from_pretrained(
					    model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path  ,     cache_dir=model_args.cache_dir  ,     )
					_UpperCamelCase			     =     AutoModelForMultipleChoice.from_pretrained(
					    model_args.model_name_or_path  ,     from_tf=bool('''.ckpt''' in model_args.model_name_or_path						)  ,     config=__snake_case  ,     cache_dir=model_args.cache_dir  ,     )

					# Get datasets
					_UpperCamelCase			     =     (
					    MultipleChoiceDataset(
					        data_dir=data_args.data_dir  ,     tokenizer=__snake_case  ,     task=data_args.task_name  ,     max_seq_length=data_args.max_seq_length  ,     overwrite_cache=data_args.overwrite_cache  ,     mode=Split.train  ,     )
					    if training_args.do_train
					    else None
					)
					_UpperCamelCase			     =     (
					    MultipleChoiceDataset(
					        data_dir=data_args.data_dir  ,     tokenizer=__snake_case  ,     task=data_args.task_name  ,     max_seq_length=data_args.max_seq_length  ,     overwrite_cache=data_args.overwrite_cache  ,     mode=Split.dev  ,     )
					    if training_args.do_eval
					    else None
					)

					def compute_metrics(__snake_case						) -> Dict:
										_UpperCamelCase			     =     np.argmax(p.predictions  ,     axis=1						)
										return {"acc": simple_accuracy(__snake_case  ,     p.label_ids						)}

					# Data collator
					_UpperCamelCase			     =     DataCollatorWithPadding(__snake_case  ,     pad_to_multiple_of=8						) if training_args.fpaa else None

					# Initialize our Trainer
					_UpperCamelCase			     =     Trainer(
					    model=__snake_case  ,     args=__snake_case  ,     train_dataset=__snake_case  ,     eval_dataset=__snake_case  ,     compute_metrics=__snake_case  ,     data_collator=__snake_case  ,     )

					# Training
					if training_args.do_train:
										trainer.train(
										    model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path						) else None						)
										trainer.save_model()
										# For convenience, we also re-save the tokenizer to the same directory,
										# so that you can share your model easily on huggingface.co/models =)
										if trainer.is_world_master():
															tokenizer.save_pretrained(training_args.output_dir						)

    # Evaluation
					_UpperCamelCase			     =     {}
					if training_args.do_eval:
										logger.info('''*** Evaluate ***'''						)

										_UpperCamelCase			     =     trainer.evaluate()

										_UpperCamelCase			     =     os.path.join(training_args.output_dir  ,     '''eval_results.txt'''						)
										if trainer.is_world_master():
															with open(__snake_case  ,     '''w'''						) as writer:
																				logger.info('''***** Eval results *****'''						)
																				for key, value in result.items():
																									logger.info('''  %s = %s'''  ,     __snake_case  ,     __snake_case						)
																									writer.write('''%s = %s\n''' % (key, value)						)

																				results.update(__snake_case						)

					return results
def 					_snake_case	(  __snake_case						):
					# For xla_spawn (TPUs)
					main()


if __name__ == "__main__":
					main()




import unittest

import numpy as np

from transformers import RobertaConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
				from transformers.models.roberta.modeling_flax_roberta import (
				    FlaxRobertaForCausalLM,
				    FlaxRobertaForMaskedLM,
				    FlaxRobertaForMultipleChoice,
				    FlaxRobertaForQuestionAnswering,
				    FlaxRobertaForSequenceClassification,
				    FlaxRobertaForTokenClassification,
				    FlaxRobertaModel,
				)







class 	__lowercase    (unittest.TestCase  ):





							"""simple docstring"""







							def __init__(      self			,						lowerCAmelCase__			,						lowerCAmelCase__=1_3			,						lowerCAmelCase__=7			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=True			,						lowerCAmelCase__=9_9			,						lowerCAmelCase__=3_2			,						lowerCAmelCase__=5			,						lowerCAmelCase__=4			,						lowerCAmelCase__=3_7			,						lowerCAmelCase__="gelu"			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=0.1			,						lowerCAmelCase__=5_1_2			,						lowerCAmelCase__=1_6			,						lowerCAmelCase__=2			,						lowerCAmelCase__=0.02			,						lowerCAmelCase__=4			,						):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Dict					=					parent
										SCREAMING_SNAKE_CASE_		:     List[str]					=					batch_size
										SCREAMING_SNAKE_CASE_		:     Dict					=					seq_length
										SCREAMING_SNAKE_CASE_		:     Any					=					is_training
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					use_attention_mask
										SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					use_token_type_ids
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					use_labels
										SCREAMING_SNAKE_CASE_		:     List[Any]					=					vocab_size
										SCREAMING_SNAKE_CASE_		:     Dict					=					hidden_size
										SCREAMING_SNAKE_CASE_		:     Any					=					num_hidden_layers
										SCREAMING_SNAKE_CASE_		:     List[str]					=					num_attention_heads
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					intermediate_size
										SCREAMING_SNAKE_CASE_		:     int					=					hidden_act
										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					hidden_dropout_prob
										SCREAMING_SNAKE_CASE_		:     str					=					attention_probs_dropout_prob
										SCREAMING_SNAKE_CASE_		:     Tuple					=					max_position_embeddings
										SCREAMING_SNAKE_CASE_		:     Any					=					type_vocab_size
										SCREAMING_SNAKE_CASE_		:     str					=					type_sequence_label_size
										SCREAMING_SNAKE_CASE_		:     str					=					initializer_range
										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					num_choices






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					ids_tensor([self.batch_size, self.seq_length]			,						self.vocab_size       )

										SCREAMING_SNAKE_CASE_		:     str					=					None
										if self.use_attention_mask:
													SCREAMING_SNAKE_CASE_		:     Union[str, Any]					=					random_attention_mask([self.batch_size, self.seq_length]       )

										SCREAMING_SNAKE_CASE_		:     Optional[int]					=					None
										if self.use_token_type_ids:
													SCREAMING_SNAKE_CASE_		:     List[Any]					=					ids_tensor([self.batch_size, self.seq_length]			,						self.type_vocab_size       )

										SCREAMING_SNAKE_CASE_		:     Any					=					RobertaConfig(
										    vocab_size=self.vocab_size			,						hidden_size=self.hidden_size			,						num_hidden_layers=self.num_hidden_layers			,						num_attention_heads=self.num_attention_heads			,						intermediate_size=self.intermediate_size			,						hidden_act=self.hidden_act			,						hidden_dropout_prob=self.hidden_dropout_prob			,						attention_probs_dropout_prob=self.attention_probs_dropout_prob			,						max_position_embeddings=self.max_position_embeddings			,						type_vocab_size=self.type_vocab_size			,						is_decoder=lowerCAmelCase__			,						initializer_range=self.initializer_range			,						)

										return config, input_ids, token_type_ids, attention_mask






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     str					=					self.prepare_config_and_inputs()
										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     str					=					config_and_inputs
										SCREAMING_SNAKE_CASE_		:     List[str]					=					{'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
										return config, inputs_dict






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     List[str]					=					self.prepare_config_and_inputs()
										SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		,      SCREAMING_SNAKE_CASE_		:     Optional[Any]					=					config_and_inputs

										SCREAMING_SNAKE_CASE_		:     str					=					True
										SCREAMING_SNAKE_CASE_		:     Dict					=					floats_tensor([self.batch_size, self.seq_length, self.hidden_size]       )
										SCREAMING_SNAKE_CASE_		:     int					=					ids_tensor([self.batch_size, self.seq_length]			,						vocab_size=2       )

										return (
										    config,
										    input_ids,
										    token_type_ids,
										    encoder_hidden_states,
										    encoder_attention_mask,
										)







@require_flax
class 	__lowercase    (__SCREAMING_SNAKE_CASE	,       unittest.TestCase  ):





							"""simple docstring"""







							_UpperCAmelCase      =						True

							_UpperCAmelCase      =						(
							    (
							        FlaxRobertaModel,
							        FlaxRobertaForCausalLM,
							        FlaxRobertaForMaskedLM,
							        FlaxRobertaForSequenceClassification,
							        FlaxRobertaForTokenClassification,
							        FlaxRobertaForMultipleChoice,
							        FlaxRobertaForQuestionAnswering,
							    )
							    if is_flax_available()
							    else ()
							)






							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										SCREAMING_SNAKE_CASE_		:     Any					=					FlaxRobertaModelTester(self       )






							@slow
							def 					UpperCamelCase__     (      self       ):





										"""simple docstring"""




										for model_class_name in self.all_model_classes:
													SCREAMING_SNAKE_CASE_		:     List[str]					=					model_class_name.from_pretrained('roberta-base'			,						from_pt=lowerCAmelCase__       )
													SCREAMING_SNAKE_CASE_		:     str					=					model(np.ones((1, 1)       )       )
													self.assertIsNotNone(lowerCAmelCase__       )





