Dev (#113)
* change local lambda to normal function and move it outside of main method to enable DDP * update .pre-commit-config.yaml * update requirements.txt * reformat files * remove disabling lightning logs feature * change logging strings to enable python 3.7 * update README.md * remove double logging bug prevention since lightning fixed that
This commit is contained in:
1 parent
bc0de86874
commit
99b9c1a717
9 files changed
+146
-140
No files matched your search
@@ -22,11 +22,22 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||
return logger
|
||||
|
||||
raise Exception(
|
||||
"You are using wandb related callback,"
|
||||
"but WandbLogger was not found for some reason..."
|
||||
"You are using wandb related callback, but WandbLogger was not found for some reason..."
|
||||
)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
self.log_freq = log_freq
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class UploadCodeToWandbAsArtifact(Callback):
|
||||
"""Upload all *.py files to wandb as an artifact, at the beginning of the run."""
|
||||
|
||||
@@ -60,26 +71,12 @@ class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
if self.upload_best_only:
|
||||
ckpts.add_file(trainer.checkpoint_callback.best_model_path)
|
||||
else:
|
||||
for path in glob.glob(
|
||||
os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True
|
||||
):
|
||||
for path in glob.glob(os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True):
|
||||
ckpts.add_file(path)
|
||||
|
||||
experiment.use_artifact(ckpts)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
self.log_freq = log_freq
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class LogConfusionMatrixToWandb(Callback):
|
||||
"""Generate confusion matrix every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
@@ -126,9 +123,7 @@ class LogConfusionMatrixToWandb(Callback):
|
||||
sn.heatmap(confusion_matrix, annot=True, annot_kws={"size": 8}, fmt="g")
|
||||
|
||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
||||
experiment.log(
|
||||
{f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False
|
||||
)
|
||||
experiment.log({f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False)
|
||||
|
||||
# according to wandb docs this should also work but it crashes
|
||||
# experiment.log(f{"confusion_matrix/{experiment.name}": plt})
|
||||
@@ -194,9 +189,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
)
|
||||
|
||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
||||
experiment.log(
|
||||
{f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False
|
||||
)
|
||||
experiment.log({f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False)
|
||||
|
||||
# reset plot
|
||||
plt.clf()
|
||||
|
||||
@@ -105,9 +105,7 @@ class MNISTLitModel(LightningModule):
|
||||
def training_epoch_end(self, outputs: List[Any]) -> None:
|
||||
# log best so far train acc and train loss
|
||||
self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
|
||||
self.metric_hist["train/loss"].append(
|
||||
self.trainer.callback_metrics["train/loss"]
|
||||
)
|
||||
self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"])
|
||||
self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
|
||||
self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
|
||||
|
||||
@@ -133,7 +131,5 @@ class MNISTLitModel(LightningModule):
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
|
||||
|
||||
"""
|
||||
optim = hydra.utils.instantiate(
|
||||
self.hparams.optimizer, params=self.parameters()
|
||||
)
|
||||
optim = hydra.utils.instantiate(self.hparams.optimizer, params=self.parameters())
|
||||
return optim
|
||||
+25
-23
@@ -16,48 +16,45 @@ log = logging.getLogger(__name__)
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
- disabling warnings
|
||||
- disabling lightning logs
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- forcing multi-gpu friendly configuration
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
"""
|
||||
|
||||
# Enable adding new keys to config
|
||||
# enable adding new keys to config
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# Fix double logging bug (this will be removed when lightning releases patch)
|
||||
pl_logger = logging.getLogger("lightning")
|
||||
pl_logger.propagate = False
|
||||
|
||||
# [OPTIONAL] Disable python warnings if <config.disable_warnings=True>
|
||||
# disable python warnings if <config.disable_warnings=True>
|
||||
if config.get("disable_warnings"):
|
||||
log.info(f"Disabling python warnings! <{config.disable_warnings=}>")
|
||||
log.info(f"Disabling python warnings! <config.disable_warnings=True")
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# [OPTIONAL] Disable Lightning logs if <config.disable_lightning_logs=True>
|
||||
if config.get("disable_lightning_logs"):
|
||||
log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>")
|
||||
logging.getLogger("lightning").setLevel(logging.ERROR)
|
||||
|
||||
# [OPTIONAL] Set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
# set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
if config.get("debug"):
|
||||
log.info(f"Running in debug mode! <{config.debug=}>")
|
||||
log.info("Running in debug mode! <config.debug=True>")
|
||||
config.trainer.fast_dev_run = True
|
||||
|
||||
# [OPTIONAL] Force debugger friendly configuration if <config.trainer.fast_dev_run=True>
|
||||
# force debugger friendly configuration if <config.trainer.fast_dev_run=True>
|
||||
if config.trainer.get("fast_dev_run"):
|
||||
log.info(
|
||||
f"Forcing debugger friendly configuration! "
|
||||
f"<{config.trainer.fast_dev_run=}>"
|
||||
)
|
||||
log.info("Forcing debugger friendly configuration! <config.trainer.fast_dev_run=True>")
|
||||
# Debuggers don't like GPUs or multiprocessing
|
||||
if config.trainer.get("gpus"):
|
||||
config.trainer.gpus = 0
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
|
||||
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
|
||||
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>")
|
||||
# ddp doesn't like num_workers>0 or pin_memory=True
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
if config.datamodule.get("pin_memory"):
|
||||
config.datamodule.pin_memory = False
|
||||
|
||||
# Disable adding new keys to config
|
||||
# disable adding new keys to config
|
||||
OmegaConf.set_struct(config, True)
|
||||
|
||||
|
||||
@@ -99,6 +96,10 @@ def print_config(
|
||||
print(tree)
|
||||
|
||||
|
||||
def empty(*args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
def log_hyperparameters(
|
||||
config: DictConfig,
|
||||
model: pl.LightningModule,
|
||||
@@ -127,8 +128,9 @@ def log_hyperparameters(
|
||||
# choose which parts of hydra config will be saved to loggers
|
||||
hparams["trainer"] = config["trainer"]
|
||||
hparams["model"] = config["model"]
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
hparams["datamodule"] = config["datamodule"]
|
||||
if "optimizer" in config:
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
if "callbacks" in config:
|
||||
hparams["callbacks"] = config["callbacks"]
|
||||
|
||||
@@ -156,7 +158,7 @@ def log_hyperparameters(
|
||||
|
||||
# disable logging any more hyperparameters for all loggers
|
||||
# (this is just a trick to prevent trainer from logging hparams of model, since we already did that above)
|
||||
trainer.logger.log_hyperparams = lambda params: None
|
||||
trainer.logger.log_hyperparams = empty
|
||||
|
||||
|
||||
def finish(
|
||||
|
||||
Reference in new issue
Block a user