

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





@dataclass
class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




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





@dataclass
class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




   lowerCamelCase__				=      field(default=__snake_case					,       metadata={"help": "The input training data file (a text file)."}		)
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={"help": "An optional input evaluation data file to evaluate the perplexity on (a text file)."}					,       )
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={"help": "Overwrite the cached training and evaluation sets"}		)
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={"help": "The number of processes to use for the preprocessing."}					,       )
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={
           "help": (
               "The maximum total input sequence length after tokenization. If passed, sequences longer "
               "than this will be truncated, sequences shorter will be padded."
           )
       }					,       )
   lowerCamelCase__				=      field(
       default=__snake_case					,       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."
           )
       }					,       )
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of training examples to this "
               "value if set."
           )
       }					,       )
   lowerCamelCase__				=      field(
       default=__snake_case					,       metadata={
           "help": (
               "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
               "value if set."
           )
       }					,       )





   def      _snake_case		(       self					:			Optional[int]			):
       if self.train_file is not None:
           SCREAMING_SNAKE_CASE										=   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:
           SCREAMING_SNAKE_CASE										=   self.validation_file.split("."			)[-1]
           assert extension in ["csv", "json"], "`validation_file` should be a csv or a json file."





@dataclass
class 			_SCREAMING_SNAKE_CASE :







   '''simple docstring'''




   lowerCamelCase__				=      42
   lowerCamelCase__				=      True
   lowerCamelCase__				=      None
   lowerCamelCase__				=      None





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

       SCREAMING_SNAKE_CASE										=   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
       SCREAMING_SNAKE_CASE										=   {k: v.view(__lowerCamelCase     , __lowerCamelCase     , -1			) for k, v in batch.items()}
       # Add back labels
       SCREAMING_SNAKE_CASE										=   torch.tensor(__lowerCamelCase     , dtype=torch.intaa			)
       return batch





