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

@@ -2,67 +2,60 @@ from sklearn.metrics import precision_score, recall_score, f1_score
from pytorch_lightning.loggers import WandbLogger
from wandb.sdk.wandb_run import Run as wandb_run
from pytorch_lightning import Callback
from shutil import copy
import random
import torch
import wandb
import glob
import os
class SaveOnnxModelToWandb(Callback):
class SaveCodeToWandb(Callback):
"""
Save model in .onnx format and upload to wandb.
Might crash since not all lightning_models are compatible with onnx.
Upload all *.py files to wandb at the beginning of the run.
"""
def __init__(self, datamodule, wandb_save_dir):
first_batch = next(iter(datamodule.train_dataloader()))
x, y = first_batch
self.dummy_input = x
self.wandb_save_dir = wandb_save_dir
def __init__(self, code_dir: str):
self.code_dir = code_dir
def on_sanity_check_end(self, trainer, pl_module):
self.save_onnx_model(pl_module)
def on_train_end(self, trainer, pl_module):
self.save_onnx_model(pl_module)
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)
"""Upload files when all validation sanity checks end."""
code = wandb.Artifact('project-source', type='code')
for path in glob.glob(os.path.join(self.code_dir, '**/*.py'), recursive=True):
code.add_file(path)
wandb.run.use_artifact(code)
class SaveImagePredictionsToWandb(Callback):
"""
Each epoch upload to wandb a couple of the same images with predicted labels.
"""
def __init__(self, datamodule, num_samples=8):
first_batch = next(iter(datamodule.train_dataloader()))
self.imgs, self.labels = first_batch
self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
self.ready = True
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_epoch_end(self, trainer, pl_module):
if self.ready:
imgs = self.imgs.to(device=pl_module.device)
logits = pl_module(imgs)
preds = torch.argmax(logits, -1)
trainer.logger.experiment.log({f"img_examples": [
wandb.Image(
x,
caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
) for x, pred, y in zip(imgs, preds, self.labels)
]}, commit=False)
# class SaveImagePredictionsToWandb(Callback):
# """
# Each epoch upload to wandb a couple of the same images with predicted labels.
# """
# def __init__(self, datamodule, num_samples=8):
# first_batch = next(iter(datamodule.train_dataloader()))
# self.imgs, self.labels = first_batch
# self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
# self.ready = True
#
# 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_epoch_end(self, trainer, pl_module):
# if self.ready:
# imgs = self.imgs.to(device=pl_module.device)
# logits = pl_module(imgs)
# preds = torch.argmax(logits, -1)
# trainer.logger.experiment.log({f"img_examples": [
# wandb.Image(
# x,
# caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
# ) for x, pred, y in zip(imgs, preds, self.labels)
# ]}, commit=False)
class SaveMetricsHeatmapToWandb(Callback):
"""
Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets.
Works only for single label classification!
Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self, 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):
"""Gather data from single batch."""
if self.ready:
preds, targets = outputs
preds, targets = outputs["preds"], outputs["y"]
self.preds.append(preds)
self.targets.append(targets)
@@ -109,9 +102,9 @@ class SaveMetricsHeatmapToWandb(Callback):
class SaveConfusionMatrixToWandb(Callback):
"""
Generate Confusion Matrix.
Expects validation step to return predictions and targets.
Works only for single label classification!
Generate Confusion Matrix.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self, 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):
"""Gather data from single batch."""
if self.ready:
preds, targets = outputs
preds, targets = outputs["preds"], outputs["y"]
self.preds.append(preds)
self.targets.append(targets)
@@ -142,7 +135,7 @@ class SaveConfusionMatrixToWandb(Callback):
logger = some_logger
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.targets,
class_names=self.class_names)
@@ -152,31 +145,13 @@ class SaveConfusionMatrixToWandb(Callback):
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):
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
@@ -185,6 +160,8 @@ class SaveBestMetricScoresToWandb(Callback):
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()
@@ -192,17 +169,31 @@ class SaveBestMetricScoresToWandb(Callback):
"""Start executing this callback only after all validation sanity checks end."""
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):
"""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)
self.val_loss_list.append(outputs["loss"])
self.val_acc_list.append(outputs["acc"])
def on_epoch_end(self, trainer, pl_module):
if self.ready:
for logger in trainer.logger.experiment:
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
@@ -40,7 +40,8 @@ class LitModel(pl.LightningModule):
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)
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
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_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, {"preds": preds, "acc": acc, "y": y}
return {"loss": loss, "acc": acc, "preds": preds, "y": y}
# logic for a single testing step
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_acc', acc, on_step=False, on_epoch=True)
return loss
return {"loss": loss}
def configure_optimizers(self):
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