



'''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


snake_case_			=     logging.getLogger(__name__)






def       __lowercase  (_SCREAMING_SNAKE_CASE      :List[str]    ,	_SCREAMING_SNAKE_CASE      :List[str]       ):
				return (preds == labels).mean()


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



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






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

				SCREAMING_SNAKE_CASE  :						str      					= HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
				SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE					,					SCREAMING_SNAKE_CASE  :						Optional[int]      					= 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:
								SCREAMING_SNAKE_CASE  :						Optional[Any]      					= processors[data_args.task_name]()
								SCREAMING_SNAKE_CASE  :						List[str]      					= processor.get_labels()
								SCREAMING_SNAKE_CASE  :						int      					= 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.

				SCREAMING_SNAKE_CASE  :						Any      					= 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    ,	)
				SCREAMING_SNAKE_CASE  :						str      					= 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    ,	)
				SCREAMING_SNAKE_CASE  :						Any      					= 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
				SCREAMING_SNAKE_CASE  :						Optional[int]      					= (
				    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
				)
				SCREAMING_SNAKE_CASE  :						int      					= (
				    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      :EvalPrediction       ) -> Dict:
								SCREAMING_SNAKE_CASE  :						str      					= np.argmax(p.predictions    ,	axis=1       )
								return {"acc": simple_accuracy(_SCREAMING_SNAKE_CASE    ,	p.label_ids       )}

				# Data collator
				SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= DataCollatorWithPadding(_SCREAMING_SNAKE_CASE    ,	pad_to_multiple_of=8       ) if training_args.fpaa else None

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

								SCREAMING_SNAKE_CASE  :						Optional[int]      					= trainer.evaluate()

								SCREAMING_SNAKE_CASE  :						List[Any]      					= 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       __lowercase  (_SCREAMING_SNAKE_CASE      :Any       ):
				# For xla_spawn (TPUs)
				main()


if __name__ == "__main__":
	main()









'''simple docstring'''

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


snake_case_			=     logging.get_logger(__name__)

snake_case_			=     {
    """facebook/nllb-moe-54B""": """https://huggingface.co/facebook/nllb-moe-54b/resolve/main/config.json""",
}


class 	a__     (				_lowercase	):
	__magic_name__		:    Optional[Any]	    =     "nllb-moe"
	__magic_name__		:    Optional[Any]	    =     ["past_key_values"]
	__magic_name__		:    Optional[int]	    =     {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}


	def __init__(self : int,					__UpperCAmelCase : Tuple=128112,					__UpperCAmelCase : Any=1024,					__UpperCAmelCase : Optional[Any]=12,					__UpperCAmelCase : Optional[int]=4096,					__UpperCAmelCase : Any=16,					__UpperCAmelCase : Any=12,					__UpperCAmelCase : Optional[Any]=4096,					__UpperCAmelCase : Optional[int]=16,					__UpperCAmelCase : List[Any]=0.05,					__UpperCAmelCase : Dict=0.05,					__UpperCAmelCase : Dict=True,					__UpperCAmelCase : List[Any]=True,					__UpperCAmelCase : Any="relu",					__UpperCAmelCase : Union[str, Any]=1024,					__UpperCAmelCase : Optional[int]=0.1,					__UpperCAmelCase : Tuple=0.1,					__UpperCAmelCase : List[Any]=0.0,					__UpperCAmelCase : Optional[int]=0.02,					__UpperCAmelCase : Tuple=2,					__UpperCAmelCase : int=True,					__UpperCAmelCase : int=False,					__UpperCAmelCase : int="float32",					__UpperCAmelCase : Optional[Any]=False,					__UpperCAmelCase : List[str]=128,					__UpperCAmelCase : Dict=64,					__UpperCAmelCase : Dict=4,					__UpperCAmelCase : Optional[Any]=4,					__UpperCAmelCase : Optional[Any]=0.001,					__UpperCAmelCase : Optional[Any]=0.001,					__UpperCAmelCase : Optional[Any]="all",					__UpperCAmelCase : List[str]=False,					__UpperCAmelCase : Dict=False,					__UpperCAmelCase : Any=1.0,					__UpperCAmelCase : Dict=0.2,					__UpperCAmelCase : int=1,					__UpperCAmelCase : Union[str, Any]=0,					__UpperCAmelCase : Any=2,					__UpperCAmelCase : Union[str, Any]=False,					**__UpperCAmelCase : Dict,					)     ->			List[Any]:

					"""simple docstring"""

					SCREAMING_SNAKE_CASE  :						Any      					= vocab_size
					SCREAMING_SNAKE_CASE  :						int      					= max_position_embeddings
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= d_model
					SCREAMING_SNAKE_CASE  :						Dict      					= encoder_ffn_dim
					SCREAMING_SNAKE_CASE  :						int      					= encoder_layers
					SCREAMING_SNAKE_CASE  :						str      					= encoder_attention_heads
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= decoder_ffn_dim
					SCREAMING_SNAKE_CASE  :						str      					= decoder_layers
					SCREAMING_SNAKE_CASE  :						Dict      					= decoder_attention_heads
					SCREAMING_SNAKE_CASE  :						Dict      					= dropout
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= attention_dropout
					SCREAMING_SNAKE_CASE  :						Dict      					= activation_dropout
					SCREAMING_SNAKE_CASE  :						List[str]      					= activation_function
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= init_std
					SCREAMING_SNAKE_CASE  :						Any      					= encoder_layerdrop
					SCREAMING_SNAKE_CASE  :						Optional[int]      					= decoder_layerdrop
					SCREAMING_SNAKE_CASE  :						Dict      					= use_cache
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= encoder_layers
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= scale_embedding  # scale factor will be sqrt(d_model) if True
					SCREAMING_SNAKE_CASE  :						List[str]      					= router_z_loss_coef
					SCREAMING_SNAKE_CASE  :						List[str]      					= router_aux_loss_coef
					SCREAMING_SNAKE_CASE  :						int      					= decoder_sparse_step
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= encoder_sparse_step
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= num_experts
					SCREAMING_SNAKE_CASE  :						List[Any]      					= expert_capacity
					SCREAMING_SNAKE_CASE  :						Optional[Any]      					= router_bias
					if router_dtype not in ["float32", "float16", "bfloat16"]:
									raise ValueError(F'''`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'''      )
					SCREAMING_SNAKE_CASE  :						Union[str, Any]      					= router_dtype

					SCREAMING_SNAKE_CASE  :						int      					= router_ignore_padding_tokens
					SCREAMING_SNAKE_CASE  :						Dict      					= batch_prioritized_routing
					SCREAMING_SNAKE_CASE  :						Dict      					= second_expert_policy
					SCREAMING_SNAKE_CASE  :						Tuple      					= normalize_router_prob_before_dropping
					SCREAMING_SNAKE_CASE  :						List[str]      					= moe_eval_capacity_token_fraction
					SCREAMING_SNAKE_CASE  :						List[Any]      					= moe_token_dropout
					SCREAMING_SNAKE_CASE  :						List[Any]      					= output_router_logits
					super().__init__(
					    pad_token_id=__UpperCAmelCase,					bos_token_id=__UpperCAmelCase,					eos_token_id=__UpperCAmelCase,					is_encoder_decoder=__UpperCAmelCase,					decoder_start_token_id=__UpperCAmelCase,					**__UpperCAmelCase,					)




