This commit is contained in:
hobogalaxy committed 2021-01-10 16:03:00 +01:00
1 parent 0030c94b17
commit 66097c4bf3
11 files changed
+162 -200

No files matched your search

@@ -8,7 +8,7 @@ import wandb
import os
class SaveOnnxModelToWandbCallback(Callback):
class SaveOnnxModelToWandb(Callback):
"""
Save model in .onnx format and upload to wandb.
Might crash since not all lightning_models are compatible with onnx.
@@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback):
wandb.save(file_path, base_path=self.wandb_save_dir)
class ImagePredictionWandbLoggerCallback(Callback):
class SaveImagePredictionsToWandb(Callback):
"""
Each epoch upload to wandb a couple of the same images with predicted labels.
"""
@@ -58,7 +58,7 @@ class ImagePredictionWandbLoggerCallback(Callback):
]}, commit=False)
class MetricsHeatmapWandbLoggerCallback(Callback):
class SaveMetricsHeatmapToWandb(Callback):
"""
Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets.
@@ -107,7 +107,7 @@ class MetricsHeatmapWandbLoggerCallback(Callback):
self.targets = []
class ConfusionMatrixWandbLoggerCallback(Callback):
class SaveConfusionMatrixToWandb(Callback):
"""
Generate Confusion Matrix.
Expects validation step to return predictions and targets.
@@ -152,7 +152,7 @@ class ConfusionMatrixWandbLoggerCallback(Callback):
self.targets = []
class SaveCodeToWandbCallback(Callback):
class SaveCodeToWandb(Callback):
"""
Upload specified code files to wandb at the beginning of the run.
"""
@@ -175,13 +175,8 @@ class SaveCodeToWandbCallback(Callback):
pass
class SaveBestMetricScores(Callback):
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
@@ -190,8 +185,6 @@ class SaveBestMetricScores(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()
@@ -206,25 +199,10 @@ class SaveBestMetricScores(Callback):
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
@@ -7,10 +7,6 @@ from torchvision.datasets import MNIST
class MNISTDataModule(LightningDataModule):
"""
This is example of datamodule for MNIST dataset.
The path to datamodule should be specified in your run config.
The 'args' dict contains datamodule args specified in config.
To learn how to create datamodules visit:
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
"""
@@ -20,10 +16,10 @@ class MNISTDataModule(LightningDataModule):
self.data_dir = data_dir # data_dir is specified in config.yaml
self.batch_size = args.get("batch_size") or 64
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
self.num_workers = args.get("num_workers") or 1
self.pin_memory = args.get("pin_memory") or False
self.batch_size = args["batch_size"]
self.train_val_test_split = args["train_val_test_split"]
self.num_workers = args["num_workers"]
self.pin_memory = args["pin_memory"]
self.transforms = transforms.ToTensor()
@@ -2,7 +2,7 @@ from sklearn.metrics import accuracy_score
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
from template_utils.initializers import init_optimizer
from template_utils.initializers import load_class
# import custom architectures
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
@@ -11,23 +11,19 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
class LitModel(pl.LightningModule):
"""
This is example of lightning model for MNIST classification.
The path to model should be specified in your run config. (run_configs.yaml)
The 'hparams' dict contains model args specified in config. (run_configs.yaml)
This class enables you to specify what happens during training, validation and test step.
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
To learn how to create lightning models visit:
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
"""
def __init__(self, optimizer_config, **hparams):
def __init__(self, model_config, optimizer_config):
super().__init__()
self.optimizer_config = optimizer_config
hparams = {**model_config["args"], **optimizer_config["args"]}
self.save_hyperparameters(hparams)
self.optimizer_config = optimizer_config
self.model = SimpleMNISTClassifier(hparams=hparams)
self.model = SimpleMNISTClassifier(hparams=self.hparams)
def forward(self, x):
return self.model(x)
@@ -41,11 +37,10 @@ class LitModel(pl.LightningModule):
# training metrics
preds = torch.argmax(logits, dim=1)
acc = accuracy_score(preds.cpu(), y.cpu())
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_loss', loss, on_step=False, on_epoch=True)
self.log('train_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, acc, preds, y
return loss
# logic for a single validation step
def validation_step(self, batch, batch_idx):
@@ -56,10 +51,11 @@ class LitModel(pl.LightningModule):
# validation metrics
preds = torch.argmax(logits, dim=1)
acc = accuracy_score(preds.cpu(), y.cpu())
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_loss', loss, on_step=False, on_epoch=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
return loss, acc, preds, y
# we can return here anything and then read it in some callback
return loss, {"preds": preds, "acc": acc, "y": y}
# logic for a single testing step
def test_step(self, batch, batch_idx):
@@ -70,10 +66,11 @@ class LitModel(pl.LightningModule):
# test metrics
preds = torch.argmax(logits, dim=1)
acc = accuracy_score(preds.cpu(), y.cpu())
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_loss', loss, on_step=False, on_epoch=True)
self.log('test_acc', acc, on_step=False, on_epoch=True)
return loss
def configure_optimizers(self):
return init_optimizer(optimizer_config=self.optimizer_config, model=self)
Optimizer = load_class(self.optimizer_config["class"])
return Optimizer(self.parameters(), **self.optimizer_config["args"])