





import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


lowerCAmelCase_        =			logging.getLogger(__name__)

require_version("""pytorch_lightning>=1.0.4""")

lowerCAmelCase_        =			{
    """base""": AutoModel,
    """sequence-classification""": AutoModelForSequenceClassification,
    """question-answering""": AutoModelForQuestionAnswering,
    """pretraining""": AutoModelForPreTraining,
    """token-classification""": AutoModelForTokenClassification,
    """language-modeling""": AutoModelWithLMHead,
    """summarization""": AutoModelForSeqaSeqLM,
    """translation""": AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
lowerCAmelCase_        =			{
    """linear""": get_linear_schedule_with_warmup,
    """cosine""": get_cosine_schedule_with_warmup,
    """cosine_w_restarts""": get_cosine_with_hard_restarts_schedule_with_warmup,
    """polynomial""": get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
lowerCAmelCase_        =			sorted(arg_to_scheduler.keys())
lowerCAmelCase_        =			"""{""" + """, """.join(arg_to_scheduler_choices) + """}"""



class 				_lowerCAmelCase			(	pl.LightningModule							):


  '''simple docstring'''







  def __init__(					self					:    int					, UpperCamelCase					:    argparse.Namespace					, UpperCamelCase					:    Optional[int]=None					, UpperCamelCase					:    List[str]="base"					, UpperCamelCase					:    Dict=None					, UpperCamelCase					:    Dict=None					, UpperCamelCase					:    int=None					, **UpperCamelCase					:    Union[str, Any]					, ):


    '''simple docstring'''





    super().__init__()
    # TODO: move to self.save_hyperparameters()
    # self.save_hyperparameters()
    # can also expand arguments into trainer signature for easier reading

    self.save_hyperparameters(UpperCamelCase							)
    _snake_case      : Optional[Any]														=		0
    _snake_case      : List[str]														=		Path(self.hparams.output_dir							)
    _snake_case      : Optional[Any]														=		self.hparams.cache_dir if self.hparams.cache_dir else None
    if config is None:
      _snake_case      : List[str]														=		AutoConfig.from_pretrained(
          self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path					, **({'num_labels': num_labels} if num_labels is not None else {})					, cache_dir=UpperCamelCase					, **UpperCamelCase					, )
    else:
      _snake_case      : PretrainedConfig														=		config

    _snake_case      : Dict														=		('encoder_layerdrop', 'decoder_layerdrop', 'dropout', 'attention_dropout')
    for p in extra_model_params:
      if getattr(self.hparams					, UpperCamelCase					, UpperCamelCase							):
        assert hasattr(self.config					, UpperCamelCase							), f"""model config doesn't have a `{p}` attribute"""
        setattr(self.config					, UpperCamelCase					, getattr(self.hparams					, UpperCamelCase							)							)

    if tokenizer is None:
      _snake_case      : Optional[Any]														=		AutoTokenizer.from_pretrained(
          self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path					, cache_dir=UpperCamelCase					, )
    else:
      _snake_case      : PreTrainedTokenizer														=		tokenizer
    _snake_case      : Dict														=		MODEL_MODES[mode]
    if model is None:
      _snake_case      : List[Any]														=		self.model_type.from_pretrained(
          self.hparams.model_name_or_path					, from_tf=bool('.ckpt' in self.hparams.model_name_or_path							)					, config=self.config					, cache_dir=UpperCamelCase					, )
    else:
      _snake_case      : Any														=		model







  def UpperCamelCase_       (					self					:    List[str]					, *UpperCamelCase					:    List[Any]					, **UpperCamelCase					:    List[Any]							):


    '''simple docstring'''





    _snake_case      : str														=		self.model_type.from_pretrained(*UpperCamelCase					, **UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[str]							):


    '''simple docstring'''





    _snake_case      : Dict														=		arg_to_scheduler[self.hparams.lr_scheduler]
    _snake_case      : Tuple														=		get_schedule_func(
        self.opt					, num_warmup_steps=self.hparams.warmup_steps					, num_training_steps=self.total_steps()							)
    _snake_case      : Dict														=		{'scheduler': scheduler, 'interval': 'step', 'frequency': 1}
    return scheduler







  def UpperCamelCase_       (					self					:    Optional[int]							):


    '''simple docstring'''





    _snake_case      : Optional[Any]														=		self.model
    _snake_case      : Optional[Any]														=		['bias', 'LayerNorm.weight']
    _snake_case      : Tuple														=		[
        {
            'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay							)],
            'weight_decay': self.hparams.weight_decay,
        },
        {
            'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay							)],
            'weight_decay': 0.0,
        },
    ]
    if self.hparams.adafactor:
      _snake_case      : str														=		Adafactor(
          UpperCamelCase					, lr=self.hparams.learning_rate					, scale_parameter=UpperCamelCase					, relative_step=UpperCamelCase							)

    else:
      _snake_case      : int														=		AdamW(
          UpperCamelCase					, lr=self.hparams.learning_rate					, eps=self.hparams.adam_epsilon							)
    _snake_case      : Optional[Any]														=		optimizer

    _snake_case      : Optional[Any]														=		self.get_lr_scheduler()

    return [optimizer], [scheduler]







  def UpperCamelCase_       (					self					:    List[str]					, UpperCamelCase					:    int					, UpperCamelCase					:    List[str]							):


    '''simple docstring'''





    return self.validation_step(UpperCamelCase					, UpperCamelCase							)







  def UpperCamelCase_       (					self					:    str					, UpperCamelCase					:    Union[str, Any]							):


    '''simple docstring'''





    return self.validation_end(UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Any							):


    '''simple docstring'''





    _snake_case      : Optional[Any]														=		max(1					, self.hparams.gpus							)  # TODO: consider num_tpu_cores
    _snake_case      : Tuple														=		self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
    return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs







  def UpperCamelCase_       (					self					:    str					, UpperCamelCase					:    Tuple							):


    '''simple docstring'''





    if mode == "test":
      _snake_case      : Union[str, Any]														=		len(self.test_dataloader().dataset							)
    else:
      _snake_case      : Union[str, Any]														=		self.get_dataloader('train'					, self.hparams.train_batch_size					, shuffle=UpperCamelCase							)
      _snake_case      : List[Any]														=		len(self.train_dataloader().dataset							)







  def UpperCamelCase_       (					self					:    Dict					, UpperCamelCase					:    str					, UpperCamelCase					:    int					, UpperCamelCase					:    bool = False							):


    '''simple docstring'''





    raise NotImplementedError('You must implement this for your task'							)







  def UpperCamelCase_       (					self					:    Tuple							):


    '''simple docstring'''





    return self.train_loader







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    return self.get_dataloader('dev'					, self.hparams.eval_batch_size					, shuffle=UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    return self.get_dataloader('test'					, self.hparams.eval_batch_size					, shuffle=UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Optional[int]					, UpperCamelCase					:    List[Any]							):


    '''simple docstring'''





    return os.path.join(
        self.hparams.data_dir					, 'cached_{}_{}_{}'.format(
            UpperCamelCase					, list(filter(UpperCamelCase					, self.hparams.model_name_or_path.split('/'							)							)							).pop()					, str(self.hparams.max_seq_length							)					, )					, )







  @pl.utilities.rank_zero_only
  def UpperCamelCase_       (					self					:    Tuple					, UpperCamelCase					:    Dict[str, Any]							):


    '''simple docstring'''





    _snake_case      : int														=		self.output_dir.joinpath('best_tfmr'							)
    _snake_case      : List[str]														=		self.step_count
    self.model.save_pretrained(UpperCamelCase							)
    self.tokenizer.save_pretrained(UpperCamelCase							)







  @staticmethod
  def UpperCamelCase_       (					UpperCamelCase					:    str					, UpperCamelCase					:    Dict							):


    '''simple docstring'''





    parser.add_argument(
        '--model_name_or_path'					, default=UpperCamelCase					, type=UpperCamelCase					, required=UpperCamelCase					, help='Path to pretrained model or model identifier from huggingface.co/models'					, )
    parser.add_argument(
        '--config_name'					, default=''					, type=UpperCamelCase					, help='Pretrained config name or path if not the same as model_name'							)
    parser.add_argument(
        '--tokenizer_name'					, default=UpperCamelCase					, type=UpperCamelCase					, help='Pretrained tokenizer name or path if not the same as model_name'					, )
    parser.add_argument(
        '--cache_dir'					, default=''					, type=UpperCamelCase					, help='Where do you want to store the pre-trained models downloaded from huggingface.co'					, )
    parser.add_argument(
        '--encoder_layerdrop'					, type=UpperCamelCase					, help='Encoder layer dropout probability (Optional). Goes into model.config'					, )
    parser.add_argument(
        '--decoder_layerdrop'					, type=UpperCamelCase					, help='Decoder layer dropout probability (Optional). Goes into model.config'					, )
    parser.add_argument(
        '--dropout'					, type=UpperCamelCase					, help='Dropout probability (Optional). Goes into model.config'					, )
    parser.add_argument(
        '--attention_dropout'					, type=UpperCamelCase					, help='Attention dropout probability (Optional). Goes into model.config'					, )
    parser.add_argument('--learning_rate'					, default=5e-5					, type=UpperCamelCase					, help='The initial learning rate for Adam.'							)
    parser.add_argument(
        '--lr_scheduler'					, default='linear'					, choices=UpperCamelCase					, metavar=UpperCamelCase					, type=UpperCamelCase					, help='Learning rate scheduler'					, )
    parser.add_argument('--weight_decay'					, default=0.0					, type=UpperCamelCase					, help='Weight decay if we apply some.'							)
    parser.add_argument('--adam_epsilon'					, default=1e-8					, type=UpperCamelCase					, help='Epsilon for Adam optimizer.'							)
    parser.add_argument('--warmup_steps'					, default=0					, type=UpperCamelCase					, help='Linear warmup over warmup_steps.'							)
    parser.add_argument('--num_workers'					, default=4					, type=UpperCamelCase					, help='kwarg passed to DataLoader'							)
    parser.add_argument('--num_train_epochs'					, dest='max_epochs'					, default=3					, type=UpperCamelCase							)
    parser.add_argument('--train_batch_size'					, default=32					, type=UpperCamelCase							)
    parser.add_argument('--eval_batch_size'					, default=32					, type=UpperCamelCase							)
    parser.add_argument('--adafactor'					, action='store_true'							)




class 				_lowerCAmelCase			(	pl.Callback							):


  '''simple docstring'''







  def UpperCamelCase_       (					self					:    str					, UpperCamelCase					:    Tuple					, UpperCamelCase					:    int							):


    '''simple docstring'''





    _snake_case      : Tuple														=		trainer.lr_schedulers[0]['scheduler']
    _snake_case      : List[Any]														=		{f"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()							)}
    pl_module.logger.log_metrics(UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Tuple					, UpperCamelCase					:    pl.Trainer					, UpperCamelCase					:    pl.LightningModule							):


    '''simple docstring'''





    rank_zero_info('***** Validation results *****'							)
    _snake_case      : List[Any]														=		trainer.callback_metrics
    # Log results
    for key in sorted(UpperCamelCase							):
      if key not in ["log", "progress_bar"]:
        rank_zero_info('{} = {}\n'.format(UpperCamelCase					, str(metrics[key]							)							)							)







  def UpperCamelCase_       (					self					:    Dict					, UpperCamelCase					:    pl.Trainer					, UpperCamelCase					:    pl.LightningModule							):


    '''simple docstring'''





    rank_zero_info('***** Test results *****'							)
    _snake_case      : Any														=		trainer.callback_metrics
    # Log and save results to file
    _snake_case      : Optional[int]														=		os.path.join(pl_module.hparams.output_dir					, 'test_results.txt'							)
    with open(UpperCamelCase					, 'w'							) as writer:
      for key in sorted(UpperCamelCase							):
        if key not in ["log", "progress_bar"]:
          rank_zero_info('{} = {}\n'.format(UpperCamelCase					, str(metrics[key]							)							)							)
          writer.write('{} = {}\n'.format(UpperCamelCase					, str(metrics[key]							)							)							)




def 			lowerCamelCase_		(					lowerCAmelCase:		List[Any]			,							lowerCAmelCase:		Optional[int] )->						None:
  #  To allow all pl args uncomment the following line
  #  parser = pl.Trainer.add_argparse_args(parser)
  parser.add_argument(
      '--output_dir'			,							default=lowerCAmelCase			,							type=lowerCAmelCase			,							required=lowerCAmelCase			,							help='The output directory where the model predictions and checkpoints will be written.'			,							)
  parser.add_argument(
      '--fp16'			,							action='store_true'			,							help='Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit'			,							)

  parser.add_argument(
      '--fp16_opt_level'			,							type=lowerCAmelCase			,							default='O2'			,							help=(
          'For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'
          'See details at https://nvidia.github.io/apex/amp.html'
      )			,							)
  parser.add_argument('--n_tpu_cores'			,							dest='tpu_cores'			,							type=lowerCAmelCase )
  parser.add_argument('--max_grad_norm'			,							dest='gradient_clip_val'			,							default=1.0			,							type=lowerCAmelCase			,							help='Max gradient norm' )
  parser.add_argument('--do_train'			,							action='store_true'			,							help='Whether to run training.' )
  parser.add_argument('--do_predict'			,							action='store_true'			,							help='Whether to run predictions on the test set.' )
  parser.add_argument(
      '--gradient_accumulation_steps'			,							dest='accumulate_grad_batches'			,							type=lowerCAmelCase			,							default=1			,							help='Number of updates steps to accumulate before performing a backward/update pass.'			,							)
  parser.add_argument('--seed'			,							type=lowerCAmelCase			,							default=42			,							help='random seed for initialization' )
  parser.add_argument(
      '--data_dir'			,							default=lowerCAmelCase			,							type=lowerCAmelCase			,							required=lowerCAmelCase			,							help='The input data dir. Should contain the training files for the CoNLL-2003 NER task.'			,							)







def 			lowerCamelCase_		(					lowerCAmelCase:		BaseTransformer			,							lowerCAmelCase:		argparse.Namespace			,							lowerCAmelCase:		Dict=None			,							lowerCAmelCase:		Any=True			,							lowerCAmelCase:		List[Any]=[]			,							lowerCAmelCase:		Union[str, Any]=None			,							lowerCAmelCase:		Tuple=None			,							**lowerCAmelCase:		List[Any]			,							)->						int:
  pl.seed_everything(args.seed )

  # init model
  _snake_case      : str														=		Path(model.hparams.output_dir )
  odir.mkdir(exist_ok=lowerCAmelCase )

  # add custom checkpoints
  if checkpoint_callback is None:
    _snake_case      : Any														=		pl.callbacks.ModelCheckpoint(
        filepath=args.output_dir			,							prefix='checkpoint'			,							monitor='val_loss'			,							mode='min'			,							save_top_k=1 )
  if early_stopping_callback:
    extra_callbacks.append(lowerCAmelCase )
  if logging_callback is None:
    _snake_case      : List[Any]														=		LoggingCallback()

  _snake_case      : List[Any]														=		{}

  # TODO: remove with PyTorch 1.6 since pl uses native amp
  if args.fpaa:
    _snake_case      : List[Any]														=		16
    _snake_case      : Tuple														=		args.fpaa_opt_level

  if args.gpus > 1:
    _snake_case      : List[Any]														=		'ddp'

  _snake_case      : Dict														=		args.accumulate_grad_batches
  _snake_case      : Optional[int]														=		extra_train_kwargs.get('accelerator'			,							lowerCAmelCase )
  _snake_case      : Tuple														=		extra_train_kwargs.get('profiler'			,							lowerCAmelCase )

  _snake_case      : Dict														=		pl.Trainer.from_argparse_args(
      lowerCAmelCase			,							weights_summary=lowerCAmelCase			,							callbacks=[logging_callback] + extra_callbacks			,							logger=lowerCAmelCase			,							checkpoint_callback=lowerCAmelCase			,							**lowerCAmelCase			,							)

  if args.do_train:
    trainer.fit(lowerCAmelCase )

  return trainer











import datasets

from .evaluate import (
    apply_no_ans_threshold,
    find_all_best_thresh,
    get_raw_scores,
    make_eval_dict,
    make_qid_to_has_ans,
    merge_eval,
)


lowerCAmelCase_        =			"""\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

lowerCAmelCase_        =			"""
This metric wrap the official scoring script for version 2 of the Stanford Question
Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.

SQuAD2.0 combines the 100,000 questions in SQuAD1.1 with over 50,000 unanswerable questions
written adversarially by crowdworkers to look similar to answerable ones.
To do well on SQuAD2.0, systems must not only answer questions when possible, but also
determine when no answer is supported by the paragraph and abstain from answering.
"""

lowerCAmelCase_        =			"""
Computes SQuAD v2 scores (F1 and EM).
Args:
    predictions: List of triple for question-answers to score with the following elements:
        - the question-answer 'id' field as given in the references (see below)
        - the text of the answer
        - the probability that the question has no answer
    references: List of question-answers dictionaries with the following key-values:
            - 'id': id of the question-answer pair (see above),
            - 'answers': a list of Dict {'text': text of the answer as a string}
    no_answer_threshold: float
        Probability threshold to decide that a question has no answer.
Returns:
    'exact': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
    'total': Number of score considered
    'HasAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'HasAns_f1': The F-score of predicted tokens versus the gold answer
    'HasAns_total': Number of score considered
    'NoAns_exact': Exact match (the normalized answer exactly match the gold answer)
    'NoAns_f1': The F-score of predicted tokens versus the gold answer
    'NoAns_total': Number of score considered
    'best_exact': Best exact match (with varying threshold)
    'best_exact_thresh': No-answer probability threshold associated to the best exact match
    'best_f1': Best F1 (with varying threshold)
    'best_f1_thresh': No-answer probability threshold associated to the best F1
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22', 'no_answer_probability': 0.}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_v2_metric = datasets.load_metric(\"squad_v2\")
    >>> results = squad_v2_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact': 100.0, 'f1': 100.0, 'total': 1, 'HasAns_exact': 100.0, 'HasAns_f1': 100.0, 'HasAns_total': 1, 'best_exact': 100.0, 'best_exact_thresh': 0.0, 'best_f1': 100.0, 'best_f1_thresh': 0.0}
"""



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION							,			_KWARGS_DESCRIPTION							)
class 				_lowerCAmelCase			(	datasets.Metric							):


  '''simple docstring'''







  def UpperCamelCase_       (					self					:    str							):


    '''simple docstring'''





    return datasets.MetricInfo(
        description=_DESCRIPTION					, citation=_CITATION					, inputs_description=_KWARGS_DESCRIPTION					, features=datasets.Features(
            {
                'predictions': {
                    'id': datasets.Value('string'							),
                    'prediction_text': datasets.Value('string'							),
                    'no_answer_probability': datasets.Value('float32'							),
                },
                'references': {
                    'id': datasets.Value('string'							),
                    'answers': datasets.features.Sequence(
                        {'text': datasets.Value('string'							), 'answer_start': datasets.Value('int32'							)}							),
                },
            }							)					, codebase_urls=['https://rajpurkar.github.io/SQuAD-explorer/']					, reference_urls=['https://rajpurkar.github.io/SQuAD-explorer/']					, )







  def UpperCamelCase_       (					self					:    Optional[Any]					, UpperCamelCase					:    List[str]					, UpperCamelCase					:    Optional[Any]					, UpperCamelCase					:    str=1.0							):


    '''simple docstring'''





    _snake_case      : Dict														=		{p['id']: p['no_answer_probability'] for p in predictions}
    _snake_case      : Dict														=		[{'paragraphs': [{'qas': references}]}]
    _snake_case      : Dict														=		{p['id']: p['prediction_text'] for p in predictions}

    _snake_case      : Optional[Any]														=		make_qid_to_has_ans(UpperCamelCase							)  # maps qid to True/False
    _snake_case      : str														=		[k for k, v in qid_to_has_ans.items() if v]
    _snake_case      : Optional[Any]														=		[k for k, v in qid_to_has_ans.items() if not v]

    _snake_case							,    _snake_case      : Union[str, Any]														=		get_raw_scores(UpperCamelCase					, UpperCamelCase							)
    _snake_case      : int														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : List[Any]														=		apply_no_ans_threshold(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    _snake_case      : Optional[Any]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase							)

    if has_ans_qids:
      _snake_case      : Optional[int]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'HasAns'							)
    if no_ans_qids:
      _snake_case      : List[str]														=		make_eval_dict(UpperCamelCase					, UpperCamelCase					, qid_list=UpperCamelCase							)
      merge_eval(UpperCamelCase					, UpperCamelCase					, 'NoAns'							)
    find_all_best_thresh(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)
    return dict(UpperCamelCase							)




