

"""simple docstring"""




import json
import os
from typing import List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__UpperCAmelCase	=			logging.get_logger(__name__)

__UpperCAmelCase	=			{
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
}

__UpperCAmelCase	=			{
    'vocab_file': {
        'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/vocab.json',
    },
    'merges_file': {'microsoft/biogpt': 'https://huggingface.co/microsoft/biogpt/resolve/main/merges.txt'},
}

__UpperCAmelCase	=			{
    'microsoft/biogpt': 1024,
}
def 					lowerCAmelCase  (   __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					int   				=   set()
 UpperCAmelCase__   :					int   				=   word[0]
 for char in word[1:]:
  pairs.add((prev_char, char) )
  UpperCAmelCase__   :					Any   				=   char
 return pairs







class        __lowercase     (      __lowerCamelCase   ):
  snake_case_			    =    VOCAB_FILES_NAMES
  snake_case_			    =    PRETRAINED_VOCAB_FILES_MAP
  snake_case_			    =    PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  snake_case_			    =    ["""input_ids""", """attention_mask"""]

  def __init__(					self						:     str   ,A						:     List[str]   ,A						:     Optional[Any]   ,A						:     Tuple="<unk>"   ,A						:     Optional[Any]="<s>"   ,A						:     Optional[int]="</s>"   ,A						:     int="</s>"   ,A						:     str="<pad>"   ,**A						:     str   ,):






   '''simple docstring'''
   super().__init__(
       bos_token=A   ,eos_token=A   ,sep_token=A   ,unk_token=A   ,pad_token=A   ,**A   ,)

   try:
    import sacremoses
   except ImportError:
    raise ImportError(
        """You need to install sacremoses to use BioGptTokenizer. """
        """See https://pypi.org/project/sacremoses/ for installation."""      )

   UpperCAmelCase__   :					List[str]   				=   """en"""
   UpperCAmelCase__   :					Dict   				=   sacremoses
   # cache of sm.MosesTokenizer instance
   UpperCAmelCase__   :					Union[str, Any]   				=   {}
   UpperCAmelCase__   :					Tuple   				=   {}
   with open(A   ,encoding="""utf-8"""      ) as vocab_handle:
    UpperCAmelCase__   :					str   				=   json.load(A      )
   UpperCAmelCase__   :					List[Any]   				=   {v: k for k, v in self.encoder.items()}
   with open(A   ,encoding="""utf-8"""      ) as merges_handle:
    UpperCAmelCase__   :					Any   				=   merges_handle.read().split("""\n"""      )[:-1]
   UpperCAmelCase__   :					Tuple   				=   [tuple(merge.split()[:2]      ) for merge in merges]
   UpperCAmelCase__   :					Union[str, Any]   				=   dict(zip(A   ,range(len(A      )      )      )      )
   UpperCAmelCase__   :					int   				=   {}

  @property
  def 				__lowercase    (					self						:     str      ):






   '''simple docstring'''
   return len(self.encoder      )

  def 				__lowercase    (					self						:     List[Any]      ):






   '''simple docstring'''
   return dict(self.encoder   ,**self.added_tokens_encoder      )

  def 				__lowercase    (					self						:     Optional[int]   ,A						:     List[str]   ,A						:     int      ):






   '''simple docstring'''
   if lang not in self.cache_moses_tokenizer:
    UpperCAmelCase__   :					Union[str, Any]   				=   self.sm.MosesTokenizer(lang=A      )
    UpperCAmelCase__   :					Dict   				=   moses_tokenizer
   return self.cache_moses_tokenizer[lang].tokenize(
       A   ,aggressive_dash_splits=A   ,return_str=A   ,escape=A      )

  def 				__lowercase    (					self						:     List[Any]   ,A						:     Dict   ,A						:     Any      ):






   '''simple docstring'''
   if lang not in self.cache_moses_detokenizer:
    UpperCAmelCase__   :					Union[str, Any]   				=   self.sm.MosesDetokenizer(lang=A      )
    UpperCAmelCase__   :					Dict   				=   moses_detokenizer
   return self.cache_moses_detokenizer[lang].detokenize(A      )

  def 				__lowercase    (					self						:     Optional[int]   ,A						:     Union[str, Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   tuple(token[:-1]      ) + (token[-1] + """</w>""",)
   if token in self.cache:
    return self.cache[token]
   UpperCAmelCase__   :					int   				=   get_pairs(A      )

   if not pairs:
    return token + "</w>"

   while True:
    UpperCAmelCase__   :					List[Any]   				=   min(A   ,key=lambda A      : self.bpe_ranks.get(A   ,float("""inf"""      )      )      )
    if bigram not in self.bpe_ranks:
     break
    UpperCAmelCase__   :					int   				=   bigram
    UpperCAmelCase__   :					str   				=   []
    UpperCAmelCase__   :					Tuple   				=   0
    while i < len(A      ):
     try:
      UpperCAmelCase__   :					int   				=   word.index(A   ,A      )
     except ValueError:
      new_word.extend(word[i:]      )
      break
     else:
      new_word.extend(word[i:j]      )
      UpperCAmelCase__   :					Tuple   				=   j

     if word[i] == first and i < len(A      ) - 1 and word[i + 1] == second:
      new_word.append(first + second      )
      i += 2
     else:
      new_word.append(word[i]      )
      i += 1
    UpperCAmelCase__   :					Optional[int]   				=   tuple(A      )
    UpperCAmelCase__   :					List[str]   				=   new_word
    if len(A      ) == 1:
     break
    else:
     UpperCAmelCase__   :					int   				=   get_pairs(A      )
   UpperCAmelCase__   :					int   				=   """ """.join(A      )
   if word == "\n  </w>":
    UpperCAmelCase__   :					List[str]   				=   """\n</w>"""
   UpperCAmelCase__   :					List[str]   				=   word
   return word

  def 				__lowercase    (					self						:     List[Any]   ,A						:     List[str]   ,A						:     Optional[int]=False      ):






   '''simple docstring'''
   if bypass_tokenizer:
    UpperCAmelCase__   :					List[str]   				=   text.split()
   else:
    UpperCAmelCase__   :					List[Any]   				=   self.moses_tokenize(A   ,self.lang      )

   UpperCAmelCase__   :					List[str]   				=   []
   for token in text:
    if token:
     split_tokens.extend(list(self.bpe(A      ).split(""" """      )      )      )

   return split_tokens

  def 				__lowercase    (					self						:     List[Any]   ,A						:     Tuple      ):






   '''simple docstring'''
   return self.encoder.get(A   ,self.encoder.get(self.unk_token      )      )

  def 				__lowercase    (					self						:     List[str]   ,A						:     str      ):






   '''simple docstring'''
   return self.decoder.get(A   ,self.unk_token      )

  def 				__lowercase    (					self						:     int   ,A						:     Tuple      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   [t.replace(""" """   ,""""""      ).replace("""</w>"""   ,""" """      ) for t in tokens]
   UpperCAmelCase__   :					List[Any]   				=   """""".join(A      ).split()
   # detokenize
   UpperCAmelCase__   :					int   				=   self.moses_detokenize(A   ,self.lang      )
   return text

  def 				__lowercase    (					self						:     Optional[int]   ,A						:     List[int]   ,A						:     Optional[List[int]] = None      ):






   '''simple docstring'''
   if token_ids_a is None:
    return [self.sep_token_id] + token_ids_a
   UpperCAmelCase__   :					int   				=   [self.sep_token_id]
   return sep + token_ids_a + sep + token_ids_a

  def 				__lowercase    (					self						:     Dict   ,A						:     List[int]   ,A						:     Optional[List[int]] = None   ,A						:     bool = False      ):






   '''simple docstring'''
   if already_has_special_tokens:
    return super().get_special_tokens_mask(
        token_ids_a=A   ,token_ids_a=A   ,already_has_special_tokens=A      )
   # no bos used in fairseq
   if token_ids_a is not None:
    return [1] + ([0] * len(A      )) + [1] + ([0] * len(A      ))
   return [1] + ([0] * len(A      ))

  def 				__lowercase    (					self						:     Dict   ,A						:     List[int]   ,A						:     Optional[List[int]] = None      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   [self.sep_token_id]

   # no bos used in fairseq
   if token_ids_a is None:
    return len(token_ids_a + sep      ) * [0]
   return len(token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]

  def 				__lowercase    (					self						:     Optional[int]   ,A						:     str   ,A						:     Optional[str] = None      ):






   '''simple docstring'''
   if not os.path.isdir(A      ):
    logger.error(f"Vocabulary path ({save_directory}) should be a directory"      )
    return
   UpperCAmelCase__   :					List[Any]   				=   os.path.join(
       A   ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]      )
   UpperCAmelCase__   :					Union[str, Any]   				=   os.path.join(
       A   ,(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]      )

   with open(A   ,"""w"""   ,encoding="""utf-8"""      ) as f:
    f.write(json.dumps(self.encoder   ,indent=2   ,sort_keys=A   ,ensure_ascii=A      ) + """\n"""      )

   UpperCAmelCase__   :					int   				=   0
   with open(A   ,"""w"""   ,encoding="""utf-8"""      ) as writer:
    for bpe_tokens, token_index in sorted(self.bpe_ranks.items()   ,key=lambda A      : kv[1]      ):
     if index != token_index:
      logger.warning(
          f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
          """ Please check that the tokenizer is not corrupted!"""      )
      UpperCAmelCase__   :					Optional[int]   				=   token_index
     writer.write(""" """.join(A      ) + """\n"""      )
     index += 1

   return vocab_file, merge_file

  def __getstate__(					self						:     Union[str, Any]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					int   				=   self.__dict__.copy()
   UpperCAmelCase__   :					str   				=   None
   return state




  def __setstate__(					self						:     Optional[int]   ,A						:     Tuple      ):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   d

   try:
    import sacremoses
   except ImportError:
    raise ImportError(
        """You need to install sacremoses to use XLMTokenizer. """
        """See https://pypi.org/project/sacremoses/ for installation."""      )

   UpperCAmelCase__   :					int   				=   sacremoses








"""simple docstring"""




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


__UpperCAmelCase	=			logging.getLogger(__name__)







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







@dataclass
class        __lowercase     :
  snake_case_			    =    field(
      metadata={"""help""": """The name of the task to train selected in the list: """ + """, """.join(hans_processors.keys()   )}   )
  snake_case_			    =    field(
      metadata={"""help""": """The input data dir. Should contain the .tsv files (or other data files) for the task."""}   )
  snake_case_			    =    field(
      default=1_2_8		,     metadata={
          """help""": (
              """The maximum total input sequence length after tokenization. Sequences longer """
              """than this will be truncated, sequences shorter will be padded."""
          )
      }		,     )
  snake_case_			    =    field(
      default=__lowerCamelCase		,     metadata={"""help""": """Overwrite the cached training and evaluation sets"""}   )







def 					lowerCAmelCase  (   __UpperCamelCase ):
 '''simple docstring'''





 UpperCAmelCase__   :					Optional[Any]   				=   default_data_collator(__UpperCamelCase )
 UpperCAmelCase__   :					List[str]   				=   batch.pop("""pairID"""							,      __UpperCamelCase )
 return batch
def 					lowerCAmelCase  (   ):
 '''simple docstring'''





 UpperCAmelCase__   :					Dict   				=   HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
 UpperCAmelCase__				, UpperCAmelCase__				, UpperCAmelCase__   :					Union[str, Any]   				=   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"""							,      __UpperCamelCase )

 # Set seed
 set_seed(training_args.seed )

 try:
  UpperCAmelCase__   :					Optional[int]   				=   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.

 UpperCAmelCase__   :					Tuple   				=   AutoConfig.from_pretrained(
     model_args.config_name if model_args.config_name else model_args.model_name_or_path							,      num_labels=__UpperCamelCase							,      finetuning_task=data_args.task_name							,      cache_dir=model_args.cache_dir							,      )
 UpperCAmelCase__   :					int   				=   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							,      )
 UpperCAmelCase__   :					List[Any]   				=   AutoModelForSequenceClassification.from_pretrained(
     model_args.model_name_or_path							,      from_tf=bool(""".ckpt""" in model_args.model_name_or_path )							,      config=__UpperCamelCase							,      cache_dir=model_args.cache_dir							,      )

 # Get datasets
 UpperCAmelCase__   :					Optional[int]   				=   (
     HansDataset(
         data_dir=data_args.data_dir							,      tokenizer=__UpperCamelCase							,      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
 )
 UpperCAmelCase__   :					str   				=   (
     HansDataset(
         data_dir=data_args.data_dir							,      tokenizer=__UpperCamelCase							,      task=data_args.task_name							,      max_seq_length=data_args.max_seq_length							,      overwrite_cache=data_args.overwrite_cache							,      evaluate=__UpperCamelCase							,      )
     if training_args.do_eval
     else None
 )

 # Initialize our Trainer
 UpperCAmelCase__   :					List[Any]   				=   Trainer(
     model=__UpperCamelCase							,      args=__UpperCamelCase							,      train_dataset=__UpperCamelCase							,      eval_dataset=__UpperCamelCase							,      data_collator=__UpperCamelCase							,      )

 # 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 ***""" )

  UpperCAmelCase__   :					Optional[Any]   				=   trainer.predict(__UpperCamelCase )
  UpperCAmelCase__   :					List[str]   				=   output.predictions
  UpperCAmelCase__   :					Dict   				=   np.argmax(__UpperCamelCase							,      axis=1 )

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

  trainer._log(output.metrics )
def 					lowerCAmelCase  (   __UpperCamelCase ):
 '''simple docstring'''





 main()


if __name__ == "__main__":
      main()





