




import logging
from pathlib import Path

import numpy as np
import pytorch_lightning as pl
import torch
from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint
from pytorch_lightning.utilities import rank_zero_only
from utils_rag import save_json



def 						lowerCAmelCase		(		_lowerCAmelCase							:   str	):




 """simple docstring"""







 UpperCAmelCase__							 =						filter(lambda _lowerCAmelCase	: p.requires_grad						,							model.parameters()	)
 UpperCAmelCase__							 =						sum([np.prod(p.size()	) for p in model_parameters]	)
 return params


_lowerCAmelCase						:   Dict		=   logging.getLogger(__name__)



def 						lowerCAmelCase		(		_lowerCAmelCase							:   Optional[int]						,							_lowerCAmelCase							:   Union[str, Any]	):




 """simple docstring"""







 if metric == "rouge2":
  UpperCAmelCase__							 =						"{val_avg_rouge2:.4f}-{step_count}"
 elif metric == "bleu":
  UpperCAmelCase__							 =						"{val_avg_bleu:.4f}-{step_count}"
 elif metric == "em":
  UpperCAmelCase__							 =						"{val_avg_em:.4f}-{step_count}"
 elif metric == "loss":
  UpperCAmelCase__							 =						"{val_avg_loss:.4f}-{step_count}"
 else:
  raise NotImplementedError(
      F'''seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this'''
      " function."	)

 UpperCAmelCase__							 =						ModelCheckpoint(
     dirpath=_lowerCAmelCase						,							filename=_lowerCAmelCase						,							monitor=F'''val_{metric}'''						,							mode="max"						,							save_top_k=1						,							every_n_epochs=1						,							)

 return checkpoint_callback



def 						lowerCAmelCase		(		_lowerCAmelCase							:   List[str]						,							_lowerCAmelCase							:   Union[str, Any]	):




 """simple docstring"""







 return EarlyStopping(
     monitor=F'''val_{metric}'''						,							mode="min" if "loss" in metric else "max"						,							patience=_lowerCAmelCase						,							verbose=_lowerCAmelCase						,							)


class 			_UpperCamelCase      (				pl.Callback		):
      def 	UpperCAmelCase_						(			self   :List[Any] ,      lowerCamelCase   :Any ,      lowerCamelCase   :Any      )     ->			Optional[Any]:
       UpperCAmelCase__							 =						{f'''lr_group_{i}''': param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups      )}
       pl_module.logger.log_metrics(lowerCamelCase      )
      @rank_zero_only
      def 	UpperCAmelCase_						(			self   :Tuple ,      lowerCamelCase   :pl.Trainer ,      lowerCamelCase   :pl.LightningModule ,      lowerCamelCase   :str ,      lowerCamelCase   :List[str]=True      )     ->			None:
       logger.info(f'''***** {type_path} results at step {trainer.global_step:05d} *****'''      )
       UpperCAmelCase__							 =						trainer.callback_metrics
       trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]}      )
       # Log results
       UpperCAmelCase__							 =						Path(pl_module.hparams.output_dir      )
       if type_path == "test":
        UpperCAmelCase__							 =						od / "test_results.txt"
        UpperCAmelCase__							 =						od / "test_generations.txt"
       else:
        # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json
        # If people want this it will be easy enough to add back.
        UpperCAmelCase__							 =						od / f'''{type_path}_results/{trainer.global_step:05d}.txt'''
        UpperCAmelCase__							 =						od / f'''{type_path}_generations/{trainer.global_step:05d}.txt'''
        results_file.parent.mkdir(exist_ok=lowerCamelCase      )
        generations_file.parent.mkdir(exist_ok=lowerCamelCase      )
       with open(lowerCamelCase ,      "a+"      ) as writer:
        for key in sorted(lowerCamelCase      ):
         if key in ["log", "progress_bar", "preds"]:
          continue
         UpperCAmelCase__							 =						metrics[key]
         if isinstance(lowerCamelCase ,      torch.Tensor      ):
          UpperCAmelCase__							 =						val.item()
         UpperCAmelCase__							 =						f'''{key}: {val:.6f}\n'''
         writer.write(lowerCamelCase      )

       if not save_generations:
        return

       if "preds" in metrics:
        UpperCAmelCase__							 =						"\n".join(metrics["preds"]      )
        generations_file.open("w+"      ).write(lowerCamelCase      )
      @rank_zero_only
      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :str ,      lowerCamelCase   :str      )     ->			int:
       try:
        UpperCAmelCase__							 =						pl_module.model.model.num_parameters()
       except AttributeError:
        UpperCAmelCase__							 =						pl_module.model.num_parameters()

       UpperCAmelCase__							 =						count_trainable_parameters(lowerCamelCase      )
       # mp stands for million parameters
       trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1e6, "grad_mp": n_trainable_pars / 1e6}      )
      @rank_zero_only
      def 	UpperCAmelCase_						(			self   :Optional[Any] ,      lowerCamelCase   :pl.Trainer ,      lowerCamelCase   :pl.LightningModule      )     ->			Optional[int]:
       save_json(pl_module.metrics ,      pl_module.metrics_save_path      )
       return self._write_logs(lowerCamelCase ,      lowerCamelCase ,      "test"      )







      @rank_zero_only
      def 	UpperCAmelCase_						(			self   :Optional[Any] ,      lowerCamelCase   :pl.Trainer ,      lowerCamelCase   :int      )     ->			Any:
       save_json(pl_module.metrics ,      pl_module.metrics_save_path      )
       # Uncommenting this will save val generations
       # return self._write_logs(trainer, pl_module, "valid")











import argparse
import os

import torch

from transformers.utils import WEIGHTS_NAME


_lowerCAmelCase						:   List[Any]		=   ["small", "medium", "large"]

_lowerCAmelCase						:   List[Any]		=   "lm_head.decoder.weight"
_lowerCAmelCase						:   Optional[int]		=   "lm_head.weight"



def 						lowerCAmelCase		(		_lowerCAmelCase							:   str						,							_lowerCAmelCase							:   str	):




 """simple docstring"""







 UpperCAmelCase__							 =						torch.load(_lowerCAmelCase	)
 UpperCAmelCase__							 =						d.pop(_lowerCAmelCase	)
 os.makedirs(_lowerCAmelCase						,							exist_ok=_lowerCAmelCase	)
 torch.save(_lowerCAmelCase						,							os.path.join(_lowerCAmelCase						,							_lowerCAmelCase	)	)


if __name__ == "__main__":
  _lowerCAmelCase						:   Dict		=   argparse.ArgumentParser()
  parser.add_argument("--dialogpt_path", default=".", type=str)
  _lowerCAmelCase						:   Union[str, Any]		=   parser.parse_args()
  for MODEL in DIALOGPT_MODELS:
    _lowerCAmelCase						:   Union[str, Any]		=   os.path.join(args.dialogpt_path, F'''{MODEL}_ft.pkl''')
    _lowerCAmelCase						:   List[str]		=   F'''./DialoGPT-{MODEL}'''
    convert_dialogpt_checkpoint(
        checkpoint_path,
        pytorch_dump_folder_path,
    )





