'''simple docstring'''

import argparse
import collections
import json
import os
import re
import string
import sys

import numpy as np


__a:					str			  =  re.compile(R"""\b(a|an|the)\b""", re.UNICODE)

__a:					Optional[int]			  =  None
def      __UpperCamelCase			(  ):
 lowercase__							:       Dict										=   argparse.ArgumentParser('''Official evaluation script for SQuAD version 2.0.'''	)
 parser.add_argument('''data_file'''						,	metavar='''data.json'''						,	help='''Input data JSON file.'''	)
 parser.add_argument('''pred_file'''						,	metavar='''pred.json'''						,	help='''Model predictions.'''	)
 parser.add_argument(
     '''--out-file'''						,	'''-o'''						,	metavar='''eval.json'''						,	help='''Write accuracy metrics to file (default is stdout).'''	)
 parser.add_argument(
     '''--na-prob-file'''						,	'''-n'''						,	metavar='''na_prob.json'''						,	help='''Model estimates of probability of no answer.'''	)
 parser.add_argument(
     '''--na-prob-thresh'''						,	'''-t'''						,	type=UpperCamelCase__						,	default=1.0						,	help='''Predict "" if no-answer probability exceeds this (default = 1.0).'''						,	)
 parser.add_argument(
     '''--out-image-dir'''						,	'''-p'''						,	metavar='''out_images'''						,	default=UpperCamelCase__						,	help='''Save precision-recall curves to directory.'''	)
 parser.add_argument('''--verbose'''						,	'''-v'''						,	action='''store_true'''	)
 if len(sys.argv	) == 1:
  parser.print_help()
  sys.exit(1	)
 return parser.parse_args()
def      __UpperCamelCase			(  UpperCAmelCase	):
 lowercase__							:       Tuple										=   {}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    lowercase__							:       Any										=   bool(qa['''answers''']['''text''']	)
 return qid_to_has_ans
def      __UpperCamelCase			(  UpperCAmelCase	):

 def remove_articles(UpperCAmelCase	):
  return ARTICLES_REGEX.sub(''' '''						,	UpperCamelCase__	)

 def white_space_fix(UpperCAmelCase	):
  return " ".join(text.split()	)

 def remove_punc(UpperCAmelCase	):
  lowercase__							:       Dict										=   set(string.punctuation	)
  return "".join(ch for ch in text if ch not in exclude	)

 def lower(UpperCAmelCase	):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(UpperCamelCase__	)	)	)	)
