


import logging
import os
import sys
from dataclasses import dataclass, field
from itertools import chain
from typing import Optional, Union

import datasets
import numpy as np
import torch
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForMultipleChoice,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import PaddingStrategy, check_min_version, send_example_telemetry


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

A   :					Any	=      logging.getLogger(__name__)







@dataclass
class     _lowercase				:


							"""simple docstring"""




							A__      		=    field(
							    metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"})
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "Pretrained config name or path if not the same as model_name"})
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"})
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}							,						)
							A__      		=    field(
							    default="main"							,						metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={
							        "help": (
							            "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
							            "with private models)."
							        )
							    }							,						)







@dataclass
class     _lowercase				:


							"""simple docstring"""




							A__      		=    field(default=UpperCamelCase__							,						metadata={"help": "The input training data file (a text file)."})
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "Overwrite the cached training and evaluation sets"})
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={"help": "The number of processes to use for the preprocessing."}							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={
							        "help": (
							            "The maximum total input sequence length after tokenization. If passed, sequences longer "
							            "than this will be truncated, sequences shorter will be padded."
							        )
							    }							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={
							        "help": (
							            "Whether to pad all samples to the maximum sentence length. "
							            "If False, will pad the samples dynamically when batching to the maximum length in the batch. More "
							            "efficient on GPU but very bad for TPU."
							        )
							    }							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={
							        "help": (
							            "For debugging purposes or quicker training, truncate the number of training examples to this "
							            "value if set."
							        )
							    }							,						)
							A__      		=    field(
							    default=UpperCamelCase__							,						metadata={
							        "help": (
							            "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
							            "value if set."
							        )
							    }							,						)





							def 		lowerCAmelCase  (     self							:    List[Any] ):


													'''simple docstring'''



													if self.train_file is not None:
																			lowerCamelCase__	:       List[str]					=						self.train_file.split("." )[-1]
																			assert extension in ["csv", "json"], "`train_file` should be a csv or a json file."
													if self.validation_file is not None:
																			lowerCamelCase__	:       Tuple					=						self.validation_file.split("." )[-1]
																			assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."







@dataclass
class     _lowercase				:


							"""simple docstring"""




							A__      		=    42
							A__      		=    True
							A__      		=    None
							A__      		=    None





							def __call__(     self							:    Union[str, Any]      ,   __lowerCamelCase							:    Any ):


													'''simple docstring'''



													lowerCamelCase__	:       List[str]					=						"label" if "label" in features[0].keys() else "labels"
													lowerCamelCase__	:       Union[str, Any]					=						[feature.pop(__lowerCamelCase ) for feature in features]
													lowerCamelCase__	:       str					=						len(__lowerCamelCase )
													lowerCamelCase__	:       Dict					=						len(features[0]["input_ids"] )
													lowerCamelCase__	:       Union[str, Any]					=						[
													    [{k: v[i] for k, v in feature.items()} for i in range(__lowerCamelCase )] for feature in features
													]
													lowerCamelCase__	:       Any					=						list(chain(*__lowerCamelCase ) )

													lowerCamelCase__	:       Optional[Any]					=						self.tokenizer.pad(
													    __lowerCamelCase      ,   padding=self.padding      ,   max_length=self.max_length      ,   pad_to_multiple_of=self.pad_to_multiple_of      ,   return_tensors="pt"      ,   )

													# Un-flatten
													lowerCamelCase__	:       List[str]					=						{k: v.view(__lowerCamelCase      ,   __lowerCamelCase      ,   -1 ) for k, v in batch.items()}
													# Add back labels
													lowerCamelCase__	:       str					=						torch.tensor(__lowerCamelCase      ,   dtype=torch.intaa )
													return batch



