fix most of wandb callbacks

This commit is contained in:
hobogalaxy committed 2021-01-10 17:39:28 +01:00
1 parent 66097c4bf3
commit 90174d52c4
9 files changed
+100 -120

No files matched your search

@@ -3,3 +3,22 @@
defaults: defaults:
- default_callbacks.yaml - default_callbacks.yaml
save_best_metric_scores_to_wandb:
class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb"
args: {}
save_code_to_wandb_as_artifact:
class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb"
args:
code_dir: ${work_dir}/
save_confusion_matrix_to_wandb:
class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveConfusionMatrixToWandb"
args:
class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
save_f1_heatmap_to_wandb:
class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb"
args:
class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
+2 -2
View File
@@ -2,7 +2,7 @@
# Train with all logger at once # Train with all logger at once
defaults: defaults:
- comet.yaml
- csv_logger.yaml - csv_logger.yaml
- tensorboard.yaml
- wandb.yaml - wandb.yaml
# - comet.yaml
# - tensorboard.yaml
@@ -2,67 +2,60 @@ from sklearn.metrics import precision_score, recall_score, f1_score
from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.loggers import WandbLogger
from wandb.sdk.wandb_run import Run as wandb_run from wandb.sdk.wandb_run import Run as wandb_run
from pytorch_lightning import Callback from pytorch_lightning import Callback
from shutil import copy import random
import torch import torch
import wandb import wandb
import glob
import os import os
class SaveOnnxModelToWandb(Callback): class SaveCodeToWandb(Callback):
""" """
Save model in .onnx format and upload to wandb. Upload all *.py files to wandb at the beginning of the run.
Might crash since not all lightning_models are compatible with onnx.
""" """
def __init__(self, datamodule, wandb_save_dir): def __init__(self, code_dir: str):
first_batch = next(iter(datamodule.train_dataloader())) self.code_dir = code_dir
x, y = first_batch
self.dummy_input = x
self.wandb_save_dir = wandb_save_dir
def on_sanity_check_end(self, trainer, pl_module): def on_sanity_check_end(self, trainer, pl_module):
self.save_onnx_model(pl_module) """Upload files when all validation sanity checks end."""
code = wandb.Artifact('project-source', type='code')
def on_train_end(self, trainer, pl_module): for path in glob.glob(os.path.join(self.code_dir, '**/*.py'), recursive=True):
self.save_onnx_model(pl_module) code.add_file(path)
wandb.run.use_artifact(code)
def save_onnx_model(self, pl_module):
file_path = os.path.join(self.wandb_save_dir, "model.onnx")
pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
wandb.save(file_path, base_path=self.wandb_save_dir)
class SaveImagePredictionsToWandb(Callback): # class SaveImagePredictionsToWandb(Callback):
""" # """
Each epoch upload to wandb a couple of the same images with predicted labels. # Each epoch upload to wandb a couple of the same images with predicted labels.
""" # """
def __init__(self, datamodule, num_samples=8): # def __init__(self, datamodule, num_samples=8):
first_batch = next(iter(datamodule.train_dataloader())) # first_batch = next(iter(datamodule.train_dataloader()))
self.imgs, self.labels = first_batch # self.imgs, self.labels = first_batch
self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples] # self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
self.ready = True # self.ready = True
#
def on_sanity_check_end(self, trainer, pl_module): # def on_sanity_check_end(self, trainer, pl_module):
"""Start executing this callback only after all validation sanity checks end.""" # """Start executing this callback only after all validation sanity checks end."""
self.ready = True # self.ready = True
#
def on_validation_epoch_end(self, trainer, pl_module): # def on_validation_epoch_end(self, trainer, pl_module):
if self.ready: # if self.ready:
imgs = self.imgs.to(device=pl_module.device) # imgs = self.imgs.to(device=pl_module.device)
logits = pl_module(imgs) # logits = pl_module(imgs)
preds = torch.argmax(logits, -1) # preds = torch.argmax(logits, -1)
trainer.logger.experiment.log({f"img_examples": [ # trainer.logger.experiment.log({f"img_examples": [
wandb.Image( # wandb.Image(
x, # x,
caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}" # caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
) for x, pred, y in zip(imgs, preds, self.labels) # ) for x, pred, y in zip(imgs, preds, self.labels)
]}, commit=False) # ]}, commit=False)
class SaveMetricsHeatmapToWandb(Callback): class SaveMetricsHeatmapToWandb(Callback):
""" """
Generate f1, precision and recall heatmap from validation epoch outputs. Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
Works only for single label classification! Works only for single label classification!
""" """
def __init__(self, class_names): def __init__(self, class_names):
self.class_names = class_names self.class_names = class_names
@@ -77,7 +70,7 @@ class SaveMetricsHeatmapToWandb(Callback):
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
"""Gather data from single batch.""" """Gather data from single batch."""
if self.ready: if self.ready:
preds, targets = outputs preds, targets = outputs["preds"], outputs["y"]
self.preds.append(preds) self.preds.append(preds)
self.targets.append(targets) self.targets.append(targets)
@@ -109,9 +102,9 @@ class SaveMetricsHeatmapToWandb(Callback):
class SaveConfusionMatrixToWandb(Callback): class SaveConfusionMatrixToWandb(Callback):
""" """
Generate Confusion Matrix. Generate Confusion Matrix.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
Works only for single label classification! Works only for single label classification!
""" """
def __init__(self, class_names): def __init__(self, class_names):
self.class_names = class_names self.class_names = class_names
@@ -126,7 +119,7 @@ class SaveConfusionMatrixToWandb(Callback):
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
"""Gather data from single batch.""" """Gather data from single batch."""
if self.ready: if self.ready:
preds, targets = outputs preds, targets = outputs["preds"], outputs["y"]
self.preds.append(preds) self.preds.append(preds)
self.targets.append(targets) self.targets.append(targets)
@@ -142,7 +135,7 @@ class SaveConfusionMatrixToWandb(Callback):
logger = some_logger logger = some_logger
logger.log({ logger.log({
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix( f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
self.preds, self.preds,
self.targets, self.targets,
class_names=self.class_names) class_names=self.class_names)
@@ -152,31 +145,13 @@ class SaveConfusionMatrixToWandb(Callback):
self.targets = [] self.targets = []
class SaveCodeToWandb(Callback):
"""
Upload specified code files to wandb at the beginning of the run.
"""
def __init__(self, base_dir, wandb_save_dir, run_config):
self.base_dir = base_dir
self.wandb_save_dir = wandb_save_dir
self.model_folder = run_config["model"]["load_from"]["model_path"]
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
"template_utils/custom_callbacks.py",
"template_utils/initializers.py",
"train.py",
"config.yaml",
"run_configs.yaml",
]
def on_sanity_check_end(self, trainer, pl_module):
"""Upload files when all validation sanity checks end."""
# upload additional files
pass
class SaveBestMetricScoresToWandb(Callback): class SaveBestMetricScoresToWandb(Callback):
def __init__(self): 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_loss_list = []
self.val_acc_list = [] self.val_acc_list = []
self.val_loss_best = None self.val_loss_best = None
@@ -185,6 +160,8 @@ class SaveBestMetricScoresToWandb(Callback):
self.ready = False self.ready = False
def clear_lists(self): def clear_lists(self):
self.train_loss_list.clear()
self.train_acc_list.clear()
self.val_loss_list.clear() self.val_loss_list.clear()
self.val_acc_list.clear() self.val_acc_list.clear()
@@ -192,17 +169,31 @@ class SaveBestMetricScoresToWandb(Callback):
"""Start executing this callback only after all validation sanity checks end.""" """Start executing this callback only after all validation sanity checks end."""
self.ready = True self.ready = True
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
"""Gather data from single batch."""
# This is bugged :/ - lets wait for lightning 1.2 update
# if self.ready:
# self.train_loss_list.append(outputs["loss"])
# self.train_acc_list.append(outputs["acc"])
pass
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
"""Gather data from single batch.""" """Gather data from single batch."""
if self.ready: if self.ready:
loss, acc, preds, targets = outputs self.val_loss_list.append(outputs["loss"])
self.val_loss_list.append(loss) self.val_acc_list.append(outputs["acc"])
self.val_acc_list.append(acc)
def on_epoch_end(self, trainer, pl_module): def on_epoch_end(self, trainer, pl_module):
if self.ready: if self.ready:
for logger in trainer.logger.experiment: for logger in trainer.logger.experiment:
if isinstance(logger, wandb_run): 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) loss = sum(self.val_loss_list) / len(self.val_loss_list)
acc = sum(self.val_acc_list) / len(self.val_acc_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_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best
@@ -40,7 +40,8 @@ class LitModel(pl.LightningModule):
self.log('train_loss', loss, on_step=False, on_epoch=True) self.log('train_loss', loss, on_step=False, on_epoch=True)
self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True) self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
return loss # we can return here anything and then read it in some callback
return {"loss": loss, "acc": acc, "preds": preds, "y": 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):
@@ -54,8 +55,7 @@ class LitModel(pl.LightningModule):
self.log('val_loss', loss, on_step=False, on_epoch=True) self.log('val_loss', loss, on_step=False, on_epoch=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True) self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
# we can return here anything and then read it in some callback return {"loss": loss, "acc": acc, "preds": preds, "y": y}
return loss, {"preds": preds, "acc": acc, "y": 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):
@@ -69,7 +69,7 @@ class LitModel(pl.LightningModule):
self.log('test_loss', loss, on_step=False, on_epoch=True) self.log('test_loss', loss, on_step=False, on_epoch=True)
self.log('test_acc', acc, on_step=False, on_epoch=True) self.log('test_acc', acc, on_step=False, on_epoch=True)
return loss return {"loss": loss}
def configure_optimizers(self): def configure_optimizers(self):
Optimizer = load_class(self.optimizer_config["class"]) Optimizer = load_class(self.optimizer_config["class"])
@@ -1,5 +1,5 @@
""" """
Example file containing data transformations which can be used by datamodule. Example file containing data transformations, which can be used by datamodule.
""" """
from torchvision import transforms from torchvision import transforms
@@ -1,33 +0,0 @@
# THIS FILE WILL EXECUTE ALL EXPERIMENT CONFIGS LOCATED IN SPECIFIED FOLDER ONE AFTER THE OTHER
from argparse import ArgumentParser
import train
import wandb
import yaml
import os
def main(project_config_path, run_configs_path):
with open(project_config_path, "r") as ymlfile:
project_config = yaml.load(ymlfile, Loader=yaml.FullLoader)
with open(run_configs_path, "r") as ymlfile:
run_configs = yaml.load(ymlfile, Loader=yaml.FullLoader)
# EXECUTE ALL RUNS ONE AFTER THE OTHER
for conf_name in run_configs:
print(f"\nEXECUTING RUN: {conf_name}\n")
train.train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
wandb.finish()
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-p", "--project_config_path", type=str,
default=os.path.join(train.BASE_DIR, "config.yaml"))
parser.add_argument("-r", "--run_configs_path", type=str,
default=os.path.join(train.BASE_DIR, "run_configs.yaml"))
args = parser.parse_args()
main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path)
@@ -0,0 +1 @@
import hydra
@@ -1,4 +1,4 @@
from pytorch_modules.lightning_datamodules.mnist_datamodule import transforms from pytorch_modules.transforms import mnist_transforms
from PIL import Image from PIL import Image
# the LitModel you import should be the same as the one you used for training! # the LitModel you import should be the same as the one you used for training!
@@ -29,7 +29,7 @@ def predict():
# img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion # img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion
# preprocess # preprocess
img = transforms.mnist_test_transforms(img) img = mnist_transforms.mnist_test_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1 img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference # inference
+2
View File
@@ -9,6 +9,7 @@ import hydra
# normal imports # normal imports
from typing import List from typing import List
import wandb
# template utils imports # template utils imports
import template_utils.initializers as utils import template_utils.initializers as utils
@@ -75,6 +76,7 @@ def train(config):
def main(config: DictConfig) -> None: def main(config: DictConfig) -> None:
utils.show_config(config) # print content of config utils.show_config(config) # print content of config
train(config) train(config)
wandb.finish()
if __name__ == "__main__": if __name__ == "__main__":