def      __UpperCamelCase			(  UpperCAmelCase	):
 if not s:
  return []
 return normalize_answer(UpperCamelCase__	).split()
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase	):
 return int(normalize_answer(UpperCamelCase__	) == normalize_answer(UpperCamelCase__	)	)
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase	):
 lowercase__							:       Tuple										=   get_tokens(UpperCamelCase__	)
 lowercase__							:       str										=   get_tokens(UpperCamelCase__	)
 lowercase__							:       int										=   collections.Counter(UpperCamelCase__	) & collections.Counter(UpperCamelCase__	)
 lowercase__							:       Tuple										=   sum(common.values()	)
 if len(UpperCamelCase__	) == 0 or len(UpperCamelCase__	) == 0:
  # If either is no-answer, then F1 is 1 if they agree, 0 otherwise
  return int(gold_toks == pred_toks	)
 if num_same == 0:
  return 0
 lowercase__							:       Union[str, Any]										=   1.0 * num_same / len(UpperCamelCase__	)
 lowercase__							:       Optional[Any]										=   1.0 * num_same / len(UpperCamelCase__	)
 lowercase__							:       Optional[int]										=   (2 * precision * recall) / (precision + recall)
 return fa
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase	):
 lowercase__							:       Union[str, Any]										=   {}
 lowercase__							:       Any										=   {}
 for article in dataset:
  for p in article["paragraphs"]:
   for qa in p["qas"]:
    lowercase__							:       Tuple										=   qa['''id''']
    lowercase__							:       int										=   [t for t in qa['''answers''']['''text'''] if normalize_answer(UpperCamelCase__	)]
    if not gold_answers:
     # For unanswerable questions, only correct answer is empty string
     lowercase__							:       str										=   ['''''']
    if qid not in preds:
     print(F"""Missing prediction for {qid}"""	)
     continue
    lowercase__							:       Optional[int]										=   preds[qid]
    # Take max over all gold answers
    lowercase__							:       Tuple										=   max(compute_exact(UpperCamelCase__						,	UpperCamelCase__	) for a in gold_answers	)
    lowercase__							:       Dict										=   max(compute_fa(UpperCamelCase__						,	UpperCamelCase__	) for a in gold_answers	)
 return exact_scores, fa_scores
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 lowercase__							:       Tuple										=   {}
 for qid, s in scores.items():
  lowercase__							:       List[str]										=   na_probs[qid] > na_prob_thresh
  if pred_na:
   lowercase__							:       Optional[Any]										=   float(not qid_to_has_ans[qid]	)
  else:
   lowercase__							:       int										=   s
 return new_scores
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase=None	):
 if not qid_list:
  lowercase__							:       List[str]										=   len(UpperCamelCase__	)
  return collections.OrderedDict(
      [
          ('''exact''', 1_0_0.0 * sum(exact_scores.values()	) / total),
          ('''f1''', 1_0_0.0 * sum(fa_scores.values()	) / total),
          ('''total''', total),
      ]	)
 else:
  lowercase__							:       int										=   len(UpperCamelCase__	)
  return collections.OrderedDict(
      [
          ('''exact''', 1_0_0.0 * sum(exact_scores[k] for k in qid_list	) / total),
          ('''f1''', 1_0_0.0 * sum(fa_scores[k] for k in qid_list	) / total),
          ('''total''', total),
      ]	)
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 for k in new_eval:
  lowercase__							:       Optional[Any]										=   new_eval[k]
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 plt.step(UpperCamelCase__						,	UpperCamelCase__						,	color='''b'''						,	alpha=0.2						,	where='''post'''	)
 plt.fill_between(UpperCamelCase__						,	UpperCamelCase__						,	step='''post'''						,	alpha=0.2						,	color='''b'''	)
 plt.xlabel('''Recall'''	)
 plt.ylabel('''Precision'''	)
 plt.xlim([0.0, 1.0_5]	)
 plt.ylim([0.0, 1.0_5]	)
 plt.title(UpperCamelCase__	)
 plt.savefig(UpperCamelCase__	)
 plt.clf()
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase=None						,	UpperCAmelCase=None	):
 lowercase__							:       List[Any]										=   sorted(UpperCamelCase__						,	key=lambda UpperCAmelCase	: na_probs[k]	)
 lowercase__							:       Tuple										=   0.0
 lowercase__							:       int										=   1.0
 lowercase__							:       int										=   0.0
 lowercase__							:       List[str]										=   [1.0]
 lowercase__							:       str										=   [0.0]
 lowercase__							:       Tuple										=   0.0
 for i, qid in enumerate(UpperCamelCase__	):
  if qid_to_has_ans[qid]:
   true_pos += scores[qid]
  lowercase__							:       Dict										=   true_pos / float(i + 1	)
  lowercase__							:       Tuple										=   true_pos / float(UpperCamelCase__	)
  if i == len(UpperCamelCase__	) - 1 or na_probs[qid] != na_probs[qid_list[i + 1]]:
   # i.e., if we can put a threshold after this point
   avg_prec += cur_p * (cur_r - recalls[-1])
   precisions.append(UpperCamelCase__	)
   recalls.append(UpperCamelCase__	)
 if out_image:
  plot_pr_curve(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__	)
 return {"ap": 1_0_0.0 * avg_prec}
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 if out_image_dir and not os.path.exists(UpperCamelCase__	):
  os.makedirs(UpperCamelCase__	)
 lowercase__							:       Optional[int]										=   sum(1 for v in qid_to_has_ans.values() if v	)
 if num_true_pos == 0:
  return
 lowercase__							:       Any										=   make_precision_recall_eval(
     UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	out_image=os.path.join(UpperCamelCase__						,	'''pr_exact.png'''	)						,	title='''Precision-Recall curve for Exact Match score'''						,	)
 lowercase__							:       Any										=   make_precision_recall_eval(
     UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	out_image=os.path.join(UpperCamelCase__						,	'''pr_f1.png'''	)						,	title='''Precision-Recall curve for F1 score'''						,	)
 lowercase__							:       str										=   {k: float(UpperCamelCase__	) for k, v in qid_to_has_ans.items()}
 lowercase__							:       List[str]										=   make_precision_recall_eval(
     UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	out_image=os.path.join(UpperCamelCase__						,	'''pr_oracle.png'''	)						,	title='''Oracle Precision-Recall curve (binary task of HasAns vs. NoAns)'''						,	)
 merge_eval(UpperCamelCase__						,	UpperCamelCase__						,	'''pr_exact'''	)
 merge_eval(UpperCamelCase__						,	UpperCamelCase__						,	'''pr_f1'''	)
 merge_eval(UpperCamelCase__						,	UpperCamelCase__						,	'''pr_oracle'''	)
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 if not qid_list:
  return
 lowercase__							:       Any										=   [na_probs[k] for k in qid_list]
 lowercase__							:       str										=   np.ones_like(UpperCamelCase__	) / float(len(UpperCamelCase__	)	)
 plt.hist(UpperCamelCase__						,	weights=UpperCamelCase__						,	bins=20						,	range=(0.0, 1.0)	)
 plt.xlabel('''Model probability of no-answer'''	)
 plt.ylabel('''Proportion of dataset'''	)
 plt.title(F"""Histogram of no-answer probability: {name}"""	)
 plt.savefig(os.path.join(UpperCamelCase__						,	F"""na_prob_hist_{name}.png"""	)	)
 plt.clf()
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 lowercase__							:       str										=   sum(1 for k in qid_to_has_ans if not qid_to_has_ans[k]	)
 lowercase__							:       List[str]										=   num_no_ans
 lowercase__							:       Union[str, Any]										=   cur_score
 lowercase__							:       List[Any]										=   0.0
 lowercase__							:       Any										=   sorted(UpperCamelCase__						,	key=lambda UpperCAmelCase	: na_probs[k]	)
 for i, qid in enumerate(UpperCamelCase__	):
  if qid not in scores:
   continue
  if qid_to_has_ans[qid]:
   lowercase__							:       Optional[int]										=   scores[qid]
  else:
   if preds[qid]:
    lowercase__							:       List[Any]										=   -1
   else:
    lowercase__							:       Union[str, Any]										=   0
  cur_score += diff
  if cur_score > best_score:
   lowercase__							:       Tuple										=   cur_score
   lowercase__							:       Any										=   na_probs[qid]
 return 1_0_0.0 * best_score / len(UpperCamelCase__	), best_thresh
