




import logging
import os
from dataclasses import dataclass, field
from typing import Dict, List, Optional

import numpy as np
import torch
from utils_hans import HansDataset, InputFeatures, hans_processors, hans_tasks_num_labels

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import is_main_process


__SCREAMING_SNAKE_CASE			:      Dict      			=logging.getLogger(__name__)






@dataclass
class 	A	:
     """simple docstring"""

     _snake_case:		str   =field(
         metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}						)
     _snake_case:		Optional[str]   =field(
         default=_lowerCAmelCase	,  metadata={"help": "Pretrained config name or path if not the same as model_name"}						)
     _snake_case:		Optional[str]   =field(
         default=_lowerCAmelCase	,  metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}						)
     _snake_case:		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"""

     _snake_case:		str   =field(
         metadata={"help": "The name of the task to train selected in the list: " + ", ".join(hans_processors.keys()						)}						)
     _snake_case:		str   =field(
         metadata={"help": "The input data dir. Should contain the .tsv files (or other data files) for the task."}						)
     _snake_case:		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."
             )
         }	,  )
     _snake_case:		bool   =field(
         default=_lowerCAmelCase	,  metadata={"help": "Overwrite the cached training and evaluation sets"}						)

def 	lowerCAmelCase_	(     lowerCamelCase:				List[InputFeatures]  )    ->	Dict[str, torch.Tensor]:


      '''simple docstring'''




      lowerCamelCase__					     = default_data_collator(lowerCamelCase  )
      lowerCamelCase__					     = batch.pop('pairID'   , lowerCamelCase  )
      return batch

def 	lowerCAmelCase_	(     )    ->	int:


      '''simple docstring'''




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

      # Set seed
      set_seed(training_args.seed  )

      try:
            lowerCamelCase__					     = hans_tasks_num_labels[data_args.task_name]
      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.

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

      # Get datasets
      lowerCamelCase__					     = (
          HansDataset(
              data_dir=data_args.data_dir   , tokenizer=lowerCamelCase   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , )
          if training_args.do_train
          else None
      )
      lowerCamelCase__					     = (
          HansDataset(
              data_dir=data_args.data_dir   , tokenizer=lowerCamelCase   , task=data_args.task_name   , max_seq_length=data_args.max_seq_length   , overwrite_cache=data_args.overwrite_cache   , evaluate=lowerCamelCase   , )
          if training_args.do_eval
          else None
      )

      # Initialize our Trainer
      lowerCamelCase__					     = Trainer(
          model=lowerCamelCase   , args=lowerCamelCase   , train_dataset=lowerCamelCase   , eval_dataset=lowerCamelCase   , data_collator=lowerCamelCase   , )

      # 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
      if training_args.do_eval:
            logger.info('*** Evaluate ***'  )

            lowerCamelCase__					     = trainer.predict(lowerCamelCase  )
            lowerCamelCase__					     = output.predictions
            lowerCamelCase__					     = np.argmax(lowerCamelCase   , axis=1  )

            lowerCamelCase__					     = [ex.pairID for ex in eval_dataset]
            lowerCamelCase__					     = os.path.join(training_args.output_dir   , 'hans_predictions.txt'  )
            lowerCamelCase__					     = eval_dataset.get_labels()
            if trainer.is_world_master():
                  with open(lowerCamelCase   , 'w'  ) as writer:
                        writer.write('pairID,gold_label\n'  )
                        for pid, pred in zip(lowerCamelCase   , lowerCamelCase  ):
                              writer.write('ex' + str(lowerCamelCase  ) + ',' + label_list[int(lowerCamelCase  )] + '\n'  )

            trainer._log(output.metrics  )

def 	lowerCAmelCase_	(     lowerCamelCase:				List[str]  )    ->	Optional[Any]:


      '''simple docstring'''




      main()


if __name__ == "__main__":
      main()





import os
import random
from pathlib import Path
from typing import List

import numpy as np
import torch
from torch.cuda.amp import GradScaler

from .utils import (
    MODEL_NAME,
    OPTIMIZER_NAME,
    RNG_STATE_NAME,
    SCALER_NAME,
    SCHEDULER_NAME,
    get_pretty_name,
    is_tpu_available,
    is_xpu_available,
    save,
)


if is_tpu_available(check_device=False):
      import torch_xla.core.xla_model as xm

from .logging import get_logger
from .state import PartialState


__SCREAMING_SNAKE_CASE			:      Union[str, Any]      			=get_logger(__name__)

def 	lowerCAmelCase_	(     lowerCamelCase:				str   , lowerCamelCase:				List[dict]   , lowerCamelCase:				list   , lowerCamelCase:				list   , lowerCamelCase:				int   , lowerCamelCase:				GradScaler = None   , )    ->	Any:


      '''simple docstring'''




      for i, state in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Model weights saved in {output_model_file}"""  )
      # Optimizer states
      for i, opt in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = opt.state_dict()
            lowerCamelCase__					     = f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Optimizer state saved in {output_optimizer_file}"""  )
      # Scheduler states
      for i, scheduler in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = scheduler.state_dict()
            lowerCamelCase__					     = f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Scheduler state saved in {output_scheduler_file}"""  )
      # GradScaler state
      if scaler is not None:
            lowerCamelCase__					     = scaler.state_dict()
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            torch.save(lowerCamelCase   , lowerCamelCase  )
            logger.info(f"""Gradient scaler state saved in {output_scaler_file}"""  )
      # Random number generator states
      lowerCamelCase__					     = {}
      lowerCamelCase__					     = f"""{RNG_STATE_NAME}_{process_index}.pkl"""
      lowerCamelCase__					     = random.getstate()
      lowerCamelCase__					     = np.random.get_state()
      lowerCamelCase__					     = torch.get_rng_state()
      if is_xpu_available():
            lowerCamelCase__					     = torch.xpu.get_rng_state_all()
      else:
            lowerCamelCase__					     = torch.cuda.get_rng_state_all()
      if is_tpu_available():
            lowerCamelCase__					     = xm.get_rng_state()
      lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
      torch.save(lowerCamelCase   , lowerCamelCase  )
      logger.info(f"""Random states saved in {output_states_file}"""  )
      return output_dir

