from sklearn.metrics import matthews_corrcoef

import datasets


_lowerCAmelCase       =		"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

_lowerCAmelCase       =		"\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

_lowerCAmelCase       =		"\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION,  _KWARGS_DESCRIPTION )
class     lowerCAmelCase_     (       datasets.Metric ):







							def  UpperCamelCase_						(   self      :     Dict		):
												return datasets.MetricInfo(
												    description=_DESCRIPTION ,			citation=_CITATION ,			inputs_description=_KWARGS_DESCRIPTION ,			features=datasets.Features(
												        {
												            '''predictions''': datasets.Value('''int32'''		),
												            '''references''': datasets.Value('''int32'''		),
												        }		) ,			reference_urls=[
												        '''https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'''
												    ] ,			)







							def  UpperCamelCase_						(   self      :     List[str] ,			_A      :     List[str] ,			_A      :     str ,			_A      :     str=None		):
												return {
												    "matthews_correlation": float(matthews_corrcoef(_A ,			_A ,			sample_weight=_A		)		),
												}

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()
