


'''simple docstring'''


import math






def        __lowerCAmelCase       (__lowerCAmelCase      ):
		_UpperCAmelCase						:				Tuple	    =					0
		_UpperCAmelCase						:				Tuple	    =					0
		while num > 0:
				_UpperCAmelCase						:				List[Any]	    =					num % 8
				_UpperCAmelCase						:				Optional[int]	    =					octal + (remainder * math.floor(math.pow(10					,       __lowerCAmelCase      )      ))
				counter += 1
				_UpperCAmelCase						:				Optional[Any]	    =					math.floor(num / 8      )  # basically /= 8 without remainder if any
				# This formatting removes trailing '.0' from `octal`.
		return F"""0o{int(__lowerCAmelCase      )}"""






def        __lowerCAmelCase       ():
		print("\n2 in octal is:"      )
		print(decimal_to_octal(2      )      )  # = 2
		print("\n8 in octal is:"      )
		print(decimal_to_octal(8      )      )  # = 10
		print("\n65 in octal is:"      )
		print(decimal_to_octal(65      )      )  # = 101
		print("\n216 in octal is:"      )
		print(decimal_to_octal(216      )      )  # = 330
		print("\n512 in octal is:"      )
		print(decimal_to_octal(512      )      )  # = 1000
		print("\n"      )


if __name__ == "__main__":
						main()







'''simple docstring'''


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      ):
		_UpperCAmelCase						:				Dict	    =					filter(lambda __lowerCAmelCase      : p.requires_grad					,       model.parameters()      )
		_UpperCAmelCase						:				Optional[Any]	    =					sum([np.prod(p.size()      ) for p in model_parameters]      )
		return params


lowerCamelCase__					=   logging.getLogger(__name__)






def        __lowerCAmelCase       (__lowerCAmelCase					,       __lowerCAmelCase      ):
		if metric == "rouge2":
				_UpperCAmelCase						:				List[str]	    =					"{val_avg_rouge2:.4f}-{step_count}"
		elif metric == "bleu":
				_UpperCAmelCase						:				int	    =					"{val_avg_bleu:.4f}-{step_count}"
		elif metric == "em":
				_UpperCAmelCase						:				str	    =					"{val_avg_em:.4f}-{step_count}"
		elif metric == "loss":
				_UpperCAmelCase						:				List[Any]	    =					"{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						:				Any	    =					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					,       __lowerCAmelCase      ):
		return EarlyStopping(
		    monitor=F"""val_{metric}"""					,       mode="min" if "loss" in metric else "max"					,       patience=__lowerCAmelCase					,       verbose=__lowerCAmelCase					,       )






class 		lowerCAmelCase__	(	pl.Callback		):




			def 							lowerCAmelCase__			(						self     :   Union[str, Any]		,     lowerCamelCase__     :   Optional[int]		,     lowerCamelCase__     :   Optional[int]       )      ->int:



					'''simple docstring'''







					_UpperCAmelCase						:				Dict	    =					{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 							lowerCAmelCase__			(						self     :   Optional[Any]		,     lowerCamelCase__     :   pl.Trainer		,     lowerCamelCase__     :   pl.LightningModule		,     lowerCamelCase__     :   str		,     lowerCamelCase__     :   Union[str, Any]=True       )      ->None:



					'''simple docstring'''







					logger.info(F"""***** {type_path} results at step {trainer.global_step:05d} *****"""       )
					_UpperCAmelCase						:				str	    =					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						:				Any	    =					Path(pl_module.hparams.output_dir       )
					if type_path == "test":
							_UpperCAmelCase						:				List[Any]	    =					od / "test_results.txt"
							_UpperCAmelCase						:				Union[str, Any]	    =					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						:				Optional[Any]	    =					od / F"""{type_path}_results/{trainer.global_step:05d}.txt"""
							_UpperCAmelCase						:				Dict	    =					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						:				Dict	    =					metrics[key]
									if isinstance(lowerCamelCase__		,     torch.Tensor       ):
											_UpperCAmelCase						:				Tuple	    =					val.item()
									_UpperCAmelCase						:				str	    =					F"""{key}: {val:.6f}\n"""
									writer.write(lowerCamelCase__       )

					if not save_generations:
							return

					if "preds" in metrics:
							_UpperCAmelCase						:				Optional[int]	    =					"\n".join(metrics["preds"]       )
							generations_file.open("w+"       ).write(lowerCamelCase__       )




			@rank_zero_only
			def 							lowerCAmelCase__			(						self     :   Dict		,     lowerCamelCase__     :   Optional[int]		,     lowerCamelCase__     :   Optional[int]       )      ->Any:



					'''simple docstring'''







					try:
							_UpperCAmelCase						:				Tuple	    =					pl_module.model.model.num_parameters()
					except AttributeError:
							_UpperCAmelCase						:				int	    =					pl_module.model.num_parameters()

					_UpperCAmelCase						:				int	    =					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 							lowerCAmelCase__			(						self     :   Dict		,     lowerCamelCase__     :   pl.Trainer		,     lowerCamelCase__     :   pl.LightningModule       )      ->int:



					'''simple docstring'''







					save_json(pl_module.metrics		,     pl_module.metrics_save_path       )
					return self._write_logs(lowerCamelCase__		,     lowerCamelCase__		,     "test"       )






			@rank_zero_only
			def 							lowerCAmelCase__			(						self     :   Tuple		,     lowerCamelCase__     :   pl.Trainer		,     lowerCamelCase__     :   Union[str, Any]       )      ->Union[str, Any]:



					'''simple docstring'''







					save_json(pl_module.metrics		,     pl_module.metrics_save_path       )
					# Uncommenting this will save val generations
					# return self._write_logs(trainer, pl_module, "valid")