def      __UpperCamelCase			(  UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase						,	UpperCAmelCase	):
 lowercase__					,				lowercase__							:       Dict										=   find_best_thresh(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__	)
 lowercase__					,				lowercase__							:       Optional[Any]										=   find_best_thresh(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__	)
 lowercase__							:       Any										=   best_exact
 lowercase__							:       Any										=   exact_thresh
 lowercase__							:       Union[str, Any]										=   best_fa
 lowercase__							:       Union[str, Any]										=   fa_thresh
def      __UpperCamelCase			(  ):
 with open(OPTS.data_file	) as f:
  lowercase__							:       Union[str, Any]										=   json.load(UpperCamelCase__	)
  lowercase__							:       Dict										=   dataset_json['''data''']
 with open(OPTS.pred_file	) as f:
  lowercase__							:       int										=   json.load(UpperCamelCase__	)
 if OPTS.na_prob_file:
  with open(OPTS.na_prob_file	) as f:
   lowercase__							:       List[Any]										=   json.load(UpperCamelCase__	)
 else:
  lowercase__							:       Dict										=   {k: 0.0 for k in preds}
 lowercase__							:       Optional[int]										=   make_qid_to_has_ans(UpperCamelCase__	)  # maps qid to True/False
 lowercase__							:       Dict										=   [k for k, v in qid_to_has_ans.items() if v]
 lowercase__							:       int										=   [k for k, v in qid_to_has_ans.items() if not v]
 lowercase__					,				lowercase__							:       Dict										=   get_raw_scores(UpperCamelCase__						,	UpperCamelCase__	)
 lowercase__							:       Optional[int]										=   apply_no_ans_threshold(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	OPTS.na_prob_thresh	)
 lowercase__							:       Tuple										=   apply_no_ans_threshold(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	OPTS.na_prob_thresh	)
 lowercase__							:       Dict										=   make_eval_dict(UpperCamelCase__						,	UpperCamelCase__	)
 if has_ans_qids:
  lowercase__							:       Any										=   make_eval_dict(UpperCamelCase__						,	UpperCamelCase__						,	qid_list=UpperCamelCase__	)
  merge_eval(UpperCamelCase__						,	UpperCamelCase__						,	'''HasAns'''	)
 if no_ans_qids:
  lowercase__							:       Union[str, Any]										=   make_eval_dict(UpperCamelCase__						,	UpperCamelCase__						,	qid_list=UpperCamelCase__	)
  merge_eval(UpperCamelCase__						,	UpperCamelCase__						,	'''NoAns'''	)
 if OPTS.na_prob_file:
  find_all_best_thresh(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__	)
 if OPTS.na_prob_file and OPTS.out_image_dir:
  run_precision_recall_analysis(UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	UpperCamelCase__						,	OPTS.out_image_dir	)
  histogram_na_prob(UpperCamelCase__						,	UpperCamelCase__						,	OPTS.out_image_dir						,	'''hasAns'''	)
  histogram_na_prob(UpperCamelCase__						,	UpperCamelCase__						,	OPTS.out_image_dir						,	'''noAns'''	)
 if OPTS.out_file:
  with open(OPTS.out_file						,	'''w'''	) as f:
   json.dump(UpperCamelCase__						,	UpperCamelCase__	)
 else:
  print(json.dumps(UpperCamelCase__						,	indent=2	)	)