def    lowercase_	(	):

						"""simple docstring"""




						lowerCamelCase__	:       Any					=						HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)		)
						if len(sys.argv		) == 2 and sys.argv[1].endswith(".json"		):
												# If we pass only one argument to the script and it's the path to a json file,
												# let's parse it to get our arguments.
												lowerCamelCase__					,     lowerCamelCase__					,     lowerCamelCase__	:       Dict					=						parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]		)		)
						else:
												lowerCamelCase__					,     lowerCamelCase__					,     lowerCamelCase__	:       int					=						parser.parse_args_into_dataclasses()

						# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
						# information sent is the one passed as arguments along with your Python/PyTorch versions.
						send_example_telemetry("run_swag"					,      _A					,      _A		)

						# Setup logging
						logging.basicConfig(
						    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"					,      datefmt="%m/%d/%Y %H:%M:%S"					,      handlers=[logging.StreamHandler(sys.stdout		)]					,      )

						if training_args.should_log:
												# The default of training_args.log_level is passive, so we set log level at info here to have that default.
												transformers.utils.logging.set_verbosity_info()

						lowerCamelCase__	:       int					=						training_args.get_process_log_level()
						logger.setLevel(_A		)
						datasets.utils.logging.set_verbosity(_A		)
						transformers.utils.logging.set_verbosity(_A		)
						transformers.utils.logging.enable_default_handler()
						transformers.utils.logging.enable_explicit_format()

						# Log on each process the small summary:
						logger.warning(
						    F"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}"
						    + F"distributed training: {bool(training_args.local_rank != -1		)}, 16-bits training: {training_args.fpaa}"		)
						logger.info(F"Training/evaluation parameters {training_args}"		)

						# Detecting last checkpoint.
						lowerCamelCase__	:       Optional[Any]					=						None
						if os.path.isdir(training_args.output_dir		) and training_args.do_train and not training_args.overwrite_output_dir:
												lowerCamelCase__	:       Any					=						get_last_checkpoint(training_args.output_dir		)
												if last_checkpoint is None and len(os.listdir(training_args.output_dir		)		) > 0:
																		raise ValueError(
																		    F"Output directory ({training_args.output_dir}) already exists and is not empty. "
																		    "Use --overwrite_output_dir to overcome."		)
												elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
																		logger.info(
																		    F"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change "
																		    "the `--output_dir` or add `--overwrite_output_dir` to train from scratch."		)

    # Set seed before initializing model.
						set_seed(training_args.seed		)

						# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
						# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
						# (the dataset will be downloaded automatically from the datasets Hub).

						# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
						# 'text' is found. You can easily tweak this behavior (see below).

						# In distributed training, the load_dataset function guarantee that only one local process can concurrently
						# download the dataset.
						if data_args.train_file is not None or data_args.validation_file is not None:
												lowerCamelCase__	:       Dict					=						{}
												if data_args.train_file is not None:
																		lowerCamelCase__	:       Any					=						data_args.train_file
												if data_args.validation_file is not None:
																		lowerCamelCase__	:       str					=						data_args.validation_file
												lowerCamelCase__	:       Dict					=						data_args.train_file.split("."		)[-1]
												lowerCamelCase__	:       List[str]					=						load_dataset(
												    _A					,      data_files=_A					,      cache_dir=model_args.cache_dir					,      use_auth_token=True if model_args.use_auth_token else None					,      )
						else:
												# Downloading and loading the swag dataset from the hub.
												lowerCamelCase__	:       Dict					=						load_dataset(
												    "swag"					,      "regular"					,      cache_dir=model_args.cache_dir					,      use_auth_token=True if model_args.use_auth_token else None					,      )
						# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
						# https://huggingface.co/docs/datasets/loading_datasets.html.

						# Load pretrained model and tokenizer

						# Distributed training:
						# The .from_pretrained methods guarantee that only one local process can concurrently
						# download model & vocab.
						lowerCamelCase__	:       int					=						AutoConfig.from_pretrained(
						    model_args.config_name if model_args.config_name else model_args.model_name_or_path					,      cache_dir=model_args.cache_dir					,      revision=model_args.model_revision					,      use_auth_token=True if model_args.use_auth_token else None					,      )
						lowerCamelCase__	:       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					,      use_fast=model_args.use_fast_tokenizer					,      revision=model_args.model_revision					,      use_auth_token=True if model_args.use_auth_token else None					,      )
						lowerCamelCase__	:       Dict					=						AutoModelForMultipleChoice.from_pretrained(
						    model_args.model_name_or_path					,      from_tf=bool(".ckpt" in model_args.model_name_or_path		)					,      config=_A					,      cache_dir=model_args.cache_dir					,      revision=model_args.model_revision					,      use_auth_token=True if model_args.use_auth_token else None					,      )

						# When using your own dataset or a different dataset from swag, you will probably need to change this.
						lowerCamelCase__	:       str					=						[F"ending{i}" for i in range(4		)]
						lowerCamelCase__	:       Dict					=						"sent1"
						lowerCamelCase__	:       str					=						"sent2"

						if data_args.max_seq_length is None:
												lowerCamelCase__	:       Optional[int]					=						tokenizer.model_max_length
												if max_seq_length > 1024:
																		logger.warning(
																		    "The chosen tokenizer supports a `model_max_length` that is longer than the default `block_size` value"
																		    " of 1024. If you would like to use a longer `block_size` up to `tokenizer.model_max_length` you can"
																		    " override this default with `--block_size xxx`."		)
																		lowerCamelCase__	:       Any					=						1024
						else:
												if data_args.max_seq_length > tokenizer.model_max_length:
																		logger.warning(
																		    F"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
																		    F"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."		)
												lowerCamelCase__	:       int					=						min(data_args.max_seq_length					,      tokenizer.model_max_length		)

						# Preprocessing the datasets.
						def preprocess_function(_A    :					Tuple		):
												lowerCamelCase__	:       int					=						[[context] * 4 for context in examples[context_name]]
												lowerCamelCase__	:       List[str]					=						examples[question_header_name]
												lowerCamelCase__	:       Any					=						[
												    [F"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(_A		)
												]

												# Flatten out
												lowerCamelCase__	:       Tuple					=						list(chain(*_A		)		)
												lowerCamelCase__	:       Optional[Any]					=						list(chain(*_A		)		)

												# Tokenize
												lowerCamelCase__	:       List[Any]					=						tokenizer(
												    _A					,      _A					,      truncation=_A					,      max_length=_A					,      padding="max_length" if data_args.pad_to_max_length else False					,      )
												# Un-flatten
												return {k: [v[i : i + 4] for i in range(0					,      len(_A		)					,      4		)] for k, v in tokenized_examples.items()}

						if training_args.do_train:
												if "train" not in raw_datasets:
																		raise ValueError("--do_train requires a train dataset"		)
												lowerCamelCase__	:       Dict					=						raw_datasets["train"]
												if data_args.max_train_samples is not None:
																		lowerCamelCase__	:       Tuple					=						min(len(_A		)					,      data_args.max_train_samples		)
																		lowerCamelCase__	:       Any					=						train_dataset.select(range(_A		)		)
												with training_args.main_process_first(desc="train dataset map pre-processing"		):
																		lowerCamelCase__	:       Tuple					=						train_dataset.map(
																		    _A					,      batched=_A					,      num_proc=data_args.preprocessing_num_workers					,      load_from_cache_file=not data_args.overwrite_cache					,      )

						if training_args.do_eval:
												if "validation" not in raw_datasets:
																		raise ValueError("--do_eval requires a validation dataset"		)
												lowerCamelCase__	:       Union[str, Any]					=						raw_datasets["validation"]
												if data_args.max_eval_samples is not None:
																		lowerCamelCase__	:       Dict					=						min(len(_A		)					,      data_args.max_eval_samples		)
																		lowerCamelCase__	:       Dict					=						eval_dataset.select(range(_A		)		)
												with training_args.main_process_first(desc="validation dataset map pre-processing"		):
																		lowerCamelCase__	:       Optional[int]					=						eval_dataset.map(
																		    _A					,      batched=_A					,      num_proc=data_args.preprocessing_num_workers					,      load_from_cache_file=not data_args.overwrite_cache					,      )

    # Data collator
						lowerCamelCase__	:       Tuple					=						(
						    default_data_collator
						    if data_args.pad_to_max_length
						    else DataCollatorForMultipleChoice(tokenizer=_A					,      pad_to_multiple_of=8 if training_args.fpaa else None		)
						)

						# Metric
						def compute_metrics(_A    :					Dict		):
												lowerCamelCase__					,     lowerCamelCase__	:       Dict					=						eval_predictions
												lowerCamelCase__	:       int					=						np.argmax(_A					,      axis=1		)
												return {"accuracy": (preds == label_ids).astype(np.floataa		).mean().item()}

						# Initialize our Trainer
						lowerCamelCase__	:       Tuple					=						Trainer(
						    model=_A					,      args=_A					,      train_dataset=train_dataset if training_args.do_train else None					,      eval_dataset=eval_dataset if training_args.do_eval else None					,      tokenizer=_A					,      data_collator=_A					,      compute_metrics=_A					,      )

						# Training
						if training_args.do_train:
												lowerCamelCase__	:       Optional[int]					=						None
												if training_args.resume_from_checkpoint is not None:
																		lowerCamelCase__	:       Any					=						training_args.resume_from_checkpoint
												elif last_checkpoint is not None:
																		lowerCamelCase__	:       Optional[int]					=						last_checkpoint
												lowerCamelCase__	:       Tuple					=						trainer.train(resume_from_checkpoint=_A		)
												trainer.save_model()  # Saves the tokenizer too for easy upload
												lowerCamelCase__	:       List[Any]					=						train_result.metrics

												lowerCamelCase__	:       List[str]					=						(
												    data_args.max_train_samples if data_args.max_train_samples is not None else len(_A		)
												)
												lowerCamelCase__	:       Optional[Any]					=						min(_A					,      len(_A		)		)

												trainer.log_metrics("train"					,      _A		)
												trainer.save_metrics("train"					,      _A		)
												trainer.save_state()

						# Evaluation
						if training_args.do_eval:
												logger.info("*** Evaluate ***"		)

												lowerCamelCase__	:       Dict					=						trainer.evaluate()
												lowerCamelCase__	:       str					=						data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_A		)
												lowerCamelCase__	:       Any					=						min(_A					,      len(_A		)		)

												trainer.log_metrics("eval"					,      _A		)
												trainer.save_metrics("eval"					,      _A		)

						lowerCamelCase__	:       int					=						{
						    "finetuned_from": model_args.model_name_or_path,
						    "tasks": "multiple-choice",
						    "dataset_tags": "swag",
						    "dataset_args": "regular",
						    "dataset": "SWAG",
						    "language": "en",
						}

						if training_args.push_to_hub:
												trainer.push_to_hub(**_A		)
						else:
												trainer.create_model_card(**_A		)

