




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


SCREAMING_SNAKE_CASE_						:					Any			   =       logging.getLogger(__name__)

require_version('''pytorch_lightning>=1.0.4''')

SCREAMING_SNAKE_CASE_						:					Any			   =       {
    '''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
SCREAMING_SNAKE_CASE_						:					List[Any]			   =       {
    '''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
}
SCREAMING_SNAKE_CASE_						:					str			   =       sorted(arg_to_scheduler.keys())
SCREAMING_SNAKE_CASE_						:					str			   =       '''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''







class 		__UpperCAmelCase(		pl.LightningModule ):





     """simple docstring"""



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






         """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(A    )
         a__      =       0
         a__      =       Path(self.hparams.output_dir    )
         a__      =       self.hparams.cache_dir if self.hparams.cache_dir else None
         if config is None:
             a__      =       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=A						,				**A						,				)
         else:
             a__      =       config

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

         if tokenizer is None:
             a__      =       AutoTokenizer.from_pretrained(
                 self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path						,				cache_dir=A						,				)
         else:
             a__      =       tokenizer
         a__      =       MODEL_MODES[mode]
         if model is None:
             a__      =       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=A						,				)
         else:
             a__      =       model

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[Any]						,				*A :       str						,				**A :       Optional[Any]    )			->			Tuple:






         """simple docstring"""
         a__      =       self.model_type.from_pretrained(*A						,				**A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any    )			->			Any:






         """simple docstring"""
         a__      =       arg_to_scheduler[self.hparams.lr_scheduler]
         a__      =       get_schedule_func(
             self.opt						,				num_warmup_steps=self.hparams.warmup_steps						,				num_training_steps=self.total_steps()    )
         a__      =       {"""scheduler""": scheduler, """interval""": """step""", """frequency""": 1}
         return scheduler

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			Dict:






         """simple docstring"""
         a__      =       self.model
         a__      =       ["""bias""", """LayerNorm.weight"""]
         a__      =       [
             {
                 """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:
             a__      =       Adafactor(
                 A						,				lr=self.hparams.learning_rate						,				scale_parameter=A						,				relative_step=A    )

         else:
             a__      =       AdamW(
                 A						,				lr=self.hparams.learning_rate						,				eps=self.hparams.adam_epsilon    )
         a__      =       optimizer

         a__      =       self.get_lr_scheduler()

         return [optimizer], [scheduler]

     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple						,				A :       Any						,				A :       str    )			->			str:






         """simple docstring"""
         return self.validation_step(A						,				A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       str    )			->			Optional[int]:






         """simple docstring"""
         return self.validation_end(A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       int    )			->			int:






         """simple docstring"""
         a__      =       max(1						,				self.hparams.gpus    )  # TODO: consider num_tpu_cores
         a__      =       self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
         return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs

     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       Tuple    )			->			List[str]:






         """simple docstring"""
         if stage == "test":
             a__      =       len(self.test_dataloader().dataset    )
         else:
             a__      =       self.get_dataloader("""train"""						,				self.hparams.train_batch_size						,				shuffle=A    )
             a__      =       len(self.train_dataloader().dataset    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[int]						,				A :       str						,				A :       int						,				A :       bool = False    )			->			Any:






         """simple docstring"""
         raise NotImplementedError("""You must implement this for your task"""    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]    )			->			Dict:






         """simple docstring"""
         return self.train_loader

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			Any:






         """simple docstring"""
         return self.get_dataloader("""dev"""						,				self.hparams.eval_batch_size						,				shuffle=A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			Optional[Any]:






         """simple docstring"""
         return self.get_dataloader("""test"""						,				self.hparams.eval_batch_size						,				shuffle=A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]						,				A :       Any    )			->			Optional[Any]:






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

     @pl.utilities.rank_zero_only
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]						,				A :       Dict[str, Any]    )			->			None:






         """simple docstring"""
         a__      =       self.output_dir.joinpath("""best_tfmr"""    )
         a__      =       self.step_count
         self.model.save_pretrained(A    )
         self.tokenizer.save_pretrained(A    )






     @staticmethod
     def 				__SCREAMING_SNAKE_CASE		(      A :       Optional[Any]						,				A :       List[str]    )			->			Union[str, Any]:






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







class 		__UpperCAmelCase(		pl.Callback ):





     """simple docstring"""



     def 				__SCREAMING_SNAKE_CASE		(      self :       Union[str, Any]						,				A :       Tuple						,				A :       Optional[int]    )			->			Dict:






         """simple docstring"""
         if (
             trainer.is_global_zero and trainer.global_rank == 0
         ):  # we initialize the retriever only on master worker with RAY. In new pytorch-lightning accelorators are removed.
             pl_module.model.rag.retriever.init_retrieval()  # better to use hook functions.







class 		__UpperCAmelCase(		pl.Callback ):





     """simple docstring"""



     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple						,				A :       List[str]						,				A :       str    )			->			Optional[Any]:






         """simple docstring"""
         a__      =       trainer.lr_schedulers[0]["""scheduler"""]
         a__      =       {f"""lr_group_{i}""": lr for i, lr in enumerate(lr_scheduler.get_lr()    )}
         pl_module.logger.log_metrics(A    )

     def 				__SCREAMING_SNAKE_CASE		(      self :       Any						,				A :       pl.Trainer						,				A :       pl.LightningModule    )			->			List[str]:






         """simple docstring"""
         rank_zero_info("""***** Validation results *****"""    )
         a__      =       trainer.callback_metrics
         # Log results
         for key in sorted(A    ):
             if key not in ["log", "progress_bar"]:
                 rank_zero_info("""{} = {}\n""".format(A						,				str(metrics[key]    )    )    )






     def 				__SCREAMING_SNAKE_CASE		(      self :       int						,				A :       pl.Trainer						,				A :       pl.LightningModule    )			->			Tuple:






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






def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_		):
    #  To allow all pl args uncomment the following line
    #  parser = pl.Trainer.add_argparse_args(parser)
    parser.add_argument(
        """--output_dir"""   ,    default=UpperCAmelCase_   ,    type=UpperCAmelCase_   ,    required=UpperCAmelCase_   ,    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=UpperCAmelCase_   ,    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=UpperCAmelCase_		)
    parser.add_argument("""--max_grad_norm"""   ,    dest="""gradient_clip_val"""   ,    default=1.0   ,    type=UpperCAmelCase_   ,    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=UpperCAmelCase_   ,    default=1   ,    help="""Number of updates steps to accumulate before performing a backward/update pass."""   ,    )
    parser.add_argument("""--seed"""   ,    type=UpperCAmelCase_   ,    default=42   ,    help="""random seed for initialization"""		)
    parser.add_argument(
        """--data_dir"""   ,    default=UpperCAmelCase_   ,    type=UpperCAmelCase_   ,    required=UpperCAmelCase_   ,    help="""The input data dir. Should contain the training files for the CoNLL-2003 NER task."""   ,    )







def        __lowerCAmelCase (UpperCAmelCase_   ,    UpperCAmelCase_   ,    UpperCAmelCase_=None   ,    UpperCAmelCase_=True   ,    UpperCAmelCase_=None   ,    UpperCAmelCase_=[]   ,    UpperCAmelCase_=None   ,    UpperCAmelCase_=None   ,    **UpperCAmelCase_   ,    ):
    pl.seed_everything(args.seed		)

    # init model
    a__      =       Path(model.hparams.output_dir		)
    odir.mkdir(exist_ok=UpperCAmelCase_		)

    # add custom checkpoints
    if checkpoint_callback is None:
        a__      =       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(UpperCAmelCase_		)
    if logging_callback is None:
        a__      =       LoggingCallback()

    a__      =       {}

    # TODO: remove with PyTorch 1.6 since pl uses native amp
    if args.fpaa:
        a__      =       16
        # train_params["amp_level"] = args.fp16_opt_level

    if args.gpus > 1:
        a__      =       """auto"""  # "ddp"
        a__      =       """ddp"""

    a__      =       args.accumulate_grad_batches
    a__      =       None  # extra_train_kwargs.get("profiler", None) #get unwanted logs
    a__      =       """auto"""

    a__      =       pl.Trainer.from_argparse_args(
        UpperCAmelCase_   ,    weights_summary=UpperCAmelCase_   ,    callbacks=[logging_callback] + extra_callbacks + [checkpoint_callback] + [InitCallback()]   ,    logger=UpperCAmelCase_   ,    **UpperCAmelCase_   ,    )

    if args.do_train:
        trainer.fit(UpperCAmelCase_		)

    return trainer












import warnings
from dataclasses import dataclass, field
from typing import Optional, Tuple

from .training_args import TrainingArguments
from .utils import cached_property, is_tf_available, logging, requires_backends


SCREAMING_SNAKE_CASE_						:					Optional[Any]			   =       logging.get_logger(__name__)

if is_tf_available():
 import tensorflow as tf







@dataclass
class 		__UpperCAmelCase(		lowercase__ ):





     """simple docstring"""



     __UpperCAmelCase	: int						=    """tf"""
     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Name of TPU"""}       ,	)

     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Zone of TPU"""}       ,	)

     __UpperCAmelCase	: Optional[str]						=    field(
         default=lowercase__       ,	metadata={"""help""": """Name of Cloud TPU-enabled project"""}       ,	)

     __UpperCAmelCase	: float						=    field(
         default=1.0       ,	metadata={"""help""": """Power for the Polynomial decay LR scheduler."""}       ,	)

     __UpperCAmelCase	: bool						=    field(default=lowercase__       ,	metadata={"""help""": """Whether to activate the XLA compilation or not"""} )

     @cached_property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			Tuple["tf.distribute.Strategy", int]:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         logger.info("""Tensorflow: setting up strategy"""    )

         a__      =       tf.config.list_physical_devices("""GPU"""    )

         # Set to float16 at first
         if self.fpaa:
             tf.keras.mixed_precision.set_global_policy("""mixed_float16"""    )

         if self.no_cuda:
             a__      =       tf.distribute.OneDeviceStrategy(device="""/cpu:0"""    )
         else:
             try:
                 if self.tpu_name:
                     a__      =       tf.distribute.cluster_resolver.TPUClusterResolver(
                         self.tpu_name						,				zone=self.tpu_zone						,				project=self.gcp_project    )
                 else:
                     a__      =       tf.distribute.cluster_resolver.TPUClusterResolver()
             except ValueError:
                 if self.tpu_name:
                     raise RuntimeError(f"""Couldn't connect to TPU {self.tpu_name}!"""    )
                 else:
                     a__      =       None

             if tpu:
                 # Set to bfloat16 in case of TPU
                 if self.fpaa:
                     tf.keras.mixed_precision.set_global_policy("""mixed_bfloat16"""    )

                 tf.config.experimental_connect_to_cluster(A    )
                 tf.tpu.experimental.initialize_tpu_system(A    )

                 a__      =       tf.distribute.TPUStrategy(A    )

             elif len(A    ) == 0:
                 a__      =       tf.distribute.OneDeviceStrategy(device="""/cpu:0"""    )
             elif len(A    ) == 1:
                 a__      =       tf.distribute.OneDeviceStrategy(device="""/gpu:0"""    )
             elif len(A    ) > 1:
                 # If you only want to use a specific subset of GPUs use `CUDA_VISIBLE_DEVICES=0`
                 a__      =       tf.distribute.MirroredStrategy()
             else:
                 raise ValueError("""Cannot find the proper strategy, please check your environment properties."""    )

         return strategy

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Tuple    )			->			"tf.distribute.Strategy":






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         return self._setup_strategy

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			int:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         return self._setup_strategy.num_replicas_in_sync

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Dict    )			->			List[Any]:






         """simple docstring"""
         return False  # TF Logging is handled by Keras not the Trainer

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       Optional[Any]    )			->			int:






         """simple docstring"""
         if self.per_gpu_train_batch_size:
             logger.warning(
                 """Using deprecated `--per_gpu_train_batch_size` argument which will be removed in a future """
                 """version. Using `--per_device_train_batch_size` is preferred."""    )
         a__      =       self.per_gpu_train_batch_size or self.per_device_train_batch_size
         return per_device_batch_size * self.n_replicas

     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       List[str]    )			->			int:






         """simple docstring"""
         if self.per_gpu_eval_batch_size:
             logger.warning(
                 """Using deprecated `--per_gpu_eval_batch_size` argument which will be removed in a future """
                 """version. Using `--per_device_eval_batch_size` is preferred."""    )
         a__      =       self.per_gpu_eval_batch_size or self.per_device_eval_batch_size
         return per_device_batch_size * self.n_replicas






     @property
     def 				__SCREAMING_SNAKE_CASE		(      self :       str    )			->			int:






         """simple docstring"""
         requires_backends(self						,				["""tf"""]    )
         warnings.warn(
             """The n_gpu argument is deprecated and will be removed in a future version, use n_replicas instead."""						,				A						,				)
         return self._setup_strategy.num_replicas_in_sync