def 	lowerCAmelCase_	(     lowerCamelCase:				int   , lowerCamelCase:				Dict   , lowerCamelCase:				Union[str, Any]   , lowerCamelCase:				Any   , lowerCamelCase:				Any   , lowerCamelCase:				Any=None   , lowerCamelCase:				Dict=None   , **lowerCamelCase:				Optional[Any]   , )    ->	Any:


      '''simple docstring'''




      if map_location not in [None, "cpu", "on_device"]:
            raise TypeError(
                'Unsupported optimizer map location passed, please choose one of `None`, `\'cpu\'`, or `\'on_device\'`'  )
      if map_location is None:
            lowerCamelCase__					     = 'cpu'
      elif map_location == "on_device":
            lowerCamelCase__					     = PartialState().device
      # Model states
      for i, model in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{MODEL_NAME}.bin""" if i == 0 else f"""{MODEL_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            models[i].load_state_dict(torch.load(lowerCamelCase   , map_location=lowerCamelCase  )   , **lowerCamelCase  )
      logger.info('All model weights loaded successfully'  )

      # Optimizer states
      for i, opt in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{OPTIMIZER_NAME}.bin""" if i == 0 else f"""{OPTIMIZER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            lowerCamelCase__					     = torch.load(lowerCamelCase   , map_location=lowerCamelCase  )
            optimizers[i].load_state_dict(lowerCamelCase  )
      logger.info('All optimizer states loaded successfully'  )

      # Scheduler states
      for i, scheduler in enumerate(lowerCamelCase  ):
            lowerCamelCase__					     = f"""{SCHEDULER_NAME}.bin""" if i == 0 else f"""{SCHEDULER_NAME}_{i}.bin"""
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            scheduler.load_state_dict(torch.load(lowerCamelCase  )  )
      logger.info('All scheduler states loaded successfully'  )

      # GradScaler state
      if scaler is not None:
            lowerCamelCase__					     = os.path.join(lowerCamelCase   , lowerCamelCase  )
            scaler.load_state_dict(torch.load(lowerCamelCase  )  )
            logger.info('GradScaler state loaded successfully'  )

      # Random states
      try:
            lowerCamelCase__					     = torch.load(os.path.join(lowerCamelCase   , f"""{RNG_STATE_NAME}_{process_index}.pkl"""  )  )
            random.setstate(states['random_state']  )
            np.random.set_state(states['numpy_random_seed']  )
            torch.set_rng_state(states['torch_manual_seed']  )
            if is_xpu_available():
                  torch.xpu.set_rng_state_all(states['torch_xpu_manual_seed']  )
            else:
                  torch.cuda.set_rng_state_all(states['torch_cuda_manual_seed']  )
            if is_tpu_available():
                  xm.set_rng_state(states['xm_seed']  )
            logger.info('All random states loaded successfully'  )
      except Exception:
            logger.info('Could not load random states'  )

def 	lowerCAmelCase_	(     lowerCamelCase:				Dict   , lowerCamelCase:				Any   , lowerCamelCase:				int = 0  )    ->	Union[str, Any]:


      '''simple docstring'''




      lowerCamelCase__					     = Path(lowerCamelCase  ) / f"""custom_checkpoint_{index}.pkl"""
      logger.info(f"""Saving the state of {get_pretty_name(lowerCamelCase  )} to {save_location}"""  )
      torch.save(obj.state_dict()   , lowerCamelCase  )


def 	lowerCAmelCase_	(     lowerCamelCase:				int   , lowerCamelCase:				Optional[int]   , lowerCamelCase:				int = 0  )    ->	Any:


      '''simple docstring'''




      lowerCamelCase__					     = f"""{path}/custom_checkpoint_{index}.pkl"""
      logger.info(f"""Loading the state of {get_pretty_name(lowerCamelCase  )} from {load_location}"""  )
      obj.load_state_dict(torch.load(lowerCamelCase   , map_location='cpu'  )  )