def    lowercase_	(	_A    :					Tuple		):

						"""simple docstring"""




						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   :					int	=      logging.get_logger(__name__)

A   :					Optional[int]	=      {
    "facebook/xmod-base": "https://huggingface.co/facebook/xmod-base/resolve/main/config.json",
    "facebook/xmod-large-prenorm": "https://huggingface.co/facebook/xmod-large-prenorm/resolve/main/config.json",
    "facebook/xmod-base-13-125k": "https://huggingface.co/facebook/xmod-base-13-125k/resolve/main/config.json",
    "facebook/xmod-base-30-125k": "https://huggingface.co/facebook/xmod-base-30-125k/resolve/main/config.json",
    "facebook/xmod-base-30-195k": "https://huggingface.co/facebook/xmod-base-30-195k/resolve/main/config.json",
    "facebook/xmod-base-60-125k": "https://huggingface.co/facebook/xmod-base-60-125k/resolve/main/config.json",
    "facebook/xmod-base-60-265k": "https://huggingface.co/facebook/xmod-base-60-265k/resolve/main/config.json",
    "facebook/xmod-base-75-125k": "https://huggingface.co/facebook/xmod-base-75-125k/resolve/main/config.json",
    "facebook/xmod-base-75-269k": "https://huggingface.co/facebook/xmod-base-75-269k/resolve/main/config.json",
}