def 	__a     (      ):
    # 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										=   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.
        SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]       )       )
    else:
        SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   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()

    SCREAMING_SNAKE_CASE										=   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.
    SCREAMING_SNAKE_CASE										=   None
    if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
        SCREAMING_SNAKE_CASE										=   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:
        SCREAMING_SNAKE_CASE										=   {}
        if data_args.train_file is not None:
            SCREAMING_SNAKE_CASE										=   data_args.train_file
        if data_args.validation_file is not None:
            SCREAMING_SNAKE_CASE										=   data_args.validation_file
        SCREAMING_SNAKE_CASE										=   data_args.train_file.split("."       )[-1]
        SCREAMING_SNAKE_CASE										=   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.
        SCREAMING_SNAKE_CASE										=   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.
    SCREAMING_SNAKE_CASE										=   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			,  )
    SCREAMING_SNAKE_CASE										=   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			,  )
    SCREAMING_SNAKE_CASE										=   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.
    SCREAMING_SNAKE_CASE										=   [F"ending{i}" for i in range(4       )]
    SCREAMING_SNAKE_CASE										=   "sent1"
    SCREAMING_SNAKE_CASE										=   "sent2"

    if data_args.max_seq_length is None:
        SCREAMING_SNAKE_CASE										=   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`."       )
            SCREAMING_SNAKE_CASE										=   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}."       )
        SCREAMING_SNAKE_CASE										=   min(data_args.max_seq_length			,  tokenizer.model_max_length       )

    # Preprocessing the datasets.
    def preprocess_function(A__			:  Optional[Any]       ):
        SCREAMING_SNAKE_CASE										=   [[context] * 4 for context in examples[context_name]]
        SCREAMING_SNAKE_CASE										=   examples[question_header_name]
        SCREAMING_SNAKE_CASE										=   [
            [F"{header} {examples[end][i]}" for end in ending_names] for i, header in enumerate(A__       )
        ]

        # Flatten out
        SCREAMING_SNAKE_CASE										=   list(chain(*A__       )       )
        SCREAMING_SNAKE_CASE										=   list(chain(*A__       )       )

        # Tokenize
        SCREAMING_SNAKE_CASE										=   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"       )
        SCREAMING_SNAKE_CASE										=   raw_datasets["train"]
        if data_args.max_train_samples is not None:
            SCREAMING_SNAKE_CASE										=   min(len(A__       )			,  data_args.max_train_samples       )
            SCREAMING_SNAKE_CASE										=   train_dataset.select(range(A__       )       )
        with training_args.main_process_first(desc="train dataset map pre-processing"       ):
            SCREAMING_SNAKE_CASE										=   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"       )
        SCREAMING_SNAKE_CASE										=   raw_datasets["validation"]
        if data_args.max_eval_samples is not None:
            SCREAMING_SNAKE_CASE										=   min(len(A__       )			,  data_args.max_eval_samples       )
            SCREAMING_SNAKE_CASE										=   eval_dataset.select(range(A__       )       )
        with training_args.main_process_first(desc="validation dataset map pre-processing"       ):
            SCREAMING_SNAKE_CASE										=   eval_dataset.map(
                A__			,  batched=A__			,  num_proc=data_args.preprocessing_num_workers			,  load_from_cache_file=not data_args.overwrite_cache			,  )

    # Data collator
    SCREAMING_SNAKE_CASE										=   (
        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__			:  Optional[int]       ):
        SCREAMING_SNAKE_CASE							,	SCREAMING_SNAKE_CASE										=   eval_predictions
        SCREAMING_SNAKE_CASE										=   np.argmax(A__			,  axis=1       )
        return {"accuracy": (preds == label_ids).astype(np.floataa       ).mean().item()}

    # Initialize our Trainer
    SCREAMING_SNAKE_CASE										=   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:
        SCREAMING_SNAKE_CASE										=   None
        if training_args.resume_from_checkpoint is not None:
            SCREAMING_SNAKE_CASE										=   training_args.resume_from_checkpoint
        elif last_checkpoint is not None:
            SCREAMING_SNAKE_CASE										=   last_checkpoint
        SCREAMING_SNAKE_CASE										=   trainer.train(resume_from_checkpoint=A__       )
        trainer.save_model()  # Saves the tokenizer too for easy upload
        SCREAMING_SNAKE_CASE										=   train_result.metrics

        SCREAMING_SNAKE_CASE										=   (
            data_args.max_train_samples if data_args.max_train_samples is not None else len(A__       )
        )
        SCREAMING_SNAKE_CASE										=   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 ***"       )

        SCREAMING_SNAKE_CASE										=   trainer.evaluate()
        SCREAMING_SNAKE_CASE										=   data_args.max_eval_samples if data_args.max_eval_samples is not None else len(A__       )
        SCREAMING_SNAKE_CASE										=   min(A__			,  len(A__       )       )

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

    SCREAMING_SNAKE_CASE										=   {
        "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 	__a     (      A__			:  Any       ):
    # For xla_spawn (TPUs)
    main()


if __name__ == "__main__":
    main()

"""simple docstring"""






# This code is adapted from OpenAI's release
# https://github.com/openai/human-eval/blob/master/human_eval/execution.py

import contextlib
import faulthandler
import io
import multiprocessing
import os
import platform
import signal
import tempfile




def       A_  (				__lowercase						,	__lowercase						,	__lowercase						,	__lowercase	):
 UpperCamelCase_     :					Tuple   	=multiprocessing.Manager()
 UpperCamelCase_     :					Dict   	=manager.list()

 UpperCamelCase_     :					Union[str, Any]   	=multiprocessing.Process(target=__lowercase						,	args=(check_program, result, timeout)	)
 p.start()
 p.join(timeout=timeout + 1	)
 if p.is_alive():
  p.kill()

 if not result:
  result.append('timed out'	)

 return {
     "task_id": task_id,
     "passed": result[0] == "passed",
     "result": result[0],
     "completion_id": completion_id,
 }




def       A_  (				__lowercase						,	__lowercase						,	__lowercase	):
 with create_tempdir():
  # These system calls are needed when cleaning up tempdir.
  import os
  import shutil

  UpperCamelCase_     :					Tuple   	=shutil.rmtree
  UpperCamelCase_     :					List[str]   	=os.rmdir
  UpperCamelCase_     :					Any   	=os.chdir

  # Disable functionalities that can make destructive changes to the test.
  reliability_guard()

  # Run program.
  try:
   UpperCamelCase_     :					List[str]   	={}
   with swallow_io():
    with time_limit(__lowercase	):
     exec(__lowercase						,	__lowercase	)
   result.append('passed'	)
  except TimeoutException:
   result.append('timed out'	)
  except BaseException as e:
   result.append(F'''failed: {e}'''	)

  # Needed for cleaning up.
  UpperCamelCase_     :					Optional[Any]   	=rmtree
  UpperCamelCase_     :					str   	=rmdir
  UpperCamelCase_     :					Dict   	=chdir




@contextlib.contextmanager
def       A_  (				__lowercase	):
 def signal_handler(__lowercase						,	__lowercase	):
  raise TimeoutException('Timed out!'	)

 signal.setitimer(signal.ITIMER_REAL						,	__lowercase	)
 signal.signal(signal.SIGALRM						,	__lowercase	)
 try:
  yield
 finally:
  signal.setitimer(signal.ITIMER_REAL						,	0	)




@contextlib.contextmanager
def       A_  (				):
 UpperCamelCase_     :					str   	=WriteOnlyStringIO()
 with contextlib.redirect_stdout(__lowercase	):
  with contextlib.redirect_stderr(__lowercase	):
   with redirect_stdin(__lowercase	):
    yield




@contextlib.contextmanager
def       A_  (				):
 with tempfile.TemporaryDirectory() as dirname:
  with chdir(__lowercase	):
   yield dirname





class 				a__					(						A__       ):
     pass





class 				a__					(						io.StringIO       ):



     def  lowerCamelCase_						(							self :Any      ,  *_lowerCamelCase :Any      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      raise OSError



     def  lowerCamelCase_						(							self :Union[str, Any]      ,  *_lowerCamelCase :Any      ,  **_lowerCamelCase :Tuple   ):







      '''simple docstring'''



      raise OSError



     def  lowerCamelCase_						(							self :Tuple      ,  *_lowerCamelCase :str      ,  **_lowerCamelCase :List[str]   ):







      '''simple docstring'''



      raise OSError




     def  lowerCamelCase_						(							self :List[str]      ,  *_lowerCamelCase :Optional[int]      ,  **_lowerCamelCase :str   ):







      '''simple docstring'''



      return False





class 				a__					(						contextlib._RedirectStream       ):  # type: ignore
     UpperCAmelCase__         =      '''stdin'''




@contextlib.contextmanager
def       A_  (				__lowercase	):
 if root == ".":
  yield
  return
 UpperCamelCase_     :					List[str]   	=os.getcwd()
 os.chdir(__lowercase	)
 try:
  yield
 except BaseException as exc:
  raise exc
 finally:
  os.chdir(__lowercase	)





def       A_  (				__lowercase=None	):

 if maximum_memory_bytes is not None:
  import resource

  resource.setrlimit(resource.RLIMIT_AS						,	(maximum_memory_bytes, maximum_memory_bytes)	)
  resource.setrlimit(resource.RLIMIT_DATA						,	(maximum_memory_bytes, maximum_memory_bytes)	)
  if not platform.uname().system == "Darwin":
   resource.setrlimit(resource.RLIMIT_STACK						,	(maximum_memory_bytes, maximum_memory_bytes)	)

 faulthandler.disable()

 import builtins

 UpperCamelCase_     :					Any   	=None
 UpperCamelCase_     :					Any   	=None

 import os

 UpperCamelCase_     :					Union[str, Any]   	='1'

 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Any   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					Optional[int]   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					List[str]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					int   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					List[Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					Optional[int]   	=None
 UpperCamelCase_     :					str   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					int   	=None

 import shutil

 UpperCamelCase_     :					List[str]   	=None
 UpperCamelCase_     :					Optional[Any]   	=None
 UpperCamelCase_     :					Dict   	=None

 import subprocess

 UpperCamelCase_     :					Optional[int]   	=None  # type: ignore

 UpperCamelCase_     :					Union[str, Any]   	=None

 import sys

 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Tuple   	=None
 UpperCamelCase_     :					Union[str, Any]   	=None
 UpperCamelCase_     :					Dict   	=None
 UpperCamelCase_     :					Any   	=None