if __name__ == "__main__":
  __a:					Dict			  =  parse_args()
  if OPTS.out_image_dir:
    import matplotlib

    matplotlib.use("""Agg""")
    import matplotlib.pyplot as plt
  main()








import logging
import math
import os
from dataclasses import dataclass, field
from glob import glob
from typing import Optional

from torch.utils.data import ConcatDataset

import transformers
from transformers import (
    CONFIG_MAPPING,
    MODEL_WITH_LM_HEAD_MAPPING,
    AutoConfig,
    AutoModelWithLMHead,
    AutoTokenizer,
    DataCollatorForLanguageModeling,
    DataCollatorForPermutationLanguageModeling,
    DataCollatorForWholeWordMask,
    HfArgumentParser,
    LineByLineTextDataset,
    LineByLineWithRefDataset,
    PreTrainedTokenizer,
    TextDataset,
    Trainer,
    TrainingArguments,
    set_seed,
)
from transformers.trainer_utils import is_main_process


a__: List[Any]							   =						logging.getLogger(__name__)


a__: str							   =						list(MODEL_WITH_LM_HEAD_MAPPING.keys())
a__: Tuple							   =						tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)




@dataclass
class        SCREAMING_SNAKE_CASE__					:
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={
         '''help''': (
             '''The model checkpoint for weights initialization. Leave None if you want to train a model from'''
             ''' scratch.'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(UpperCamelCase__ )}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Pretrained tokenizer name or path if not the same as model_name'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Where do you want to store the pretrained models downloaded from huggingface.co'''}							,   )




