


"""simple docstring"""






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


UpperCamelCase__				:Dict			   =	logging.getLogger(__name__)





def 				A_       ( snake_case__       ,					snake_case__		)					->  Optional[Any]:
			return (preds == labels).mean()






@dataclass
class      A:

		"""simple docstring"""





		A    =							field(
		    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}		)
		A    =							field(
		    default=lowerCamelCase__				,							metadata={"help": "Pretrained config name or path if not the same as model_name"}		)
		A    =							field(
		    default=lowerCamelCase__				,							metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}		)
		A    =							field(
		    default=lowerCamelCase__				,							metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}				,							)






@dataclass
class      A:

		"""simple docstring"""





		A    =							field(metadata={"help": "The name of the task to train on: " + ", ".join(processors.keys()		)}		)
		A    =							field(metadata={"help": "Should contain the data files for the task."}		)
		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=lowerCamelCase__				,							metadata={"help": "Overwrite the cached training and evaluation sets"}		)





def 				A_       ( )					->  Optional[Any]:
			# 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					:Any					     =	HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
			_UpperCamelCase     ,      _UpperCamelCase     ,      _UpperCamelCase					:str					     =	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					:int					     =	processors[data_args.task_name]()
						_UpperCamelCase					:List[str]					     =	processor.get_labels()
						_UpperCamelCase					:Optional[Any]					     =	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					:Optional[int]					     =	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					:Dict					     =	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					:List[str]					     =	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					:Optional[Any]					     =	(
			    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					:Union[str, Any]					     =	(
			    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					:Dict					     =	np.argmax(p.predictions       ,					axis=1		)
						return {"acc": simple_accuracy(snake_case__       ,					p.label_ids		)}

			# Data collator
			_UpperCamelCase					:List[str]					     =	DataCollatorWithPadding(snake_case__       ,					pad_to_multiple_of=8		) if training_args.fpaa else None

			# Initialize our Trainer
			_UpperCamelCase					:Optional[Any]					     =	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					:List[Any]					     =	{}
			if training_args.do_eval:
						logger.info('''*** Evaluate ***'''		)

						_UpperCamelCase					:Any					     =	trainer.evaluate()

						_UpperCamelCase					:Optional[Any]					     =	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 				A_       ( snake_case__		)					->  Dict:
			# For xla_spawn (TPUs)
			main()


if __name__ == "__main__":
					main()





"""simple docstring"""






import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate





def 				A_       ( snake_case__		)					->  Union[str, Any]:
			return x + 2






class      A(  unittest.TestCase		):

		"""simple docstring"""





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

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	'''x = 3'''
					_UpperCamelCase					:List[str]					     =	{}
					_UpperCamelCase					:int					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3}   )

					_UpperCamelCase					:Tuple					     =	'''x = y'''
					_UpperCamelCase					:Optional[int]					     =	{'''y''': 5}
					_UpperCamelCase					:Optional[Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 5, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''y = add_two(x)'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )

					# Won't work without the tool
					with CaptureStdout() as out:
								_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result is None
					assert "tried to execute add_two" in out.out
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	'''x = 3'''
					_UpperCamelCase					:int					     =	{}
					_UpperCamelCase					:List[Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3}   )
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''test_dict = {\'x\': x, \'y\': add_two(x)}'''
					_UpperCamelCase					:str					     =	{'''x''': 3}
					_UpperCamelCase					:Dict					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	'''x = 3\ny = 5'''
					_UpperCamelCase					:int					     =	{}
					_UpperCamelCase					:Optional[int]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	'''text = f\'This is x: {x}.\''''
					_UpperCamelCase					:List[str]					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == "This is x: 3."
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''text''': '''This is x: 3.'''}   )
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[Any]					     =	'''if x <= 3:\n    y = 2\nelse:\n    y = 5'''
					_UpperCamelCase					:Dict					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 2
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 2}   )

					_UpperCamelCase					:Union[str, Any]					     =	{'''x''': 8}
					_UpperCamelCase					:Optional[int]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					# evaluate returns the value of the last assignment.
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 8, '''y''': 5}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	'''test_list = [x, add_two(x)]'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:str					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					self.assertListEqual(SCREAMING_SNAKE_CASE__					,				[3, 5]   )
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_list''': [3, 5]}   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:List[Any]					     =	'''y = x'''
					_UpperCamelCase					:List[str]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 3
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''y''': 3}   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	'''test_list = [x, add_two(x)]\ntest_list[1]'''
					_UpperCamelCase					:Optional[Any]					     =	{'''x''': 3}
					_UpperCamelCase					:Any					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_list''': [3, 5]}   )

					_UpperCamelCase					:str					     =	'''test_dict = {\'x\': x, \'y\': add_two(x)}\ntest_dict[\'y\']'''
					_UpperCamelCase					:Optional[int]					     =	{'''x''': 3}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''add_two''': add_two}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 5
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 3, '''test_dict''': {'''x''': 3, '''y''': 5}}   )





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	'''x = 0\nfor i in range(3):\n    x = i'''
					_UpperCamelCase					:Tuple					     =	{}
					_UpperCamelCase					:Union[str, Any]					     =	evaluate(SCREAMING_SNAKE_CASE__					,				{'''range''': range}					,				state=SCREAMING_SNAKE_CASE__   )
					assert result == 2
					self.assertDictEqual(SCREAMING_SNAKE_CASE__					,				{'''x''': 2, '''i''': 2}   )

