





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


a_			=					logging.getLogger(__name__)

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

a_			=					{
    "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
a_			=					{
    "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
}
a_			=					sorted(arg_to_scheduler.keys())
a_			=					"{" + ", ".join(arg_to_scheduler_choices) + "}"



class  __lowerCAmelCase     (	pl.LightningModule   ):




 def __init__(						self	,				__UpperCAmelCase	,				__UpperCAmelCase=None	,				__UpperCAmelCase="base"	,				__UpperCAmelCase=None	,				__UpperCAmelCase=None	,				__UpperCAmelCase=None	,				**__UpperCAmelCase	,				):



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

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

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




 def        lowerCamelCase      (						self	,				*__UpperCAmelCase	,				**__UpperCAmelCase				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model_type.from_pretrained(*lowerCAmelCase_	,				**lowerCAmelCase_				)




 def        lowerCamelCase      (						self				):



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




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    __lowerCamelCase													=    self.model
    __lowerCamelCase													=    ['''bias''', '''LayerNorm.weight''']
    __lowerCamelCase													=    [
        {
            '''params''': [
                p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay				)
            ],  # check this named paramters
            '''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:
       __lowerCamelCase													=    Adafactor(
           lowerCAmelCase_	,				lr=self.hparams.learning_rate	,				scale_parameter=lowerCAmelCase_	,				relative_step=lowerCAmelCase_				)

    else:
       __lowerCamelCase													=    AdamW(
           lowerCAmelCase_	,				lr=self.hparams.learning_rate	,				eps=self.hparams.adam_epsilon				)
    __lowerCamelCase													=    optimizer

    __lowerCamelCase													=    self.get_lr_scheduler()

    return [optimizer], [scheduler]




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''
    return self.validation_step(lowerCAmelCase_	,				lowerCAmelCase_				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    return self.validation_end(lowerCAmelCase_				)




 def        lowerCamelCase      (						self				):



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




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''







    if stage == "test":
       __lowerCamelCase													=    len(self.test_dataloader().dataset				)
    else:
       __lowerCamelCase													=    self.get_dataloader('''train'''	,				self.hparams.train_batch_size	,				shuffle=lowerCAmelCase_				)
       __lowerCamelCase													=    len(self.train_dataloader().dataset				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase	,				__UpperCAmelCase = False				):



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




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return self.train_loader




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return self.get_dataloader('''dev'''	,				self.hparams.eval_batch_size	,				shuffle=lowerCAmelCase_				)




 def        lowerCamelCase      (						self				):



    '''simple docstring'''
    return self.get_dataloader('''test'''	,				self.hparams.eval_batch_size	,				shuffle=lowerCAmelCase_				)




 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



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




 @pl.utilities.rank_zero_only
 def        lowerCamelCase      (						self	,				__UpperCAmelCase				):



    '''simple docstring'''
    __lowerCamelCase													=    self.output_dir.joinpath('''best_tfmr'''				)
    __lowerCamelCase													=    self.step_count
    self.model.save_pretrained(lowerCAmelCase_				)
    self.tokenizer.save_pretrained(lowerCAmelCase_				)




 @staticmethod
 def        lowerCamelCase      (						__UpperCAmelCase	,				__UpperCAmelCase				):



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



class  __lowerCAmelCase     (	pl.Callback   ):




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''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  __lowerCAmelCase     (	pl.Callback   ):




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



    '''simple docstring'''







    for name, param in pl_module.model.rag.named_parameters():
       if param.grad is None:
          print(lowerCAmelCase_				)



class  __lowerCAmelCase     (	pl.Callback   ):




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



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




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



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




 def        lowerCamelCase      (						self	,				__UpperCAmelCase	,				__UpperCAmelCase				):



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





def 		a__			(		_UpperCamelCase			: Dict ,_UpperCamelCase			: str							):
   parser.add_argument(
       '''--output_dir''' ,default=str(Path(__lowerCAmelCase							).parent / '''test_run''' / '''model_checkpoints'''							) ,type=__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=str(Path(__lowerCAmelCase							).parent / '''test_run''' / '''dummy-train-data'''							) ,type=__lowerCAmelCase ,help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.''' ,)





def 		a__			(		_UpperCamelCase			: Dict ,_UpperCamelCase			: Union[str, Any] ,_UpperCamelCase			: str=None ,_UpperCamelCase			: List[Any]=True ,_UpperCamelCase			: List[Any]=[] ,_UpperCamelCase			: Union[str, Any]=None ,_UpperCamelCase			: int=None ,**_UpperCamelCase			: int ,):
   pl.seed_everything(args.seed							)

   # init model
   __lowerCamelCase													=    Path(model.hparams.output_dir							)
   odir.mkdir(exist_ok=__lowerCAmelCase							)

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

   __lowerCamelCase													=    {}

   if args.fpaa:
      __lowerCamelCase													=    16

   if args.gpus > 1:
      __lowerCamelCase													=    '''auto'''
      __lowerCamelCase													=    '''ddp'''

   __lowerCamelCase													=    args.accumulate_grad_batches
   __lowerCamelCase													=    None
   __lowerCamelCase													=    '''auto'''

   __lowerCamelCase													=    pl.Trainer.from_argparse_args(
       __lowerCAmelCase ,weights_summary=__lowerCAmelCase ,callbacks=[logging_callback] + extra_callbacks + [InitCallback()] + [checkpoint_callback] ,logger=__lowerCAmelCase ,val_check_interval=1 ,num_sanity_val_steps=2 ,**__lowerCAmelCase ,)

   if args.do_train:
      trainer.fit(__lowerCAmelCase							)

   else:
      print('''RAG modeling tests with new set functions successfuly executed!'''							)
   return trainer











import argparse
import csv
import logging
import os
import random

import numpy as np
import torch
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from tqdm import tqdm, trange

from transformers import (
    CONFIG_NAME,
    WEIGHTS_NAME,
    AdamW,
    OpenAIGPTDoubleHeadsModel,
    OpenAIGPTTokenizer,
    get_linear_schedule_with_warmup,
)


logging.basicConfig(
    format="""%(asctime)s - %(levelname)s - %(name)s - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO
)
a_			=					logging.getLogger(__name__)





def 		a__			(		_UpperCamelCase			: str ,_UpperCamelCase			: List[Any]							):
   __lowerCamelCase													=    np.argmax(_UpperCamelCase ,axis=1							)
   return np.sum(outputs == labels							)





def 		a__			(		_UpperCamelCase			: Optional[int]							):
   with open(_UpperCamelCase ,encoding='''utf_8'''							) as f:
      __lowerCamelCase													=    csv.reader(_UpperCamelCase							)
      __lowerCamelCase													=    []
      next(_UpperCamelCase							)  # skip the first line
      for line in tqdm(_UpperCamelCase							):
         output.append((''' '''.join(line[1:5]							), line[5], line[6], int(line[-1]							) - 1)							)
   return output





def 		a__			(		_UpperCamelCase			: Any ,_UpperCamelCase			: Dict ,_UpperCamelCase			: str ,_UpperCamelCase			: Union[str, Any] ,_UpperCamelCase			: Any ,_UpperCamelCase			: Dict							):
   __lowerCamelCase													=    []
   for dataset in encoded_datasets:
      __lowerCamelCase													=    len(_UpperCamelCase							)
      __lowerCamelCase													=    np.zeros((n_batch, 2, input_len) ,dtype=np.intaa							)
      __lowerCamelCase													=    np.zeros((n_batch, 2) ,dtype=np.intaa							)
      __lowerCamelCase													=    np.full((n_batch, 2, input_len) ,fill_value=-1_00 ,dtype=np.intaa							)
      __lowerCamelCase													=    np.zeros((n_batch,) ,dtype=np.intaa							)
      for (
          i,
          (story, conta, conta, mc_label),
      ) in enumerate(_UpperCamelCase							):
         __lowerCamelCase													=    [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
         __lowerCamelCase													=    [start_token] + story[:cap_length] + [delimiter_token] + conta[:cap_length] + [clf_token]
         __lowerCamelCase													=    with_conta
         __lowerCamelCase													=    with_conta
         __lowerCamelCase													=    len(_UpperCamelCase							) - 1
         __lowerCamelCase													=    len(_UpperCamelCase							) - 1
         __lowerCamelCase													=    with_conta
         __lowerCamelCase													=    with_conta
         __lowerCamelCase													=    mc_label
      __lowerCamelCase													=    (input_ids, mc_token_ids, lm_labels, mc_labels)
      tensor_datasets.append(tuple(torch.tensor(_UpperCamelCase							) for t in all_inputs							)							)
   return tensor_datasets





def 		a__			(		):
   __lowerCamelCase													=    argparse.ArgumentParser()
   parser.add_argument('''--model_name''' ,type=_UpperCamelCase ,default='''openai-gpt''' ,help='''pretrained model name'''							)
   parser.add_argument('''--do_train''' ,action='''store_true''' ,help='''Whether to run training.'''							)
   parser.add_argument('''--do_eval''' ,action='''store_true''' ,help='''Whether to run eval on the dev set.'''							)
   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('''--train_dataset''' ,type=_UpperCamelCase ,default=''''''							)
   parser.add_argument('''--eval_dataset''' ,type=_UpperCamelCase ,default=''''''							)
   parser.add_argument('''--seed''' ,type=_UpperCamelCase ,default=42							)
   parser.add_argument('''--num_train_epochs''' ,type=_UpperCamelCase ,default=3							)
   parser.add_argument('''--train_batch_size''' ,type=_UpperCamelCase ,default=8							)
   parser.add_argument('''--eval_batch_size''' ,type=_UpperCamelCase ,default=16							)
   parser.add_argument('''--adam_epsilon''' ,default=1e-8 ,type=_UpperCamelCase ,help='''Epsilon for Adam optimizer.'''							)
   parser.add_argument('''--max_grad_norm''' ,type=_UpperCamelCase ,default=1							)
   parser.add_argument(
       '''--max_steps''' ,default=-1 ,type=_UpperCamelCase ,help=(
           '''If > 0: set total number of training                         steps to perform. Override num_train_epochs.'''
       ) ,)
   parser.add_argument(
       '''--gradient_accumulation_steps''' ,type=_UpperCamelCase ,default=1 ,help='''Number of updates steps to accumulate before                        performing a backward/update pass.''' ,)
   parser.add_argument('''--learning_rate''' ,type=_UpperCamelCase ,default=6.25e-5							)
   parser.add_argument('''--warmup_steps''' ,default=0 ,type=_UpperCamelCase ,help='''Linear warmup over warmup_steps.'''							)
   parser.add_argument('''--lr_schedule''' ,type=_UpperCamelCase ,default='''warmup_linear'''							)
   parser.add_argument('''--weight_decay''' ,type=_UpperCamelCase ,default=0.01							)
   parser.add_argument('''--lm_coef''' ,type=_UpperCamelCase ,default=0.9							)
   parser.add_argument('''--n_valid''' ,type=_UpperCamelCase ,default=3_74							)

   parser.add_argument('''--server_ip''' ,type=_UpperCamelCase ,default='''''' ,help='''Can be used for distant debugging.'''							)
   parser.add_argument('''--server_port''' ,type=_UpperCamelCase ,default='''''' ,help='''Can be used for distant debugging.'''							)
   __lowerCamelCase													=    parser.parse_args()
   print(_UpperCamelCase							)

   if args.server_ip and args.server_port:
      # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
      import ptvsd

      print('''Waiting for debugger attach'''							)
      ptvsd.enable_attach(address=(args.server_ip, args.server_port) ,redirect_output=_UpperCamelCase							)
      ptvsd.wait_for_attach()

   random.seed(args.seed							)
   np.random.seed(args.seed							)
   torch.manual_seed(args.seed							)
   torch.cuda.manual_seed_all(args.seed							)

   __lowerCamelCase													=    torch.device('''cuda''' if torch.cuda.is_available() else '''cpu'''							)
   __lowerCamelCase													=    torch.cuda.device_count()
   logger.info('''device: {}, n_gpu {}'''.format(_UpperCamelCase ,_UpperCamelCase							)							)

   if not args.do_train and not args.do_eval:
      raise ValueError('''At least one of `do_train` or `do_eval` must be True.'''							)

   if not os.path.exists(args.output_dir							):
      os.makedirs(args.output_dir							)

   # Load tokenizer and model
   # This loading functions also add new tokens and embeddings called `special tokens`
   # These new embeddings will be fine-tuned on the RocStories dataset
   __lowerCamelCase													=    ['''_start_''', '''_delimiter_''', '''_classify_''']
   __lowerCamelCase													=    OpenAIGPTTokenizer.from_pretrained(args.model_name							)
   tokenizer.add_tokens(_UpperCamelCase							)
   __lowerCamelCase													=    tokenizer.convert_tokens_to_ids(_UpperCamelCase							)
   __lowerCamelCase													=    OpenAIGPTDoubleHeadsModel.from_pretrained(args.model_name							)
   model.resize_token_embeddings(len(_UpperCamelCase							)							)
   model.to(_UpperCamelCase							)

   # Load and encode the datasets
   def tokenize_and_encode(_UpperCamelCase			: Dict							):
      if isinstance(_UpperCamelCase ,_UpperCamelCase							):
         return tokenizer.convert_tokens_to_ids(tokenizer.tokenize(_UpperCamelCase							)							)
      elif isinstance(_UpperCamelCase ,_UpperCamelCase							):
         return obj
      return [tokenize_and_encode(_UpperCamelCase							) for o in obj]

   logger.info('''Encoding dataset...'''							)
   __lowerCamelCase													=    load_rocstories_dataset(args.train_dataset							)
   __lowerCamelCase													=    load_rocstories_dataset(args.eval_dataset							)
   __lowerCamelCase													=    (train_dataset, eval_dataset)
   __lowerCamelCase													=    tokenize_and_encode(_UpperCamelCase							)

   # Compute the max input length for the Transformer
   __lowerCamelCase													=    model.config.n_positions // 2 - 2
   __lowerCamelCase													=    max(
       len(story[:max_length]							) + max(len(conta[:max_length]							) ,len(conta[:max_length]							)							) + 3
       for dataset in encoded_datasets
       for story, conta, conta, _ in dataset							)
   __lowerCamelCase													=    min(_UpperCamelCase ,model.config.n_positions							)  # Max size of input for the pre-trained model

   # Prepare inputs tensors and dataloaders
   __lowerCamelCase													=    pre_process_datasets(_UpperCamelCase ,_UpperCamelCase ,_UpperCamelCase ,*_UpperCamelCase							)
   __lowerCamelCase							,__lowerCamelCase													=    tensor_datasets[0], tensor_datasets[1]

   __lowerCamelCase													=    TensorDataset(*_UpperCamelCase							)
   __lowerCamelCase													=    RandomSampler(_UpperCamelCase							)
   __lowerCamelCase													=    DataLoader(_UpperCamelCase ,sampler=_UpperCamelCase ,batch_size=args.train_batch_size							)

   __lowerCamelCase													=    TensorDataset(*_UpperCamelCase							)
   __lowerCamelCase													=    SequentialSampler(_UpperCamelCase							)
   __lowerCamelCase													=    DataLoader(_UpperCamelCase ,sampler=_UpperCamelCase ,batch_size=args.eval_batch_size							)

   # Prepare optimizer
   if args.do_train:
      if args.max_steps > 0:
         __lowerCamelCase													=    args.max_steps
         __lowerCamelCase													=    args.max_steps // (len(_UpperCamelCase							) // args.gradient_accumulation_steps) + 1
      else:
         __lowerCamelCase													=    len(_UpperCamelCase							) // args.gradient_accumulation_steps * args.num_train_epochs

      __lowerCamelCase													=    list(model.named_parameters()							)
      __lowerCamelCase													=    ['''bias''', '''LayerNorm.bias''', '''LayerNorm.weight''']
      __lowerCamelCase													=    [
          {
              '''params''': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay							)],
              '''weight_decay''': args.weight_decay,
          },
          {'''params''': [p for n, p in param_optimizer if any(nd in n for nd in no_decay							)], '''weight_decay''': 0.0},
      ]
      __lowerCamelCase													=    AdamW(_UpperCamelCase ,lr=args.learning_rate ,eps=args.adam_epsilon							)
      __lowerCamelCase													=    get_linear_schedule_with_warmup(
          _UpperCamelCase ,num_warmup_steps=args.warmup_steps ,num_training_steps=_UpperCamelCase							)

   if args.do_train:
      __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    0, 0, None
      model.train()
      for _ in trange(int(args.num_train_epochs							) ,desc='''Epoch'''							):
         __lowerCamelCase													=    0
         __lowerCamelCase													=    0
         __lowerCamelCase													=    tqdm(_UpperCamelCase ,desc='''Training'''							)
         for step, batch in enumerate(_UpperCamelCase							):
            __lowerCamelCase													=    tuple(t.to(_UpperCamelCase							) for t in batch							)
            __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    batch
            __lowerCamelCase													=    model(_UpperCamelCase ,mc_token_ids=_UpperCamelCase ,lm_labels=_UpperCamelCase ,mc_labels=_UpperCamelCase							)
            __lowerCamelCase													=    args.lm_coef * losses[0] + losses[1]
            loss.backward()
            optimizer.step()
            scheduler.step()
            optimizer.zero_grad()
            tr_loss += loss.item()
            __lowerCamelCase													=    (
                loss.item() if exp_average_loss is None else 0.7 * exp_average_loss + 0.3 * loss.item()
            )
            nb_tr_steps += 1
            __lowerCamelCase													=    '''Training loss: {:.2e} lr: {:.2e}'''.format(_UpperCamelCase ,scheduler.get_lr()[0]							)

    # Save a trained model
   if args.do_train:
      # Save a trained model, configuration and tokenizer
      __lowerCamelCase													=    model.module if hasattr(_UpperCamelCase ,'''module'''							) else model  # Only save the model itself

      # If we save using the predefined names, we can load using `from_pretrained`
      __lowerCamelCase													=    os.path.join(args.output_dir ,_UpperCamelCase							)
      __lowerCamelCase													=    os.path.join(args.output_dir ,_UpperCamelCase							)

      torch.save(model_to_save.state_dict() ,_UpperCamelCase							)
      model_to_save.config.to_json_file(_UpperCamelCase							)
      tokenizer.save_vocabulary(args.output_dir							)

      # Load a trained model and vocabulary that you have fine-tuned
      __lowerCamelCase													=    OpenAIGPTDoubleHeadsModel.from_pretrained(args.output_dir							)
      __lowerCamelCase													=    OpenAIGPTTokenizer.from_pretrained(args.output_dir							)
      model.to(_UpperCamelCase							)

   if args.do_eval:
      model.eval()
      __lowerCamelCase							,__lowerCamelCase													=    0, 0
      __lowerCamelCase							,__lowerCamelCase													=    0, 0
      for batch in tqdm(_UpperCamelCase ,desc='''Evaluating'''							):
         __lowerCamelCase													=    tuple(t.to(_UpperCamelCase							) for t in batch							)
         __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    batch
         with torch.no_grad():
            __lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase							,__lowerCamelCase													=    model(
                _UpperCamelCase ,mc_token_ids=_UpperCamelCase ,lm_labels=_UpperCamelCase ,mc_labels=_UpperCamelCase							)

         __lowerCamelCase													=    mc_logits.detach().cpu().numpy()
         __lowerCamelCase													=    mc_labels.to('''cpu'''							).numpy()
         __lowerCamelCase													=    accuracy(_UpperCamelCase ,_UpperCamelCase							)

         eval_loss += mc_loss.mean().item()
         eval_accuracy += tmp_eval_accuracy

         nb_eval_examples += input_ids.size(0							)
         nb_eval_steps += 1

      __lowerCamelCase													=    eval_loss / nb_eval_steps
      __lowerCamelCase													=    eval_accuracy / nb_eval_examples
      __lowerCamelCase													=    tr_loss / nb_tr_steps if args.do_train else None
      __lowerCamelCase													=    {'''eval_loss''': eval_loss, '''eval_accuracy''': eval_accuracy, '''train_loss''': train_loss}

      __lowerCamelCase													=    os.path.join(args.output_dir ,'''eval_results.txt'''							)
      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]							))							)


if __name__ == "__main__":
  main()






