From 90174d52c4316d3b679db7ef712fd0166ad988fa Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 10 Jan 2021 17:39:28 +0100 Subject: [PATCH] fix most of wandb callbacks --- .../configs/callbacks/wandb_callbacks.yaml | 19 +++ project/configs/logger/all_loggers.yaml | 4 +- .../lightning_callbacks/wandb_callbacks.py | 147 ++++++++---------- .../simple_mnist_classifier.py | 8 +- .../transforms/mnist_transforms.py | 2 +- .../template_utils/execute_all_experiments.py | 33 ---- project/template_utils/hydra_config_schema.py | 1 + ...redict_example.py => inference_example.py} | 4 +- project/train.py | 2 + 9 files changed, 100 insertions(+), 120 deletions(-) delete mode 100644 project/template_utils/execute_all_experiments.py rename project/template_utils/{predict_example.py => inference_example.py} (90%) diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml index e228987..89192fd 100644 --- a/project/configs/callbacks/wandb_callbacks.yaml +++ b/project/configs/callbacks/wandb_callbacks.yaml @@ -3,3 +3,22 @@ defaults: - 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') diff --git a/project/configs/logger/all_loggers.yaml b/project/configs/logger/all_loggers.yaml index 64c302f..76af7ec 100644 --- a/project/configs/logger/all_loggers.yaml +++ b/project/configs/logger/all_loggers.yaml @@ -2,7 +2,7 @@ # Train with all logger at once defaults: - - comet.yaml - csv_logger.yaml - - tensorboard.yaml - wandb.yaml + # - comet.yaml +# - tensorboard.yaml diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 4a8409d..1158f49 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -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 diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index d7c2e79..0911e98 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -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"]) diff --git a/project/pytorch_modules/transforms/mnist_transforms.py b/project/pytorch_modules/transforms/mnist_transforms.py index 7b22102..05e4d22 100644 --- a/project/pytorch_modules/transforms/mnist_transforms.py +++ b/project/pytorch_modules/transforms/mnist_transforms.py @@ -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 diff --git a/project/template_utils/execute_all_experiments.py b/project/template_utils/execute_all_experiments.py deleted file mode 100644 index ecec406..0000000 --- a/project/template_utils/execute_all_experiments.py +++ /dev/null @@ -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) diff --git a/project/template_utils/hydra_config_schema.py b/project/template_utils/hydra_config_schema.py index e69de29..55f1dc3 100644 --- a/project/template_utils/hydra_config_schema.py +++ b/project/template_utils/hydra_config_schema.py @@ -0,0 +1 @@ +import hydra diff --git a/project/template_utils/predict_example.py b/project/template_utils/inference_example.py similarity index 90% rename from project/template_utils/predict_example.py rename to project/template_utils/inference_example.py index 39965bb..755f349 100644 --- a/project/template_utils/predict_example.py +++ b/project/template_utils/inference_example.py @@ -1,4 +1,4 @@ -from pytorch_modules.lightning_datamodules.mnist_datamodule import transforms +from pytorch_modules.transforms import mnist_transforms from PIL import Image # 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 # 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 # inference diff --git a/project/train.py b/project/train.py index 0d9c0ab..fa1a50b 100644 --- a/project/train.py +++ b/project/train.py @@ -9,6 +9,7 @@ import hydra # normal imports from typing import List +import wandb # template utils imports import template_utils.initializers as utils @@ -75,6 +76,7 @@ def train(config): def main(config: DictConfig) -> None: utils.show_config(config) # print content of config train(config) + wandb.finish() if __name__ == "__main__":