
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	      = logging.getLogger(__name__)






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE ,							__SCREAMING_SNAKE_CASE							):
	return (preds == labels).mean()







@dataclass
class        A_   :




	'''simple docstring'''


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







@dataclass
class        A_   :




	'''simple docstring'''


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






def 							UpperCAmelCase_		(							):
	# 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.

	lowercase       =    HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)							)
	lowercase  ,					lowercase  ,					lowercase       =    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' ,							__SCREAMING_SNAKE_CASE							)

	# Set seed
	set_seed(training_args.seed							)

	try:
		lowercase       =    processors[data_args.task_name]()
		lowercase       =    processor.get_labels()
		lowercase       =    len(__SCREAMING_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.

	lowercase       =    AutoConfig.from_pretrained(
	    model_args.config_name if model_args.config_name else model_args.model_name_or_path ,							num_labels=__SCREAMING_SNAKE_CASE ,							finetuning_task=data_args.task_name ,							cache_dir=model_args.cache_dir ,							)
	lowercase       =    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 ,							)
	lowercase       =    AutoModelForMultipleChoice.from_pretrained(
	    model_args.model_name_or_path ,							from_tf=bool('.ckpt' in model_args.model_name_or_path							) ,							config=__SCREAMING_SNAKE_CASE ,							cache_dir=model_args.cache_dir ,							)

	# Get datasets
	lowercase       =    (
	    MultipleChoiceDataset(
	        data_dir=data_args.data_dir ,							tokenizer=__SCREAMING_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
	)
	lowercase       =    (
	    MultipleChoiceDataset(
	        data_dir=data_args.data_dir ,							tokenizer=__SCREAMING_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(__SCREAMING_SNAKE_CASE							) -> Dict:
		lowercase       =    np.argmax(p.predictions ,							axis=1							)
		return {"acc": simple_accuracy(__SCREAMING_SNAKE_CASE ,							p.label_ids							)}

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

	# Initialize our Trainer
	lowercase       =    Trainer(
	    model=__SCREAMING_SNAKE_CASE ,							args=__SCREAMING_SNAKE_CASE ,							train_dataset=__SCREAMING_SNAKE_CASE ,							eval_dataset=__SCREAMING_SNAKE_CASE ,							compute_metrics=__SCREAMING_SNAKE_CASE ,							data_collator=__SCREAMING_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
	lowercase       =    {}
	if training_args.do_eval:
		logger.info('*** Evaluate ***'							)

		lowercase       =    trainer.evaluate()

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

				results.update(__SCREAMING_SNAKE_CASE							)

	return results






def 							UpperCAmelCase_		(							__SCREAMING_SNAKE_CASE							):
	# For xla_spawn (TPUs)
	main()


if __name__ == "__main__":
	main()



import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase	      = logging.get_logger(__name__)

UpperCAmelCase	      = {
    '''xlnet-base-cased''': '''https://huggingface.co/xlnet-base-cased/resolve/main/config.json''',
    '''xlnet-large-cased''': '''https://huggingface.co/xlnet-large-cased/resolve/main/config.json''',
}







class        A_   (			__lowerCamelCase   ):




	'''simple docstring'''


	_UpperCamelCase     :     Tuple							 =       """xlnet"""
	_UpperCamelCase     :     Optional[Any]							 =       ["""mems"""]
	_UpperCamelCase     :     Tuple							 =       {
	    """n_token""": """vocab_size""",  # Backward compatibility
	    """hidden_size""": """d_model""",
	    """num_attention_heads""": """n_head""",
	    """num_hidden_layers""": """n_layer""",
	}





	def __init__(       self		,    snake_case=3_2000		,    snake_case=1024		,    snake_case=24		,    snake_case=16		,    snake_case=4096		,    snake_case="gelu"		,    snake_case=True		,    snake_case="bi"		,    snake_case=0.02		,    snake_case=1E-12		,    snake_case=0.1		,    snake_case=512		,    snake_case=None		,    snake_case=True		,    snake_case=False		,    snake_case=False		,    snake_case=-1		,    snake_case=False		,    snake_case="last"		,    snake_case=True		,    snake_case="tanh"		,    snake_case=0.1		,    snake_case=5		,    snake_case=5		,    snake_case=5		,    snake_case=1		,    snake_case=2		,    **snake_case		,    ):
		lowercase       =    vocab_size
		lowercase       =    d_model
		lowercase       =    n_layer
		lowercase       =    n_head
		if d_model % n_head != 0:
			raise ValueError(F'''\'d_model % n_head\' ({d_model % n_head}) should be equal to 0'''       )
		if "d_head" in kwargs:
			if kwargs["d_head"] != d_model // n_head:
				raise ValueError(
				    F'''`d_head` ({kwargs['d_head']}) should be equal to `d_model // n_head` ({d_model // n_head})'''       )
		lowercase       =    d_model // n_head
		lowercase       =    ff_activation
		lowercase       =    d_inner
		lowercase       =    untie_r
		lowercase       =    attn_type

		lowercase       =    initializer_range
		lowercase       =    layer_norm_eps

		lowercase       =    dropout
		lowercase       =    mem_len
		lowercase       =    reuse_len
		lowercase       =    bi_data
		lowercase       =    clamp_len
		lowercase       =    same_length

		lowercase       =    summary_type
		lowercase       =    summary_use_proj
		lowercase       =    summary_activation
		lowercase       =    summary_last_dropout
		lowercase       =    start_n_top
		lowercase       =    end_n_top

		lowercase       =    bos_token_id
		lowercase       =    pad_token_id
		lowercase       =    eos_token_id

		if "use_cache" in kwargs:
			warnings.warn(
			    'The `use_cache` argument is deprecated and will be removed in a future version, use `use_mems_eval`'
			    ' instead.'		,    snake_case		,    )
			lowercase       =    kwargs['use_cache']

		lowercase       =    use_mems_eval
		lowercase       =    use_mems_train
		super().__init__(pad_token_id=snake_case		,    bos_token_id=snake_case		,    eos_token_id=snake_case		,    **snake_case       )





	@property
	def 	SCREAMING_SNAKE_CASE__						(       self       ):
		logger.info(F'''The model {self.model_type} is one of the few models that has no sequence length limit.'''       )
		return -1





	@max_position_embeddings.setter
	def 	SCREAMING_SNAKE_CASE__						(       self		,    snake_case       ):
		# Message copied from Transformer-XL documentation
		raise NotImplementedError(
		    F'''The model {self.model_type} is one of the few models that has no sequence length limit.'''       )

