






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


A_		:		Dict		     =			logging.getLogger(__name__)

def   snake_case (UpperCAmelCase__     ,   UpperCAmelCase__  )	->    List[str]:
		return (preds == labels).mean()




@dataclass
class     _lowerCAmelCase:





							"""simple docstring"""







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







@dataclass
class     _lowerCAmelCase:





							"""simple docstring"""







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







def   snake_case ()	->    Tuple:
		UpperCamelCase_: Optional[int]   				=    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)  )
		UpperCamelCase_				,UpperCamelCase_				,UpperCamelCase_: Dict   				=    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'     ,   UpperCAmelCase__  )

		# Set seed
		set_seed(training_args.seed  )

		try:
				UpperCamelCase_: Union[str, Any]   				=    processors[data_args.task_name]()
				UpperCamelCase_: int   				=    processor.get_labels()
				UpperCamelCase_: List[Any]   				=    len(UpperCAmelCase__  )
		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_: Dict   				=    AutoConfig.from_pretrained(
		    model_args.config_name if model_args.config_name else model_args.model_name_or_path     ,   num_labels=UpperCAmelCase__     ,   finetuning_task=data_args.task_name     ,   cache_dir=model_args.cache_dir     ,   )
		UpperCamelCase_: int   				=    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_: Any   				=    AutoModelForMultipleChoice.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     ,   )

		# Get datasets
		UpperCamelCase_: List[Any]   				=    (
		    MultipleChoiceDataset(
		        data_dir=data_args.data_dir     ,   tokenizer=UpperCAmelCase__     ,   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=UpperCAmelCase__     ,   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(UpperCAmelCase__  ) -> Dict:
				UpperCamelCase_: Any   				=    np.argmax(p.predictions     ,   axis=1  )
				return {"acc": simple_accuracy(UpperCAmelCase__     ,   p.label_ids  )}

		# Data collator
		UpperCamelCase_: Optional[int]   				=    DataCollatorWithPadding(UpperCAmelCase__     ,   pad_to_multiple_of=8  ) if training_args.fpaa else None

		# Initialize our Trainer
		UpperCamelCase_: int   				=    Trainer(
		    model=UpperCAmelCase__     ,   args=UpperCAmelCase__     ,   train_dataset=UpperCAmelCase__     ,   eval_dataset=UpperCAmelCase__     ,   compute_metrics=UpperCAmelCase__     ,   data_collator=UpperCAmelCase__     ,   )

		# 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_: Union[str, Any]   				=    trainer.evaluate()

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

								results.update(UpperCAmelCase__  )

		return results

def   snake_case (UpperCAmelCase__  )	->    Dict:
		main()


if __name__ == "__main__":
			main()







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


A_		:		List[Any]		     =			logging.get_logger(__name__)

A_		:		Optional[Any]		     =			{
    'YituTech/conv-bert-base': 'https://huggingface.co/YituTech/conv-bert-base/resolve/main/config.json',
    'YituTech/conv-bert-medium-small': (
        'https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/config.json'
    ),
    'YituTech/conv-bert-small': 'https://huggingface.co/YituTech/conv-bert-small/resolve/main/config.json',
    # See all ConvBERT models at https://huggingface.co/models?filter=convbert
}




class     _lowerCAmelCase(	UpperCAmelCase_ ):





       """simple docstring"""







       a    :		str									='''convbert'''





       def __init__( self  ,      _lowerCamelCase=3_0_5_2_2  ,      _lowerCamelCase=7_6_8  ,      _lowerCamelCase=1_2  ,      _lowerCamelCase=1_2  ,      _lowerCamelCase=3_0_7_2  ,      _lowerCamelCase="gelu"  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=0.1  ,      _lowerCamelCase=5_1_2  ,      _lowerCamelCase=2  ,      _lowerCamelCase=0.0_2  ,      _lowerCamelCase=1e-12  ,      _lowerCamelCase=1  ,      _lowerCamelCase=0  ,      _lowerCamelCase=2  ,      _lowerCamelCase=7_6_8  ,      _lowerCamelCase=2  ,      _lowerCamelCase=9  ,      _lowerCamelCase=1  ,      _lowerCamelCase=None  ,      **_lowerCamelCase  ,      ):
         super().__init__(
             pad_token_id=_lowerCamelCase  ,      bos_token_id=_lowerCamelCase  ,      eos_token_id=_lowerCamelCase  ,      **_lowerCamelCase  ,      )

         UpperCamelCase_: Dict   				=    vocab_size
         UpperCamelCase_: Tuple   				=    hidden_size
         UpperCamelCase_: Optional[int]   				=    num_hidden_layers
         UpperCamelCase_: Optional[int]   				=    num_attention_heads
         UpperCamelCase_: Optional[Any]   				=    intermediate_size
         UpperCamelCase_: Tuple   				=    hidden_act
         UpperCamelCase_: Any   				=    hidden_dropout_prob
         UpperCamelCase_: Any   				=    attention_probs_dropout_prob
         UpperCamelCase_: List[Any]   				=    max_position_embeddings
         UpperCamelCase_: List[Any]   				=    type_vocab_size
         UpperCamelCase_: Optional[int]   				=    initializer_range
         UpperCamelCase_: Tuple   				=    layer_norm_eps
         UpperCamelCase_: List[str]   				=    embedding_size
         UpperCamelCase_: int   				=    head_ratio
         UpperCamelCase_: Dict   				=    conv_kernel_size
         UpperCamelCase_: List[Any]   				=    num_groups
         UpperCamelCase_: Dict   				=    classifier_dropout







class     _lowerCAmelCase(	UpperCAmelCase_ ):





       """simple docstring"""







       @property
       def       _a   ( self							):
         if self.task == "multiple-choice":
           UpperCamelCase_: Dict   				=    {0: 'batch', 1: 'choice', 2: 'sequence'}
         else:
           UpperCamelCase_: Dict   				=    {0: 'batch', 1: 'sequence'}
         return OrderedDict(
             [
                 ('input_ids', dynamic_axis),
                 ('attention_mask', dynamic_axis),
                 ('token_type_ids', dynamic_axis),
             ]							)