add callback for saving best metrics scores to wandb
This commit is contained in:
1 parent
d24568e686
commit
0030c94b17
9 files changed
+103
-36
No files matched your search
@@ -7,11 +7,13 @@ model_checkpoint:
|
|||||||
save_top_k: 1 # save k best lightning_models (determined by above metric)
|
save_top_k: 1 # save k best lightning_models (determined by above metric)
|
||||||
save_last: True # additionaly always save model from last epoch
|
save_last: True # additionaly always save model from last epoch
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # can be "max" or "min"
|
||||||
|
filepath: "checkpoints/{epoch}"
|
||||||
|
|
||||||
|
|
||||||
early_stopping:
|
early_stopping:
|
||||||
class: "pytorch_lightning.callbacks.EarlyStopping"
|
class: "pytorch_lightning.callbacks.EarlyStopping"
|
||||||
args:
|
args:
|
||||||
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
||||||
patience: 5 # how many epochs of not improving until training stops
|
patience: 100 # how many epochs of not improving until training stops
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # can be "max" or "min"
|
||||||
|
min_delta: 0.0 # minimum change in the monitored metric needed to qualify as an improvement
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
@@ -22,3 +22,14 @@ hydra:
|
|||||||
sweep:
|
sweep:
|
||||||
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
|
|
||||||
|
# extra things that are logged by all loggers as hyperparameters, before training starts
|
||||||
|
extra_logs:
|
||||||
|
log_train_val_test_sizes: True,
|
||||||
|
log_trainer_args: False,
|
||||||
|
log_model_args: True,
|
||||||
|
log_datamodule_args: True,
|
||||||
|
log_optimizer_args: True,
|
||||||
|
log_model_class_name: True,
|
||||||
|
log_datamodule_class_name: True,
|
||||||
|
log_optimizer_class_name: True
|
||||||
@@ -49,9 +49,9 @@ optimizer:
|
|||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
args: # you can add here additional logger arguments specific for this experiment
|
args: # you can add here additional logger arguments specific for this experiment
|
||||||
tags: ["uwu", "best_model"]
|
tags: [best_model"]
|
||||||
notes: ""
|
notes: ""
|
||||||
group: ""
|
group: ""
|
||||||
comet:
|
comet:
|
||||||
args:
|
args:
|
||||||
tags: ["uwu", "best_model"]
|
tags: [best_model", "uwu"]
|
||||||
@@ -2,5 +2,7 @@
|
|||||||
|
|
||||||
# Csv logger config
|
# Csv logger config
|
||||||
csv_logger:
|
csv_logger:
|
||||||
class: pytorch_lightning.logger.CSVLogger
|
class: pytorch_lightning.loggers.CSVLogger
|
||||||
args: {}
|
args:
|
||||||
|
save_dir: "."
|
||||||
|
name: "csv_logger/"
|
||||||
@@ -4,24 +4,8 @@
|
|||||||
wandb:
|
wandb:
|
||||||
class: pytorch_lightning.logger.WandbLogger
|
class: pytorch_lightning.logger.WandbLogger
|
||||||
args:
|
args:
|
||||||
project: "project_template_test"
|
project: "env_tests"
|
||||||
# entity: "your_team_name" # set to name of your team on wandb
|
entity: "lodz" # set to name of your wandb team or just remove
|
||||||
offline: False # set True to store all logs only locally
|
offline: False # set True to store all logs only locally
|
||||||
job_type: "train"
|
job_type: "train"
|
||||||
save_dir: "./"
|
save_dir: "."
|
||||||
|
|
||||||
# some extra things which will be logged by the environment
|
|
||||||
extra_logs:
|
|
||||||
watch_model: True # make wandb watch model
|
|
||||||
log_gradients: False # log gradient histograms (avoid this for very big models)
|
|
||||||
|
|
||||||
log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset
|
|
||||||
|
|
||||||
log_model_args: True
|
|
||||||
log_datamodule_args: True
|
|
||||||
log_optimizer_args: True
|
|
||||||
log_trainer_args: False
|
|
||||||
|
|
||||||
log_model_class_name: True
|
|
||||||
log_datamodule_class_name: True
|
|
||||||
log_optimizer_class_name: True
|
|
||||||
@@ -173,3 +173,63 @@ class SaveCodeToWandbCallback(Callback):
|
|||||||
"""Upload files when all validation sanity checks end."""
|
"""Upload files when all validation sanity checks end."""
|
||||||
# upload additional files
|
# upload additional files
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SaveBestMetricScores(Callback):
|
||||||
|
def __init__(self):
|
||||||
|
self.train_loss_list = []
|
||||||
|
self.train_acc_list = []
|
||||||
|
self.train_loss_best = None
|
||||||
|
self.train_acc_best = None
|
||||||
|
|
||||||
|
self.val_loss_list = []
|
||||||
|
self.val_acc_list = []
|
||||||
|
self.val_loss_best = None
|
||||||
|
self.val_acc_best = None
|
||||||
|
|
||||||
|
self.ready = False
|
||||||
|
|
||||||
|
def clear_lists(self):
|
||||||
|
self.train_loss_list.clear()
|
||||||
|
self.train_acc_list.clear()
|
||||||
|
self.val_loss_list.clear()
|
||||||
|
self.val_acc_list.clear()
|
||||||
|
|
||||||
|
def on_sanity_check_end(self, trainer, pl_module):
|
||||||
|
"""Start executing this callback only after all validation sanity checks end."""
|
||||||
|
self.ready = True
|
||||||
|
|
||||||
|
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||||
|
"""Gather data from single batch."""
|
||||||
|
if self.ready:
|
||||||
|
loss, acc, preds, targets = outputs
|
||||||
|
self.val_loss_list.append(loss)
|
||||||
|
self.val_acc_list.append(acc)
|
||||||
|
|
||||||
|
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||||
|
"""Gather data from single batch."""
|
||||||
|
if self.ready:
|
||||||
|
loss, acc, preds, targets = outputs
|
||||||
|
self.train_loss_list.append(loss)
|
||||||
|
self.train_acc_list.append(acc)
|
||||||
|
|
||||||
|
def on_epoch_end(self, trainer, pl_module):
|
||||||
|
if self.ready:
|
||||||
|
for logger in trainer.logger.experiment:
|
||||||
|
# currently works only for wandb
|
||||||
|
if isinstance(logger, wandb_run):
|
||||||
|
loss = sum(self.train_loss_list) / len(self.train_loss_list)
|
||||||
|
acc = sum(self.train_acc_list) / len(self.train_acc_list)
|
||||||
|
self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best
|
||||||
|
self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best
|
||||||
|
logger.log({"train_loss_best": self.train_loss_best}, commit=False)
|
||||||
|
logger.log({"train_acc_best": self.train_acc_best}, commit=False)
|
||||||
|
|
||||||
|
loss = sum(self.val_loss_list) / len(self.val_loss_list)
|
||||||
|
acc = sum(self.val_acc_list) / len(self.val_acc_list)
|
||||||
|
self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best
|
||||||
|
self.val_acc_best = acc if self.val_acc_best is None or acc > self.val_acc_best else self.val_acc_best
|
||||||
|
logger.log({"val_loss_best": self.val_loss_best}, commit=False)
|
||||||
|
logger.log({"val_acc_best": self.val_acc_best}, commit=False)
|
||||||
|
|
||||||
|
self.clear_lists()
|
||||||
@@ -40,12 +40,12 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# training metrics
|
# training metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
acc = accuracy_score(preds, y)
|
|
||||||
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
return loss
|
# we can return here anything and then read it in some callback
|
||||||
|
return loss, acc, preds, y
|
||||||
|
|
||||||
# logic for a single validation step
|
# logic for a single validation step
|
||||||
def validation_step(self, batch, batch_idx):
|
def validation_step(self, batch, batch_idx):
|
||||||
@@ -55,13 +55,11 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# validation metrics
|
# validation metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
acc = accuracy_score(preds, y)
|
|
||||||
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback
|
return loss, acc, preds, y
|
||||||
return preds, y
|
|
||||||
|
|
||||||
# logic for a single testing step
|
# logic for a single testing step
|
||||||
def test_step(self, batch, batch_idx):
|
def test_step(self, batch, batch_idx):
|
||||||
@@ -71,8 +69,7 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# test metrics
|
# test metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
acc = accuracy_score(preds, y)
|
|
||||||
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
||||||
|
from pytorch_lightning.callbacks.lr_monitor import LearningRateMonitor
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
@@ -126,14 +127,14 @@ def init_wandb(config: dict,
|
|||||||
"""
|
"""
|
||||||
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
||||||
# instead of auto-creating a new run
|
# instead of auto-creating a new run
|
||||||
os.environ["WANDB_RESUME"] = "must"
|
# os.environ["WANDB_RESUME"] = "must"
|
||||||
|
|
||||||
wandb_config = config["logger"]["wandb"]
|
wandb_config = config["logger"]["wandb"]
|
||||||
wandb_logger = WandbLogger(**wandb_config["args"])
|
wandb_logger = WandbLogger(**wandb_config["args"])
|
||||||
|
|
||||||
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
||||||
if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]):
|
# if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]):
|
||||||
os.makedirs(wandb_config["args"]["save_dir"])
|
# os.makedirs(wandb_config["args"]["save_dir"])
|
||||||
|
|
||||||
if hasattr(model, 'model'):
|
if hasattr(model, 'model'):
|
||||||
if wandb_config["extra_logs"]["log_gradients"]:
|
if wandb_config["extra_logs"]["log_gradients"]:
|
||||||
@@ -176,6 +177,14 @@ def init_wandb(config: dict,
|
|||||||
return wandb_logger
|
return wandb_logger
|
||||||
|
|
||||||
|
|
||||||
|
def log_extra_hparams(config: dict,
|
||||||
|
model: pl.LightningModule,
|
||||||
|
datamodule: pl.LightningDataModule,
|
||||||
|
loggers: List[pl.loggers.LightningLoggerBase],
|
||||||
|
callbacks: List[pl.callbacks.Callback]):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
def validate_config(config: dict):
|
def validate_config(config: dict):
|
||||||
# TODO
|
# TODO
|
||||||
pass
|
pass
|
||||||
|
|||||||
Reference in new issue
Block a user