@dataclass
class        SCREAMING_SNAKE_CASE__					:
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''The input training data file (a text file).'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={
         '''help''': (
             '''The input training data files (multiple files in glob format). '''
             '''Very often splitting large files to smaller files can prevent tokenizer going out of memory'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input evaluation data file to evaluate the perplexity on (a text file).'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input train ref data file for whole word mask in Chinese.'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''An optional input eval ref data file for whole word mask in Chinese.'''}							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Whether distinct lines of text in the dataset are to be handled as distinct sequences.'''}							,   )

 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Train with masked-language modeling loss instead of language modeling.'''} )
 __SCREAMING_SNAKE_CASE							=      field(default=UpperCamelCase__							,   metadata={'''help''': '''Whether ot not to use whole word mask.'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=0.1_5							,   metadata={'''help''': '''Ratio of tokens to mask for masked language modeling loss'''} )
 __SCREAMING_SNAKE_CASE							=      field(
     default=1 / 6							,   metadata={
         '''help''': (
             '''Ratio of length of a span of masked tokens to surrounding context length for permutation language'''
             ''' modeling.'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=5							,   metadata={'''help''': '''Maximum length of a span of masked tokens for permutation language modeling.'''} )

 __SCREAMING_SNAKE_CASE							=      field(
     default=-1							,   metadata={
         '''help''': (
             '''Optional input sequence length after tokenization.'''
             '''The training dataset will be truncated in block of this size for training.'''
             '''Default to the model max input length for single sentence inputs (take into account special tokens).'''
         )
     }							,   )
 __SCREAMING_SNAKE_CASE							=      field(
     default=UpperCamelCase__							,   metadata={'''help''': '''Overwrite the cached training and evaluation sets'''} )


def       UpperCamelCase__(			UpperCamelCase__     :			DataTrainingArguments					,	UpperCamelCase__     :			PreTrainedTokenizer					,	UpperCamelCase__     :			bool = False					,	UpperCamelCase__     :			Optional[str] = None					,	)->str:
       def _dataset(UpperCamelCase__     :			List[str]					,	UpperCamelCase__     :			Optional[int]=None    ):
              if args.line_by_line:
                     if ref_path is not None:
                            if not args.whole_word_mask or not args.mlm:
                                   raise ValueError('''You need to set world whole masking and mlm to True for Chinese Whole Word Mask'''    )
                            return LineByLineWithRefDataset(
                                tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size					,	ref_path=UpperCamelCase__					,	)

                     return LineByLineTextDataset(tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size    )
              else:
                     return TextDataset(
                         tokenizer=UpperCamelCase__					,	file_path=UpperCamelCase__					,	block_size=args.block_size					,	overwrite_cache=args.overwrite_cache					,	cache_dir=UpperCamelCase__					,	)

       if evaluate:
              return _dataset(args.eval_data_file					,	args.eval_ref_file    )
       elif args.train_data_files:
              return ConcatDataset([_dataset(UpperCamelCase__    ) for f in glob(args.train_data_files    )]    )
       else:
              return _dataset(args.train_data_file					,	args.train_ref_file    )


def       UpperCamelCase__(			)->List[Any]:
       # 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.

       A__		   =		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)    )
       A__   ,      A__   ,      A__		   =		parser.parse_args_into_dataclasses()

       if data_args.eval_data_file is None and training_args.do_eval:
              raise ValueError(
                  '''Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file '''
                  '''or remove the --do_eval argument.'''    )
       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    )

       # Load pretrained model and tokenizer
       #
       # Distributed training:
       # The .from_pretrained methods guarantee that only one local process can concurrently
       # download model & vocab.

       if model_args.config_name:
              A__		   =		AutoConfig.from_pretrained(model_args.config_name					,	cache_dir=model_args.cache_dir    )
       elif model_args.model_name_or_path:
              A__		   =		AutoConfig.from_pretrained(model_args.model_name_or_path					,	cache_dir=model_args.cache_dir    )
       else:
              A__		   =		CONFIG_MAPPING[model_args.model_type]()
              logger.warning('''You are instantiating a new config instance from scratch.'''    )

       if model_args.tokenizer_name:
              A__		   =		AutoTokenizer.from_pretrained(model_args.tokenizer_name					,	cache_dir=model_args.cache_dir    )
       elif model_args.model_name_or_path:
              A__		   =		AutoTokenizer.from_pretrained(model_args.model_name_or_path					,	cache_dir=model_args.cache_dir    )
       else:
              raise ValueError(
                  '''You are instantiating a new tokenizer from scratch. This is not supported, but you can do it from another'''
                  ''' script, save it,and load it from here, using --tokenizer_name'''    )

       if model_args.model_name_or_path:
              A__		   =		AutoModelWithLMHead.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					,	)
       else:
              logger.info('''Training new model from scratch'''    )
              A__		   =		AutoModelWithLMHead.from_config(UpperCamelCase__    )

       model.resize_token_embeddings(len(UpperCamelCase__    )    )

       if config.model_type in ["bert", "roberta", "distilbert", "camembert"] and not data_args.mlm:
              raise ValueError(
                  '''BERT and RoBERTa-like models do not have LM heads but masked LM heads. They must be run using the'''
                  '''--mlm flag (masked language modeling).'''    )

       if data_args.block_size <= 0:
              A__		   =		tokenizer.max_len
              # Our input block size will be the max possible for the model
       else:
              A__		   =		min(data_args.block_size					,	tokenizer.max_len    )

       # Get datasets

       A__		   =		(
           get_dataset(UpperCamelCase__					,	tokenizer=UpperCamelCase__					,	cache_dir=model_args.cache_dir    ) if training_args.do_train else None
       )
       A__		   =		(
           get_dataset(UpperCamelCase__					,	tokenizer=UpperCamelCase__					,	evaluate=UpperCamelCase__					,	cache_dir=model_args.cache_dir    )
           if training_args.do_eval
           else None
       )
       if config.model_type == "xlnet":
              A__		   =		DataCollatorForPermutationLanguageModeling(
                  tokenizer=UpperCamelCase__					,	plm_probability=data_args.plm_probability					,	max_span_length=data_args.max_span_length					,	)
       else:
              if data_args.mlm and data_args.whole_word_mask:
                     A__		   =		DataCollatorForWholeWordMask(
                         tokenizer=UpperCamelCase__					,	mlm_probability=data_args.mlm_probability    )
              else:
                     A__		   =		DataCollatorForLanguageModeling(
                         tokenizer=UpperCamelCase__					,	mlm=data_args.mlm					,	mlm_probability=data_args.mlm_probability    )

    # Initialize our Trainer
       A__		   =		Trainer(
           model=UpperCamelCase__					,	args=UpperCamelCase__					,	data_collator=UpperCamelCase__					,	train_dataset=UpperCamelCase__					,	eval_dataset=UpperCamelCase__					,	prediction_loss_only=UpperCamelCase__					,	)

       # Training
       if training_args.do_train:
              A__		   =		(
                  model_args.model_name_or_path
                  if model_args.model_name_or_path is not None and os.path.isdir(model_args.model_name_or_path    )
                  else None
              )
              trainer.train(model_path=UpperCamelCase__    )
              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
       A__		   =		{}
       if training_args.do_eval:
              logger.info('''*** Evaluate ***'''    )

              A__		   =		trainer.evaluate()

              A__		   =		math.exp(eval_output['''eval_loss''']    )
              A__		   =		{'''perplexity''': perplexity}

              A__		   =		os.path.join(training_args.output_dir					,	'''eval_results_lm.txt'''    )
              if trainer.is_world_master():
                     with open(UpperCamelCase__					,	'''w'''    ) as writer:
                            logger.info('''***** Eval results *****'''    )
                            for key in sorted(result.keys()    ):
                                   logger.info('''  %s = %s'''					,	UpperCamelCase__					,	str(result[key]    )    )
                                   writer.write('''%s = %s\n''' % (key, str(result[key]    ))    )

              results.update(UpperCamelCase__    )

       return results


def       UpperCamelCase__(			UpperCamelCase__     :			List[str]    )->List[str]:
       # For xla_spawn (TPUs)
       main()


if __name__ == "__main__":
       main()