class     _lowercase				(							lowercase__):


       """simple docstring"""




       A__      		=    "xmod"





       def __init__(     self							:    int      ,   __lowerCamelCase							:    Any=30522      ,   __lowerCamelCase							:    Any=768      ,   __lowerCamelCase							:    str=12      ,   __lowerCamelCase							:    Any=12      ,   __lowerCamelCase							:    List[str]=3072      ,   __lowerCamelCase							:    List[Any]="gelu"      ,   __lowerCamelCase							:    Union[str, Any]=0.1      ,   __lowerCamelCase							:    int=0.1      ,   __lowerCamelCase							:    Tuple=512      ,   __lowerCamelCase							:    str=2      ,   __lowerCamelCase							:    List[str]=0.0_2      ,   __lowerCamelCase							:    List[str]=1E-1_2      ,   __lowerCamelCase							:    str=1      ,   __lowerCamelCase							:    Optional[int]=0      ,   __lowerCamelCase							:    Optional[Any]=2      ,   __lowerCamelCase							:    str="absolute"      ,   __lowerCamelCase							:    List[str]=True      ,   __lowerCamelCase							:    Dict=None      ,   __lowerCamelCase							:    Optional[Any]=False      ,   __lowerCamelCase							:    Optional[Any]=2      ,   __lowerCamelCase							:    Tuple=False      ,   __lowerCamelCase							:    Tuple=True      ,   __lowerCamelCase							:    Union[str, Any]=True      ,   __lowerCamelCase							:    str=("en_XX",)      ,   __lowerCamelCase							:    Union[str, Any]=None      ,   **__lowerCamelCase							:    Optional[int]      ,   ):


             '''simple docstring'''



             super().__init__(pad_token_id=__lowerCamelCase      ,   bos_token_id=__lowerCamelCase      ,   eos_token_id=__lowerCamelCase      ,   **__lowerCamelCase )

             lowerCamelCase__	:       Union[str, Any]					=						vocab_size
             lowerCamelCase__	:       Union[str, Any]					=						hidden_size
             lowerCamelCase__	:       Optional[int]					=						num_hidden_layers
             lowerCamelCase__	:       List[Any]					=						num_attention_heads
             lowerCamelCase__	:       Union[str, Any]					=						hidden_act
             lowerCamelCase__	:       Optional[int]					=						intermediate_size
             lowerCamelCase__	:       Optional[int]					=						hidden_dropout_prob
             lowerCamelCase__	:       List[Any]					=						attention_probs_dropout_prob
             lowerCamelCase__	:       Any					=						max_position_embeddings
             lowerCamelCase__	:       List[Any]					=						type_vocab_size
             lowerCamelCase__	:       int					=						initializer_range
             lowerCamelCase__	:       Tuple					=						layer_norm_eps
             lowerCamelCase__	:       Union[str, Any]					=						position_embedding_type
             lowerCamelCase__	:       str					=						use_cache
             lowerCamelCase__	:       Union[str, Any]					=						classifier_dropout
             lowerCamelCase__	:       Any					=						pre_norm
             lowerCamelCase__	:       Tuple					=						adapter_reduction_factor
             lowerCamelCase__	:       Tuple					=						adapter_layer_norm
             lowerCamelCase__	:       List[Any]					=						adapter_reuse_layer_norm
             lowerCamelCase__	:       Dict					=						ln_before_adapter
             lowerCamelCase__	:       List[Any]					=						list(__lowerCamelCase )
             lowerCamelCase__	:       Optional[Any]					=						default_language







class     _lowercase				(							lowercase__):


       """simple docstring"""




       @property
       def 		lowerCAmelCase  (     self							:    Tuple ):


             '''simple docstring'''



             if self.task == "multiple-choice":
                   lowerCamelCase__	:       Dict					=						{0: "batch", 1: "choice", 2: "sequence"}
             else:
                   lowerCamelCase__	:       List[str]					=						{0: "batch", 1: "sequence"}
             return OrderedDict(
                 [
                     ("input_ids", dynamic_axis),
                     ("attention_mask", dynamic_axis),
                 ] )


