From 392552a5aa6819d542da0148e16090fa129e6ef5 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Wed, 9 Dec 2020 21:47:31 +0100 Subject: [PATCH 1/6] start remaking project --- README.md | 10 +- .../{data_modules => datamodules}/.gitkeep | 0 .../mnist_datamodule}/datamodule.py | 16 +- .../mnist_datamodule}/datasets.py | 0 .../mnist_datamodule}/transforms.py | 0 project/project_config.yaml | 47 +++- project/run_configs.yaml | 88 ++++--- .../{utils => template_utils}/callbacks.py | 28 +-- .../execute_all_runs.py | 0 .../execute_sweep.py | 0 project/template_utils/initializers.py | 238 ++++++++++++++++++ .../predict_example.py | 2 +- project/train.py | 85 ++++--- project/utils/init_utils.py | 168 ------------- 14 files changed, 409 insertions(+), 273 deletions(-) rename project/{data_modules => datamodules}/.gitkeep (100%) rename project/{data_modules/mnist_digits_datamodule => datamodules/mnist_datamodule}/datamodule.py (81%) rename project/{data_modules/mnist_digits_datamodule => datamodules/mnist_datamodule}/datasets.py (100%) rename project/{data_modules/mnist_digits_datamodule => datamodules/mnist_datamodule}/transforms.py (100%) rename project/{utils => template_utils}/callbacks.py (92%) rename project/{utils => template_utils}/execute_all_runs.py (100%) rename project/{utils => template_utils}/execute_sweep.py (100%) create mode 100644 project/template_utils/initializers.py rename project/{utils => template_utils}/predict_example.py (95%) delete mode 100644 project/utils/init_utils.py diff --git a/README.md b/README.md index 0154f6a..fcf461e 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,13 @@ Click on "Use this template" button above to initialize new repository. @@ -116,7 +116,7 @@ MNIST_CLASSIFIER_V1: lin2_size: 256 lin3_size: 128 dataset: # these parameters will be passed to 'LightningDataModule' object as 'hparams' dictionary - datamodule_folder: "mnist_digits_datamodule" + datamodule_folder: "mnist_datamodule" batch_size: 256 train_val_split_ratio: 0.9 num_workers: 1 @@ -137,7 +137,7 @@ Section `model` always needs to contain `model_folder` parameter (name of the fo Section `dataset` always needs to contain `datamodule_folder` parameter (name of the folder from which `datamodule.py` will be loaded, which should contain `DataModule` class).
Every parameter in `model` section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).
-Every parameter in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/data_modules/mnist_digits_datamodule/datamodule.py)).
+Every parameter in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).

diff --git a/project/data_modules/.gitkeep b/project/datamodules/.gitkeep similarity index 100% rename from project/data_modules/.gitkeep rename to project/datamodules/.gitkeep diff --git a/project/data_modules/mnist_digits_datamodule/datamodule.py b/project/datamodules/mnist_datamodule/datamodule.py similarity index 81% rename from project/data_modules/mnist_digits_datamodule/datamodule.py rename to project/datamodules/mnist_datamodule/datamodule.py index bc4d42e..ddd57db 100644 --- a/project/data_modules/mnist_digits_datamodule/datamodule.py +++ b/project/datamodules/mnist_datamodule/datamodule.py @@ -1,10 +1,10 @@ from torch.utils.data import DataLoader, random_split +from pytorch_lightning import LightningDataModule from torchvision.transforms import transforms from torchvision.datasets import MNIST -import pytorch_lightning as pl -class DataModule(pl.LightningDataModule): +class MNISTDataModule(LightningDataModule): """ This is example of datamodule for MNIST digits dataset. All data modules should be located in separate folders with file named 'datamodule.py' containing class which @@ -18,11 +18,12 @@ class DataModule(pl.LightningDataModule): def __init__(self, hparams): super().__init__() - # hparams["data_dir"] is always automatically set to "path_to_project/data/" + # hparams["data_dir"] is always automatically set to 'data_path' from 'project_config.yaml' self.data_dir = hparams["data_dir"] self.batch_size = hparams.get("batch_size") or 64 self.train_val_split_ratio = hparams.get("train_val_split_ratio") or 0.9 + self.train_val_split = hparams.get("train_val_split") or None self.num_workers = hparams.get("num_workers") or 1 self.pin_memory = hparams.get("pin_memory") or False @@ -41,11 +42,12 @@ class DataModule(pl.LightningDataModule): """Load data. Set variables: self.data_train, self.data_val, self.data_test.""" trainset = MNIST(self.data_dir, train=True, transform=self.transforms) - train_length = int(len(trainset) * self.train_val_split_ratio) - val_length = len(trainset) - train_length - train_val_split = [train_length, val_length] + if not self.train_val_split: + train_length = int(len(trainset) * self.train_val_split_ratio) + val_length = len(trainset) - train_length + self.train_val_split = [train_length, val_length] - self.data_train, self.data_val = random_split(trainset, train_val_split) + self.data_train, self.data_val = random_split(trainset, self.train_val_split) self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms) def train_dataloader(self): diff --git a/project/data_modules/mnist_digits_datamodule/datasets.py b/project/datamodules/mnist_datamodule/datasets.py similarity index 100% rename from project/data_modules/mnist_digits_datamodule/datasets.py rename to project/datamodules/mnist_datamodule/datasets.py diff --git a/project/data_modules/mnist_digits_datamodule/transforms.py b/project/datamodules/mnist_datamodule/transforms.py similarity index 100% rename from project/data_modules/mnist_digits_datamodule/transforms.py rename to project/datamodules/mnist_datamodule/transforms.py diff --git a/project/project_config.yaml b/project/project_config.yaml index 0a97b9d..c6a2dd1 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -1,5 +1,8 @@ +# set -1 to train on all GPUs abailable, set 0 to train on CPU only num_of_gpus: 0 + +# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) loggers: wandb: project: "project_template_test" @@ -7,18 +10,36 @@ loggers: log_model: True offline: False -callbacks: - checkpoint: - monitor: "val_acc" - save_top_k: 1 - save_last: True - mode: "max" - early_stop: - monitor: "val_acc" - patience: 100 - mode: "max" +# default callbacks initialised on every run/experiment +# you can just remove this section or certain callback if you don't want tu use it +# you can add here any callback class available in pytorch lightning or template_utils/callbacks.py +default_callbacks: + checkpoint: + callback_class: "ModelCheckpoint" + args: + monitor: "val_acc" + save_top_k: 1 + save_last: True + mode: "max" + early_stop: + callback_class: "EarlyStopping" + args: + monitor: "val_acc" + patience: 100 + mode: "max" + + +# configure things which are printed in terminal printing: - progress_bar_refresh_rate: 5 - weights_summary: "top" # "full" - profiler: False + progress_bar_refresh_rate: 10 # refresh every 10 batches + weights_summary: "top" # model summary (alternatively "full") + profiler: False # set True to print execution time profiling after training ends + + +# path to data folder (either absolute or relative to placement of 'train.py' file) +data_path: "data/" + + +# path to logs folder (either absolute or relative to placement of 'train.py' file) +logs_path: "logs/" diff --git a/project/run_configs.yaml b/project/run_configs.yaml index f1d04ea..70211c6 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -1,25 +1,32 @@ -MNIST_CLASSIFIER_V1: +# make sure parameters from different sections have different names +# or they will overwrite themselvess in Weights&Biases config +EXAMPLE_MNIST_RUN_CONFIG: trainer: - max_epochs: 5 + max_epochs: 10 gradient_clip_val: 0.5 model: - model_folder: "simple_mnist_classifier" - lr: 0.001 - weight_decay: 0.000001 - input_size: 784 # img size is 1*28*28 - output_size: 10 # there are 10 digit classes - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 - dataset: - datamodule_folder: "mnist_digits_datamodule" - batch_size: 64 - train_val_split_ratio: 0.9 - num_workers: 1 - pin_memory: False + load_from: + model_path: "models/simple_mnist_classifier/lightning_module.py" + model_class: "LitModel" + hparams: + lr: 0.001 + weight_decay: 1e-5 + input_size: 784 # img size is 1*28*28 + output_size: 10 # there are 10 digit classes + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + datamodule: + load_from: + datamodule_path: "datamodules/mnist_datamodule/datamodule.py" + datamodule_class: "MNISTDataModule" + hparams: + batch_size: 64 + train_val_split: [50_000, 10_000] -MNIST_CLASSIFIER_V2: + +EXAMPLE_MNIST_RUN_CONFIG_ADVANCED: trainer: min_epochs: 1 max_epochs: 10 @@ -31,27 +38,36 @@ MNIST_CLASSIFIER_V2: limit_test_batches: 1.0 val_check_interval: 1.0 model: - model_folder: "simple_mnist_classifier" - lr: 0.002 - weight_decay: 0.00001 - input_size: 784 - output_size: 10 - lin1_size: 512 - lin2_size: 256 - lin3_size: 128 - dataset: - datamodule_folder: "mnist_digits_datamodule" - batch_size: 256 - train_val_split_ratio: 0.9 - num_workers: 1 - pin_memory: False + load_from: + model_path: "models/simple_mnist_classifier/lightning_module.py" + model_class: "LitModel" + hparams: + lr: 0.001 + weight_decay: 1e-5 + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + datamodule: + load_from: + datamodule_path: "datamodules/mnist_datamodule/datamodule.py" + datamodule_class: "MNISTDataModule" + hparams: + batch_size: 256 + train_val_split: [60_000, 10_000] # use either this or 'train_val_split_ratio' + # train_val_split_ratio: 0.9 + num_workers: 1 + pin_memory: False callbacks: - ConfusionMatrixLoggerCallback: - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - MetricsHeatmapLoggerCallback: - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + early_stop: + callback_class: "EarlyStopping" + args: + monitor: "val_acc" + patience: 5 + mode: "max" wandb: - group: None + group: "" tags: ["v2", "uwu"] notes: "This is example run." resume_training: diff --git a/project/utils/callbacks.py b/project/template_utils/callbacks.py similarity index 92% rename from project/utils/callbacks.py rename to project/template_utils/callbacks.py index 0cb9545..60d1ce1 100644 --- a/project/utils/callbacks.py +++ b/project/template_utils/callbacks.py @@ -1,13 +1,13 @@ from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score -import pytorch_lightning as pl +from pytorch_lightning import Callback +import pytorch_lightning.callbacks from shutil import copy -import inspect import torch import wandb import os -class ExampleCallback(pl.Callback): +class ExampleCallback(Callback): def __init__(self): pass @@ -21,7 +21,7 @@ class ExampleCallback(pl.Callback): print('Do something when training ends.') -class SaveOnnxModelToWandbCallback(pl.Callback): +class SaveOnnxModelToWandbCallback(Callback): """ Save model in .onnx format and upload to wandb. Might crash since not all models are compatible with onnx. @@ -44,7 +44,7 @@ class SaveOnnxModelToWandbCallback(pl.Callback): wandb.save(file_path, base_path=self.wandb_save_dir) -class ImagePredictionLoggerCallback(pl.Callback): +class ImagePredictionLoggerCallback(Callback): """ Each epoch upload to wandb a couple of the same images with predicted labels. """ @@ -71,7 +71,7 @@ class ImagePredictionLoggerCallback(pl.Callback): ]}, commit=False) -class UnfreezeModelCallback(pl.Callback): +class UnfreezeModelCallback(Callback): """ Unfreeze model after a few epochs. """ @@ -84,7 +84,7 @@ class UnfreezeModelCallback(pl.Callback): param.requires_grad = True -class MetricsHeatmapLoggerCallback(pl.Callback): +class MetricsHeatmapLoggerCallback(Callback): """ Generate f1, precision and recall heatmap from validation epoch outputs. Expects validation step to return predictions and targets. @@ -128,7 +128,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback): self.targets = [] -class ConfusionMatrixLoggerCallback(pl.Callback): +class ConfusionMatrixLoggerCallback(Callback): """ Generate Confusion Matrix. Expects validation step to return predictions and targets. @@ -168,7 +168,7 @@ class ConfusionMatrixLoggerCallback(pl.Callback): self.targets = [] -class SaveCodeToWandbCallback(pl.Callback): +class SaveCodeToWandbCallback(Callback): """ Upload specified code files to wandb at the beginning of the run. """ @@ -178,8 +178,8 @@ class SaveCodeToWandbCallback(pl.Callback): self.model_folder = run_config["model"]["model_folder"] self.datamodule_folder = run_config["dataset"]["datamodule_folder"] self.additional_files_to_be_saved = [ # paths should be relative to base_dir - "utils/callbacks.py", - "utils/init_utils.py", + "template_utils/callbacks.py", + "template_utils/initializers.py", "train.py", "project_config.yaml", "run_configs.yaml", @@ -214,11 +214,11 @@ class SaveCodeToWandbCallback(pl.Callback): wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate # upload datamodule files - for filename in os.listdir(os.path.join(self.base_dir, "data_modules", self.datamodule_folder)): + for filename in os.listdir(os.path.join(self.base_dir, "datamodules", self.datamodule_folder)): if filename.endswith('.py'): - src_path = os.path.join(self.base_dir, "data_modules", self.datamodule_folder, filename) - dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", self.datamodule_folder, filename) + src_path = os.path.join(self.base_dir, "datamodules", self.datamodule_folder, filename) + dst_path = os.path.join(self.wandb_save_dir, "code", "datamodules", self.datamodule_folder, filename) path, filename = os.path.split(dst_path) if not os.path.exists(path): diff --git a/project/utils/execute_all_runs.py b/project/template_utils/execute_all_runs.py similarity index 100% rename from project/utils/execute_all_runs.py rename to project/template_utils/execute_all_runs.py diff --git a/project/utils/execute_sweep.py b/project/template_utils/execute_sweep.py similarity index 100% rename from project/utils/execute_sweep.py rename to project/template_utils/execute_sweep.py diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py new file mode 100644 index 0000000..fbfd545 --- /dev/null +++ b/project/template_utils/initializers.py @@ -0,0 +1,238 @@ +# pytorch lightning imports +from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger +from pytorch_lightning.profiler import SimpleProfiler +import pytorch_lightning as pl + +# normal imports +from typing import List +import importlib.util +import os + +# template utils imports +import template_utils.callbacks + + +def init_model(model_config: dict, base_dir: str) -> pl.LightningModule: + """ + Load LightningModule from path specified in run config. + """ + + model_path = model_config["load_from"]["model_path"] + model_class = model_config["load_from"]["model_class"] + + if not os.path.isabs(model_path): + model_path = os.path.join(base_dir, model_path) + + assert os.path.isfile(model_path), f"incorrect model path: {model_path}" + + spec = importlib.util.spec_from_file_location("lightning_model", model_path) + lightning_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(lightning_module) + + assert hasattr(lightning_module, model_class), \ + f"model class {model_class} doesn't exists in file {model_path}" + + LitModel = getattr(lightning_module, model_class) + + assert issubclass(LitModel, pl.LightningModule), \ + f"specified model class {model_class} is not a LightningModule" + + model = LitModel(hparams=model_config["hparams"]) + + return model + + +def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> pl.LightningDataModule: + """ + Load LightningDataModule from path specified in run config. + """ + + datamodule_path = datamodule_config["load_from"]["datamodule_path"] + datamodule_class = datamodule_config["load_from"]["datamodule_class"] + + if not os.path.isabs(datamodule_path): + datamodule_path = os.path.join(base_dir, datamodule_path) + assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}" + + if not os.path.isabs(data_path): + datamodule_config["hparams"]["data_dir"] = os.path.join(base_dir, data_path) + else: + datamodule_config["hparams"]["data_dir"] = data_path + + spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path) + lightning_module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(lightning_module) + + assert hasattr(lightning_module, datamodule_class), \ + f"datamodule class {datamodule_class} doesn't exists in file {datamodule_path}" + + DataModule = getattr(lightning_module, datamodule_class) + + assert issubclass(DataModule, pl.LightningDataModule), \ + f"specified datamodule class {datamodule_class} is not a LightningDataModule" + + datamodule = DataModule(hparams=datamodule_config["hparams"]) + datamodule.prepare_data() + datamodule.setup() + + return datamodule + + +def init_trainer(project_config: dict, + run_config: dict, + callbacks: List[pl.Callback], + loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer: + """ + Initialize PyTorch Lightning Trainer. + """ + + # Get path to checkpoint that you want to resume with if it was set in the run config + resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None) + + trainer = pl.Trainer( + # whether to use gpu and how many + gpus=project_config["num_of_gpus"], + + # experiment logging + logger=loggers, + + # useful callbacks + callbacks=callbacks, + + # resume training from checkpoint if it was set in the run config + resume_from_checkpoint=resume_from_checkpoint + if resume_from_checkpoint != "None" + and resume_from_checkpoint != "False" + and resume_from_checkpoint is not False + else None, + + # print related + progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"], + profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None, + weights_summary=project_config["printing"]["weights_summary"], + + # number of validation sanity checks + num_sanity_val_steps=3, + + # default log dir if no logger is found + default_root_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs/lightning_logs"), + + # insert all other trainer parameters specified in run config + **run_config["trainer"] + ) + + return trainer + + +def init_callbacks(project_config: dict, + run_config: dict, + use_wandb: bool, + base_dir: str) -> List[pl.Callback]: + """ + Initialize default callbacks and callbacks specified in run config. + """ + + default_callbacks = project_config["default_callbacks"] + run_callbacks = run_config["callbacks"] + + callbacks = [] + + for callback_config in default_callbacks: + callback_class = getattr(pl.callbacks, callback_config["callback_class"]) + callbacks.append(callback_class(**callback_config["args"])) + + for callback_config in run_callbacks: + callback_class = getattr(pl.callbacks, callback_config["callback_class"]) + callbacks.append(callback_class(**callback_config["args"])) + + if use_wandb: + callbacks.append( + template_utils.callbacks.SaveCodeToWandbCallback( + base_dir=os.path.dirname(os.path.dirname(__file__)), + wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"), + run_config=run_config + ) + ) + + return callbacks + + +def init_loggers(project_config: dict, + run_config: dict, + lit_model: pl.LightningModule, + datamodule: pl.LightningDataModule, + use_wandb: bool, + base_dir: str) -> List[pl.loggers.LightningLoggerBase]: + """ + Initialize loggers. + """ + + return [] + + +def init_wandb_logger(project_config: dict, + run_config: dict, + lit_model: pl.LightningModule, + datamodule: pl.LightningDataModule, + log_path: str = "logs/") -> pl.loggers.WandbLogger: + """ + Initialize Weights&Biases logger. + """ + + # 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 + os.environ["WANDB_RESUME"] = "must" + + resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None) + wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None) + + wandb_logger = WandbLogger( + project=project_config["loggers"]["wandb"]["project"], + entity=project_config["loggers"]["wandb"]["entity"], + log_model=project_config["loggers"]["wandb"]["log_model"], + offline=project_config["loggers"]["wandb"]["offline"], + + group=run_config.get("wandb", {}).get("group", None), + job_type=run_config.get("wandb", {}).get("job_type", "train"), + tags=run_config.get("wandb", {}).get("tags", []), + notes=run_config.get("wandb", {}).get("notes", ""), + + # resume run only if ckpt was set in the run config + id=wandb_run_id + if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None + and resume_from_checkpoint is not False and wandb_run_id is not False + else None, + + save_dir=log_path, + save_code=False + ) + + if not os.path.exists(log_path): + os.makedirs(log_path) + + if hasattr(lit_model, 'model'): + wandb_logger.watch(lit_model.model, log=None) + else: + wandb_logger.watch(lit_model, log=None) + + wandb_logger.log_hyperparams({ + "model": lit_model.model.__class__.__name__ if hasattr(lit_model, 'model') else None, + "optimizer": lit_model.configure_optimizers().__class__.__name__, + "train_size": len(datamodule.data_train) + if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, + "val_size": len(datamodule.data_val) + if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0, + "test_size": len(datamodule.data_test) + if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0, + }) + wandb_logger.log_hyperparams(run_config["trainer"]) + wandb_logger.log_hyperparams(run_config["model"]) + wandb_logger.log_hyperparams(run_config["dataset"]) + + return wandb_logger + + +def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: + """Initialize tensorboard logger""" + # TODO + return None diff --git a/project/utils/predict_example.py b/project/template_utils/predict_example.py similarity index 95% rename from project/utils/predict_example.py rename to project/template_utils/predict_example.py index 99a31c0..8f31156 100644 --- a/project/utils/predict_example.py +++ b/project/template_utils/predict_example.py @@ -1,4 +1,4 @@ -from data_modules.mnist_digits_datamodule import transforms +from datamodules.mnist_datamodule import transforms from PIL import Image # the LitModel you import should be the same as the one you used for training! diff --git a/project/train.py b/project/train.py index b0dd6ee..af16b92 100644 --- a/project/train.py +++ b/project/train.py @@ -1,43 +1,65 @@ -from pytorch_lightning.loggers import WandbLogger +# pytorch lightning imports +from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback +from pytorch_lightning.loggers import LightningLoggerBase + +# normal imports from argparse import ArgumentParser -import pytorch_lightning as pl from typing import List import yaml import os -# utils -from utils.init_utils import init_lit_model, init_data_module, init_trainer, init_callbacks, init_wandb_logger +# template utils imports +from template_utils.initializers import ( + init_model, + init_datamodule, + init_callbacks, + init_loggers, + init_trainer +) + + +# Everything will be loaded relatively to placement of this file! +BASE_DIR: str = os.path.dirname(__file__) def train(project_config: dict, run_config: dict, use_wandb: bool): # Init PyTorch Lightning model ⚡ - lit_model: pl.LightningModule = init_lit_model(hparams=run_config["model"]) + lit_model: LightningModule = init_model( + model_config=run_config["model"], + base_dir=BASE_DIR + ) # Init PyTorch Lightning datamodule ⚡ - datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"]) + datamodule: LightningDataModule = init_datamodule( + datamodule_config=run_config["datamodule"], + data_path=project_config["data_path"], + base_dir=BASE_DIR + ) - # Init Weights&Biases logger - logger: pl.loggers.WandbLogger = init_wandb_logger( + # Init PyTorch Lightning callbacks ⚡ + callbacks: List[Callback] = init_callbacks( + project_config=project_config, + run_config=run_config, + use_wandb=use_wandb, + base_dir=BASE_DIR + ) + + # Init PyTorch Lightning loggers ⚡ + loggers: List[LightningLoggerBase] = init_loggers( project_config=project_config, run_config=run_config, lit_model=lit_model, datamodule=datamodule, - log_path=os.path.join(os.path.dirname(__file__), "logs/") - ) if use_wandb else None - - # Init callbacks - callbacks: List[pl.Callback] = init_callbacks( - project_config=project_config, - run_config=run_config, - use_wandb=use_wandb + use_wandb=use_wandb, + base_dir=BASE_DIR ) # Init PyTorch Lightning trainer ⚡ - trainer: pl.Trainer = init_trainer( + trainer: Trainer = init_trainer( project_config=project_config, run_config=run_config, - logger=logger, - callbacks=callbacks + callbacks=callbacks, + loggers=loggers ) # Evaluate model on test set before training @@ -47,20 +69,20 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): trainer.fit(model=lit_model, datamodule=datamodule) # Evaluate model on test set after training - trainer.test() + # trainer.test() -def load_config(filename): - path = os.path.join(os.path.dirname(__file__), filename) - with open(path, "r") as ymlfile: +def load_config(path): + abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path + with open(abs_path, "r") as ymlfile: config = yaml.load(ymlfile, Loader=yaml.FullLoader) return config -def main(run_config_name: str, use_wandb: bool): +def main(project_config_path: str, run_configs_path: str, run_config_name: str, use_wandb: bool): # Load configs - project_config: dict = load_config("project_config.yaml") - run_config: dict = load_config("run_configs.yaml")[run_config_name] + project_config: dict = load_config(path=project_config_path) + run_config: dict = load_config(path=run_configs_path)[run_config_name] # Train model train(project_config=project_config, run_config=run_config, use_wandb=use_wandb) @@ -68,9 +90,14 @@ def main(run_config_name: str, use_wandb: bool): if __name__ == "__main__": parser = ArgumentParser() - parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V2") - parser.add_argument("-n", "--no_wandb", dest='use_wandb', action='store_false') parser.set_defaults(use_wandb=True) + parser.add_argument("--project_config_path", type=str, default="project_config.yaml") + parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") + parser.add_argument("--run_config_name", type=str, default="EXAMPLE_MNIST_RUN_CONFIG") + parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') args = parser.parse_args() - main(run_config_name=args.run_config, use_wandb=args.use_wandb) + main(project_config_path=args.project_config_path, + run_configs_path=args.run_configs_path, + run_config_name=args.run_config_name, + use_wandb=args.use_wandb) diff --git a/project/utils/init_utils.py b/project/utils/init_utils.py deleted file mode 100644 index d74ec8c..0000000 --- a/project/utils/init_utils.py +++ /dev/null @@ -1,168 +0,0 @@ -from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping -from pytorch_lightning.profiler import SimpleProfiler -from pytorch_lightning.loggers import WandbLogger -import pytorch_lightning as pl -from typing import List -import utils.callbacks -import importlib -import os - - -def init_lit_model(hparams: dict) -> pl.LightningModule: - """Load LitModel from folder specified in run config.""" - - module_path = "models." + hparams["model_folder"] + ".lightning_module" - lit_model = importlib.import_module(module_path).LitModel(hparams=hparams) - - return lit_model - - -def init_data_module(hparams: dict) -> pl.LightningDataModule: - """Load DataModule from folder specified in run config.""" - - module_path = "data_modules." + hparams["datamodule_folder"] + ".datamodule" - hparams["data_dir"] = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data") - datamodule = importlib.import_module(module_path).DataModule(hparams=hparams) - datamodule.prepare_data() - datamodule.setup() - - return datamodule - - -def init_trainer(project_config: dict, run_config: dict, logger, callbacks: list) -> pl.Trainer: - """Initialize PyTorch Lightning Trainer""" - - # Get path to checkpoint you want to resume with if it was set in the run config - resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None) - - trainer = pl.Trainer( - # whether to use gpu and how many - gpus=project_config["num_of_gpus"], - - # experiment logging - logger=logger, - - # useful callbacks - callbacks=callbacks, - - # resume training from checkpoint if it was set in the run config - resume_from_checkpoint=resume_from_checkpoint - if resume_from_checkpoint != "None" - and resume_from_checkpoint != "False" - and resume_from_checkpoint is not False - else None, - - # print related - progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"], - profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None, - weights_summary=project_config["printing"]["weights_summary"], - - # number of validation sanity checks - num_sanity_val_steps=3, - - # default log dir if no logger is found - default_root_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs/lightning_logs"), - - # insert all other trainer parameters specified in run config - **run_config["trainer"] - ) - - return trainer - - -def init_callbacks(project_config: dict, run_config: dict, use_wandb: bool) -> List[pl.Callback]: - """Initialize default callbacks ana callbacks specified in run config.""" - - callbacks = [ - ModelCheckpoint( - monitor=project_config["callbacks"]["checkpoint"]["monitor"], - save_top_k=project_config["callbacks"]["checkpoint"]["save_top_k"], - mode=project_config["callbacks"]["checkpoint"]["mode"], - save_last=project_config["callbacks"]["checkpoint"]["save_last"], - ), - EarlyStopping( - monitor=project_config["callbacks"]["early_stop"]["monitor"], - patience=project_config["callbacks"]["early_stop"]["patience"], - mode=project_config["callbacks"]["early_stop"]["mode"], - ) - ] - if use_wandb: - callbacks.append( - utils.callbacks.SaveCodeToWandbCallback( - base_dir=os.path.dirname(os.path.dirname(__file__)), - wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"), - run_config=run_config - ) - ) - - callbacks_config = run_config.get("callbacks", {}) - for conf in callbacks_config: - callback = getattr(utils.callbacks, conf) - callbacks.append(callback(**callbacks_config[conf])) - - return callbacks - - -def init_wandb_logger(project_config: dict, - run_config: dict, - lit_model: pl.LightningModule, - datamodule: pl.LightningDataModule, - log_path: str = "logs/") -> pl.loggers.WandbLogger: - """Initialize Weights&Biases logger.""" - - # 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 - os.environ["WANDB_RESUME"] = "must" - - resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None) - wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None) - - wandb_logger = WandbLogger( - project=project_config["loggers"]["wandb"]["project"], - entity=project_config["loggers"]["wandb"]["entity"], - log_model=project_config["loggers"]["wandb"]["log_model"], - offline=project_config["loggers"]["wandb"]["offline"], - - group=run_config.get("wandb", {}).get("group", None), - job_type=run_config.get("wandb", {}).get("job_type", "train"), - tags=run_config.get("wandb", {}).get("tags", []), - notes=run_config.get("wandb", {}).get("notes", ""), - - # resume run only if ckpt was set in the run config - id=wandb_run_id - if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None - and resume_from_checkpoint is not False and wandb_run_id is not False - else None, - - save_dir=log_path, - save_code=False - ) - - if not os.path.exists(log_path): - os.makedirs(log_path) - - if hasattr(lit_model, 'model'): - wandb_logger.watch(lit_model.model, log=None) - else: - wandb_logger.watch(lit_model, log=None) - - wandb_logger.log_hyperparams({ - "model": lit_model.model.__class__.__name__, - "optimizer": lit_model.configure_optimizers().__class__.__name__, - "train_size": len(datamodule.data_train) - if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, - "val_size": len(datamodule.data_val) - if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0, - "test_size": len(datamodule.data_test) - if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0, - }) - wandb_logger.log_hyperparams(run_config["trainer"]) - wandb_logger.log_hyperparams(run_config["model"]) - wandb_logger.log_hyperparams(run_config["dataset"]) - - return wandb_logger - - -def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: - """TODO""" - return None From f46f380261af628c333a8461862954091a558991 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 12 Dec 2020 14:27:08 +0100 Subject: [PATCH 2/6] update progress --- .../mnist_datamodule/datamodule.py | 35 ++- .../lightning_module.py | 2 +- project/project_config.yaml | 40 ++-- project/run_configs.yaml | 114 +++++----- project/template_utils/callbacks.py | 200 ------------------ project/template_utils/initializers.py | 29 +-- project/template_utils/wandb_callbacks.py | 163 ++++++++++++++ project/train.py | 27 ++- requirements.txt | 1 + 9 files changed, 291 insertions(+), 320 deletions(-) create mode 100644 project/template_utils/wandb_callbacks.py diff --git a/project/datamodules/mnist_datamodule/datamodule.py b/project/datamodules/mnist_datamodule/datamodule.py index ddd57db..25e35b4 100644 --- a/project/datamodules/mnist_datamodule/datamodule.py +++ b/project/datamodules/mnist_datamodule/datamodule.py @@ -1,4 +1,4 @@ -from torch.utils.data import DataLoader, random_split +from torch.utils.data import DataLoader, ConcatDataset, random_split from pytorch_lightning import LightningDataModule from torchvision.transforms import transforms from torchvision.datasets import MNIST @@ -6,24 +6,19 @@ from torchvision.datasets import MNIST class MNISTDataModule(LightningDataModule): """ - This is example of datamodule for MNIST digits dataset. - All data modules should be located in separate folders with file named 'datamodule.py' containing class which - is always called 'DataModule'! + This is example of datamodule for MNIST dataset. - The folder name of datamodule used during training should be specified in run config and all parameters from - 'dataset' section will be passed in 'hparams' dictionary. + The path to datamodule should be specified in your run config. (run_configs.yaml) + The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml) - All datamodules should have a structure like this one! """ - def __init__(self, hparams): + def __init__(self, data_dir: str, hparams: dict): super().__init__() - # hparams["data_dir"] is always automatically set to 'data_path' from 'project_config.yaml' - self.data_dir = hparams["data_dir"] + self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml self.batch_size = hparams.get("batch_size") or 64 - self.train_val_split_ratio = hparams.get("train_val_split_ratio") or 0.9 - self.train_val_split = hparams.get("train_val_split") or None + self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000] self.num_workers = hparams.get("num_workers") or 1 self.pin_memory = hparams.get("pin_memory") or False @@ -41,23 +36,19 @@ class MNISTDataModule(LightningDataModule): def setup(self, stage=None): """Load data. Set variables: self.data_train, self.data_val, self.data_test.""" trainset = MNIST(self.data_dir, train=True, transform=self.transforms) + testset = MNIST(self.data_dir, train=False, transform=self.transforms) + dataset = ConcatDataset(datasets=[trainset, testset]) - if not self.train_val_split: - train_length = int(len(trainset) * self.train_val_split_ratio) - val_length = len(trainset) - train_length - self.train_val_split = [train_length, val_length] - - self.data_train, self.data_val = random_split(trainset, self.train_val_split) - self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms) + self.data_train, self.data_val, self.data_test = random_split(dataset, self.train_val_test_split) def train_dataloader(self): - return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers, + return DataLoader(dataset=self.data_train, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=self.pin_memory, shuffle=True) def val_dataloader(self): - return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers, + return DataLoader(dataset=self.data_val, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=self.pin_memory) def test_dataloader(self): - return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers, + return DataLoader(dataset=self.data_test, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=self.pin_memory) diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index 7777390..0c75428 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -78,4 +78,4 @@ class LitModel(pl.LightningModule): return loss def configure_optimizers(self): - return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay) + return torch.optim.Adam(self.parameters(), lr=self.hparams["lr"], weight_decay=self.hparams["weight_decay"]) diff --git a/project/project_config.yaml b/project/project_config.yaml index c6a2dd1..f099dc2 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -4,42 +4,40 @@ num_of_gpus: 0 # Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) loggers: - wandb: + Weights&Biases_config: project: "project_template_test" - entity: "kino" - log_model: True - offline: False + entity: "kino" # change to your username or name of your team on wandb + log_model: True # set True to automatically upload model checkpoint to wandb cloud after training + offline: False # set True to store all logs only locally # default callbacks initialised on every run/experiment # you can just remove this section or certain callback if you don't want tu use it -# you can add here any callback class available in pytorch lightning or template_utils/callbacks.py +# you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py +# if you specify the same callback class also in run config then it will overwrite the one set here +# all of the callback parameters will be passed to it on initialization default_callbacks: - checkpoint: - callback_class: "ModelCheckpoint" - args: - monitor: "val_acc" - save_top_k: 1 - save_last: True - mode: "max" - early_stop: - callback_class: "EarlyStopping" - args: - monitor: "val_acc" - patience: 100 - mode: "max" + EarlyStopping: # name of PyTorch Lightning class for early stopping callback + monitor: "val_acc", + patience: 5, + mode: "max", + ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback + monitor: "val_acc", + save_top_k: 1, + save_last: True, + mode: "max", # configure things which are printed in terminal printing: progress_bar_refresh_rate: 10 # refresh every 10 batches - weights_summary: "top" # model summary (alternatively "full") + weights_summary: "top" # print model summary (alternatively "full") profiler: False # set True to print execution time profiling after training ends # path to data folder (either absolute or relative to placement of 'train.py' file) -data_path: "data/" +data_dir: "data/" # path to logs folder (either absolute or relative to placement of 'train.py' file) -logs_path: "logs/" +logs_dir: "logs/" diff --git a/project/run_configs.yaml b/project/run_configs.yaml index 70211c6..96a1315 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -1,42 +1,10 @@ -# make sure parameters from different sections have different names -# or they will overwrite themselvess in Weights&Biases config -EXAMPLE_MNIST_RUN_CONFIG: +# execute this run like this: +# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST +SIMPLE_CONFIG_EXAMPLE_MNIST: + seed: 1234 trainer: - max_epochs: 10 - gradient_clip_val: 0.5 - model: - load_from: - model_path: "models/simple_mnist_classifier/lightning_module.py" - model_class: "LitModel" - hparams: - lr: 0.001 - weight_decay: 1e-5 - input_size: 784 # img size is 1*28*28 - output_size: 10 # there are 10 digit classes - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 - datamodule: - load_from: - datamodule_path: "datamodules/mnist_datamodule/datamodule.py" - datamodule_class: "MNISTDataModule" - hparams: - batch_size: 64 - train_val_split: [50_000, 10_000] - - - -EXAMPLE_MNIST_RUN_CONFIG_ADVANCED: - trainer: - min_epochs: 1 - max_epochs: 10 - gradient_clip_val: 0.5 - accumulate_grad_batches: 2 - fast_dev_run: False - limit_train_batches: 1.0 - limit_val_batches: 1.0 - limit_test_batches: 1.0 - val_check_interval: 1.0 + args: + max_epochs: 10 model: load_from: model_path: "models/simple_mnist_classifier/lightning_module.py" @@ -54,22 +22,64 @@ EXAMPLE_MNIST_RUN_CONFIG_ADVANCED: datamodule_path: "datamodules/mnist_datamodule/datamodule.py" datamodule_class: "MNISTDataModule" hparams: + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] + + +# execute this run like this: +# python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST +ADVANCED_CONFIG_EXAMPLE_MNIST: + seed: 1234 + trainer: + args: + min_epochs: 1 # train for at least this many epochs (denies early stopping) + max_epochs: 10 + gradient_clip_val: 0.5 # gradient clipping (helps with exploding gradient issues) + accumulate_grad_batches: 2 # perform optimization step after accumulating gradient from 2 batches + fast_dev_run: False # execute 1 training, 1 validation and 1 test epoch only + limit_train_batches: 0.8 # train only on 80% of training data + limit_val_batches: 1.0 # validate on 100% of validation data + limit_test_batches: 1.0 # test on 100% of test data + val_check_interval: 2 # perform validation every 2 epochs + model: + load_from: + model_path: "models/simple_mnist_classifier/lightning_module.py" + model_class: "LitModel" + hparams: # you can add here any parameters you want and then read them in model! + lr: 0.001 + weight_decay: 1e-5 + input_size: 784 # img size is 1*28*28 + output_size: 10 # there are 10 digit classes + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + datamodule: + load_from: + datamodule_path: "datamodules/mnist_datamodule/datamodule.py" + datamodule_class: "MNISTDataModule" + hparams: # you can add here any parameters you want and then read them in datamodule! batch_size: 256 - train_val_split: [60_000, 10_000] # use either this or 'train_val_split_ratio' - # train_val_split_ratio: 0.9 - num_workers: 1 - pin_memory: False - callbacks: - early_stop: - callback_class: "EarlyStopping" - args: - monitor: "val_acc" - patience: 5 - mode: "max" - wandb: + train_val_test_split: [55_000, 5_000, 10_000] + num_workers: 1 # num of processes used for loading data in parallel + pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them + # the following sections of config are optional and can be removed: + wandb: # Weights&Biases run options group: "" + job_type: "train" tags: ["v2", "uwu"] notes: "This is example run." + callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py + EarlyStopping: # name of PyTorch Lightning class for early stopping callback + monitor: "val_acc", + patience: 5, + mode: "max", + ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback + monitor: "val_acc", + save_top_k: 1, + save_last: True, + mode: "max", + ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py + class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] resume_training: - checkpoint_path: None - wandb_run_id: None + checkpoint_path: None # path to your checkpoint + wandb_run_id: None # you can add id of wandb run you want to resume but it's optional diff --git a/project/template_utils/callbacks.py b/project/template_utils/callbacks.py index 60d1ce1..31785a2 100644 --- a/project/template_utils/callbacks.py +++ b/project/template_utils/callbacks.py @@ -1,10 +1,4 @@ -from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from pytorch_lightning import Callback -import pytorch_lightning.callbacks -from shutil import copy -import torch -import wandb -import os class ExampleCallback(Callback): @@ -21,56 +15,6 @@ class ExampleCallback(Callback): print('Do something when training ends.') -class SaveOnnxModelToWandbCallback(Callback): - """ - Save model in .onnx format and upload to wandb. - Might crash since not all models are compatible with onnx. - """ - 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 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) - - -class ImagePredictionLoggerCallback(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 UnfreezeModelCallback(Callback): """ Unfreeze model after a few epochs. @@ -82,147 +26,3 @@ class UnfreezeModelCallback(Callback): if trainer.current_epoch == self.wait_epochs: for param in pl_module.model.model.parameters(): param.requires_grad = True - - -class MetricsHeatmapLoggerCallback(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! - """ - def __init__(self, class_names): - self.class_names = class_names - self.preds = [] - self.targets = [] - self.ready = False - - 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: - preds, targets = outputs - self.preds.append(preds) - self.targets.append(targets) - - def on_validation_epoch_end(self, trainer, pl_module): - """Generate f1, precision and recall heatmap.""" - if self.ready: - self.preds = torch.cat(self.preds) - self.targets = torch.cat(self.targets) - f1 = f1_score(self.preds, self.targets, average=None) - r = recall_score(self.preds, self.targets, average=None) - p = precision_score(self.preds, self.targets, average=None) - - trainer.logger.experiment.log({ - f"f1_p_r_heatmap_{trainer.current_epoch}": wandb.plots.HeatMap( - x_labels=self.class_names, - y_labels=["f1", "precision", "recall"], - matrix_values=[f1, p, r], - show_text=True, - )}, commit=False) - - self.preds = [] - self.targets = [] - - -class ConfusionMatrixLoggerCallback(Callback): - """ - 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 - self.preds = [] - self.targets = [] - self.ready = False - - 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: - preds, targets = outputs - self.preds.append(preds) - self.targets.append(targets) - - def on_validation_epoch_end(self, trainer, pl_module): - """Generate f1, precision and recall heatmap.""" - if self.ready: - self.preds = torch.cat(self.preds).tolist() - self.targets = torch.cat(self.targets).tolist() - - trainer.logger.experiment.log({ - f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix( - self.preds, - self.targets, - class_names=self.class_names) - }, commit=False) - - self.preds = [] - self.targets = [] - - -class SaveCodeToWandbCallback(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"]["model_folder"] - self.datamodule_folder = run_config["dataset"]["datamodule_folder"] - self.additional_files_to_be_saved = [ # paths should be relative to base_dir - "template_utils/callbacks.py", - "template_utils/initializers.py", - "train.py", - "project_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 - for file in self.additional_files_to_be_saved: - src_path = os.path.join(self.base_dir, file) - dst_path = os.path.join(self.wandb_save_dir, "code", file) - - path, filename = os.path.split(dst_path) - if not os.path.exists(path): - os.makedirs(path) - - copy(src_path, dst_path) - wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate - - # upload model files - for filename in os.listdir(os.path.join(self.base_dir, "models", self.model_folder)): - - if filename.endswith('.py'): - src_path = os.path.join(self.base_dir, "models", self.model_folder, filename) - dst_path = os.path.join(self.wandb_save_dir, "code", "models", self.model_folder, filename) - - path, filename = os.path.split(dst_path) - if not os.path.exists(path): - os.makedirs(path) - - copy(src_path, dst_path) - wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate - - # upload datamodule files - for filename in os.listdir(os.path.join(self.base_dir, "datamodules", self.datamodule_folder)): - - if filename.endswith('.py'): - src_path = os.path.join(self.base_dir, "datamodules", self.datamodule_folder, filename) - dst_path = os.path.join(self.wandb_save_dir, "code", "datamodules", self.datamodule_folder, filename) - - path, filename = os.path.split(dst_path) - if not os.path.exists(path): - os.makedirs(path) - - copy(src_path, dst_path) - wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index fbfd545..c9cd76d 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -42,7 +42,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule: return model -def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> pl.LightningDataModule: +def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl.LightningDataModule: """ Load LightningDataModule from path specified in run config. """ @@ -54,10 +54,8 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p datamodule_path = os.path.join(base_dir, datamodule_path) assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}" - if not os.path.isabs(data_path): - datamodule_config["hparams"]["data_dir"] = os.path.join(base_dir, data_path) - else: - datamodule_config["hparams"]["data_dir"] = data_path + if not os.path.isabs(data_dir): + data_dir = os.path.join(base_dir, data_dir) spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path) lightning_module = importlib.util.module_from_spec(spec) @@ -71,7 +69,7 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p assert issubclass(DataModule, pl.LightningDataModule), \ f"specified datamodule class {datamodule_class} is not a LightningDataModule" - datamodule = DataModule(hparams=datamodule_config["hparams"]) + datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"]) datamodule.prepare_data() datamodule.setup() @@ -81,7 +79,8 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p def init_trainer(project_config: dict, run_config: dict, callbacks: List[pl.Callback], - loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer: + loggers: List[pl.loggers.LightningLoggerBase], + base_dir: str) -> pl.Trainer: """ Initialize PyTorch Lightning Trainer. """ @@ -115,10 +114,10 @@ def init_trainer(project_config: dict, num_sanity_val_steps=3, # default log dir if no logger is found - default_root_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs/lightning_logs"), + default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"), - # insert all other trainer parameters specified in run config - **run_config["trainer"] + # insert all other trainer args specified in run config + **run_config["trainer"]["args"] ) return trainer @@ -132,8 +131,10 @@ def init_callbacks(project_config: dict, Initialize default callbacks and callbacks specified in run config. """ - default_callbacks = project_config["default_callbacks"] - run_callbacks = run_config["callbacks"] + default_callbacks = project_config.get("default_callbacks", {}) + run_callbacks = run_config.get("callbacks", {}) + + print(default_callbacks) callbacks = [] @@ -159,7 +160,7 @@ def init_callbacks(project_config: dict, def init_loggers(project_config: dict, run_config: dict, - lit_model: pl.LightningModule, + model: pl.LightningModule, datamodule: pl.LightningDataModule, use_wandb: bool, base_dir: str) -> List[pl.loggers.LightningLoggerBase]: @@ -212,11 +213,11 @@ def init_wandb_logger(project_config: dict, if hasattr(lit_model, 'model'): wandb_logger.watch(lit_model.model, log=None) + wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__}) else: wandb_logger.watch(lit_model, log=None) wandb_logger.log_hyperparams({ - "model": lit_model.model.__class__.__name__ if hasattr(lit_model, 'model') else None, "optimizer": lit_model.configure_optimizers().__class__.__name__, "train_size": len(datamodule.data_train) if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, diff --git a/project/template_utils/wandb_callbacks.py b/project/template_utils/wandb_callbacks.py new file mode 100644 index 0000000..ab23ee7 --- /dev/null +++ b/project/template_utils/wandb_callbacks.py @@ -0,0 +1,163 @@ +from sklearn.metrics import precision_score, recall_score, f1_score +from pytorch_lightning import Callback +from shutil import copy +import torch +import wandb +import os + + +class SaveOnnxModelToWandbCallback(Callback): + """ + Save model in .onnx format and upload to wandb. + Might crash since not all models are compatible with onnx. + """ + 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 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) + + +class ImagePredictionLoggerCallback(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 MetricsHeatmapLoggerCallback(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! + """ + def __init__(self, class_names): + self.class_names = class_names + self.preds = [] + self.targets = [] + self.ready = False + + 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: + preds, targets = outputs + self.preds.append(preds) + self.targets.append(targets) + + def on_validation_epoch_end(self, trainer, pl_module): + """Generate f1, precision and recall heatmap.""" + if self.ready: + self.preds = torch.cat(self.preds) + self.targets = torch.cat(self.targets) + f1 = f1_score(self.preds, self.targets, average=None) + r = recall_score(self.preds, self.targets, average=None) + p = precision_score(self.preds, self.targets, average=None) + + trainer.logger.experiment.log({ + f"f1_p_r_heatmap_{trainer.current_epoch}_{trainer.logger.id}": wandb.plots.HeatMap( + x_labels=self.class_names, + y_labels=["f1", "precision", "recall"], + matrix_values=[f1, p, r], + show_text=True, + )}, commit=False) + + self.preds = [] + self.targets = [] + + +class ConfusionMatrixLoggerCallback(Callback): + """ + 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 + self.preds = [] + self.targets = [] + self.ready = False + + 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: + preds, targets = outputs + self.preds.append(preds) + self.targets.append(targets) + + def on_validation_epoch_end(self, trainer, pl_module): + """Generate f1, precision and recall heatmap.""" + if self.ready: + self.preds = torch.cat(self.preds).tolist() + self.targets = torch.cat(self.targets).tolist() + + trainer.logger.experiment.log({ + f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix( + self.preds, + self.targets, + class_names=self.class_names) + }, commit=False) + + self.preds = [] + self.targets = [] + + +class SaveCodeToWandbCallback(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"]["model_folder"] + self.datamodule_folder = run_config["dataset"]["datamodule_folder"] + self.additional_files_to_be_saved = [ # paths should be relative to base_dir + "template_utils/callbacks.py", + "template_utils/initializers.py", + "train.py", + "project_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 diff --git a/project/train.py b/project/train.py index af16b92..4575ec3 100644 --- a/project/train.py +++ b/project/train.py @@ -1,4 +1,5 @@ # pytorch lightning imports +import torch from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback from pytorch_lightning.loggers import LightningLoggerBase @@ -18,13 +19,18 @@ from template_utils.initializers import ( ) -# Everything will be loaded relatively to placement of this file! +# Everything will be loaded relatively to placement of 'train.py' file! BASE_DIR: str = os.path.dirname(__file__) def train(project_config: dict, run_config: dict, use_wandb: bool): + + # Set global PyTorch seed + if "seed" in run_config: + torch.manual_seed(run_config["seed"]) + # Init PyTorch Lightning model ⚡ - lit_model: LightningModule = init_model( + model: LightningModule = init_model( model_config=run_config["model"], base_dir=BASE_DIR ) @@ -32,7 +38,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): # Init PyTorch Lightning datamodule ⚡ datamodule: LightningDataModule = init_datamodule( datamodule_config=run_config["datamodule"], - data_path=project_config["data_path"], + data_dir=project_config["data_dir"], base_dir=BASE_DIR ) @@ -48,7 +54,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): loggers: List[LightningLoggerBase] = init_loggers( project_config=project_config, run_config=run_config, - lit_model=lit_model, + model=model, datamodule=datamodule, use_wandb=use_wandb, base_dir=BASE_DIR @@ -59,17 +65,18 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): project_config=project_config, run_config=run_config, callbacks=callbacks, - loggers=loggers + loggers=loggers, + base_dir=BASE_DIR ) # Evaluate model on test set before training - # trainer.test(model=lit_model, datamodule=datamodule) + # trainer.test(model=model, datamodule=datamodule) # Train the model - trainer.fit(model=lit_model, datamodule=datamodule) + trainer.fit(model=model, datamodule=datamodule) # Evaluate model on test set after training - # trainer.test() + trainer.test() def load_config(path): @@ -90,11 +97,11 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str, if __name__ == "__main__": parser = ArgumentParser() - parser.set_defaults(use_wandb=True) parser.add_argument("--project_config_path", type=str, default="project_config.yaml") parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") - parser.add_argument("--run_config_name", type=str, default="EXAMPLE_MNIST_RUN_CONFIG") + parser.add_argument("--run_config_name", type=str, default="SIMPLE_CONFIG_EXAMPLE_MNIST") parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') + parser.set_defaults(use_wandb=True) args = parser.parse_args() main(project_config_path=args.project_config_path, diff --git a/requirements.txt b/requirements.txt index 50d2d73..aa3d615 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,3 +5,4 @@ pytorch-lightning>=1.0.8 wandb>=0.10.12 PyYAML>=5.3.1 scikit-learn>=0.23.2 +pandas>=1.1.5 From 757f0fc25ac329fbfda407d09f19752e2f2295a2 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 12 Dec 2020 22:05:48 +0100 Subject: [PATCH 3/6] everything except callbacks works --- README.md | 106 +++++++------- .../datamodules/mnist_datamodule/datasets.py | 7 +- .../lightning_module.py | 14 +- project/project_config.yaml | 23 +-- project/run_configs.yaml | 22 +-- project/template_utils/initializers.py | 135 +++++++++++------- project/train.py | 30 ++-- 7 files changed, 189 insertions(+), 148 deletions(-) diff --git a/README.md b/README.md index fcf461e..5b0eb6f 100644 --- a/README.md +++ b/README.md @@ -38,16 +38,16 @@ The directory structure of new project looks like this: │ │ │ ├── data_modules <- All your data modules should be located here! │ │ ├── example_datamodule <- Each datamodule should be located in separate folder! -│ │ │ ├── datamodule.py <- Contains 'DataModule' class -│ │ │ ├── datasets.py <- Contains pytorch 'Dataset' classes (optional file) -│ │ │ └── transforms.py <- Contains data transformations (optional file) +│ │ │ ├── datamodule.py <- Contains class of type 'LightningDataModule' +│ │ │ ├── datasets.py <- Optional file +│ │ │ └── transforms.py <- Optional file │ │ ├── ... │ │ └── ... │ │ │ ├── models <- All your models should be located here! │ │ ├── example_model <- Each model should be located in separate folder! -│ │ │ ├── lightning_module.py <- Contains 'LitModel' class with train/val/test step methods -│ │ │ └── models.py <- Model architectures used by lightning_module.py (optional file) +│ │ │ ├── lightning_module.py <- Contains class of type 'LightningModule' +│ │ │ └── models.py <- Model architectures used by 'LightningModule' │ │ ├── ... │ │ └── ... │ │ @@ -68,23 +68,24 @@ The directory structure of new project looks like this: ## Project config parameters ([project_config.yaml](project/project_config.yaml)) Example project configuration: ```yaml -num_of_gpus: -1 <- '-1' to use all gpus available, '0' to train on cpu +num_of_gpus: -1 <- '-1' to train on all GPUs available, '0' to train on CPU loggers: wandb: project: "project_name" <- wandb project name entity: "some_name" <- wandb entity name log_model: True <- set True if you want to upload ckpts to wandb automatically + log_gradients: False <- set True to log gradient histograms offline: False <- set True if you want to store all data locally -callbacks: - checkpoint: - monitor: "val_acc" <- name of the logged metric that determines when model is improving +default_callbacks: + ModelCheckpoint: + monitor: "val_acc" <- name of the logged metric which determines when model is improving save_top_k: 1 <- save k best models (determined by above metric) save_last: True <- additionaly always save model from last epoch mode: "max" <- can be "max" or "min" - early_stop: - monitor: "val_acc" <- name of the logged metric that determines when model is improving + EarlyStopping: + 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 mode: "max" <- can be "max" or "min" @@ -100,55 +101,52 @@ printing: You can store many run configurations in this file.
Example run configuration: ```yaml -MNIST_CLASSIFIER_V1: - trainer: # these parameters will be passed directly to PyTorch Lightning 'Trainer' object - max_epochs: 5 - gradient_clip_val: 0.5 - accumulate_grad_batches: 1 - limit_train_batches: 1.0 - model: # these parameters will be passed to 'LightningModule' object as 'hparams' dictionary - model_folder: "simple_mnist_classifier" - lr: 0.001 - weight_decay: 0.000001 - input_size: 784 - output_size: 10 - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 - dataset: # these parameters will be passed to 'LightningDataModule' object as 'hparams' dictionary - datamodule_folder: "mnist_datamodule" - batch_size: 256 - train_val_split_ratio: 0.9 - num_workers: 1 - pin_memory: False - callbacks: - ConfusionMatrixLoggerCallback: - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - wandb: - group: "" - tags: ["v1", "uwu"] - resume_training: - checkpoint_path: "path_to_checkpoint/last.ckpt" - wandb_run_id: None +SIMPLE_CONFIG_EXAMPLE_MNIST: + seed: 1234 + trainer: + args: + max_epochs: 10 + model: + load_from: + model_path: "models/simple_mnist_classifier/lightning_module.py" + model_class: "LitModel" + hparams: + lr: 0.001 + weight_decay: 0.00001 + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + datamodule: + load_from: + datamodule_path: "datamodules/mnist_datamodule/datamodule.py" + datamodule_class: "MNISTDataModule" + hparams: + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] ``` -Each run configuration needs to contain sections `trainer`, `model` and `dataset`. Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.
+To start training with this configuration run: `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` -Section `model` always needs to contain `model_folder` parameter (name of the folder from which `lightning_module.py` will be loaded, which should contain `LitModel` class).
-Section `dataset` always needs to contain `datamodule_folder` parameter (name of the folder from which `datamodule.py` will be loaded, which should contain `DataModule` class).
+Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
+Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.
-Every parameter in `model` section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).
-Every parameter in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).
+Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).
+Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).

## Workflow -1. Add your model to `project/models` folder. You need to create folder with `lightning_module.py` file containing `LitModel` class -2. Add your datamodule to `project/data_modules` folder. You need to create folder with `datamodule.py` file containing `DataModule` class -3. Create new run config in [run_configs.yaml](project/run_configs.yaml) (specify there folders containing your model and datamodule) -3. Configure [project_config.yaml](project/project_config.yaml) +1. Create model in PyTorch Lightning +2. Create datamodule in PyTorch Lightning +3. Create new run config in [run_configs.yaml](project/run_configs.yaml) + - specify path to your model class + - specify path to your datamodule class + - you can add there and hyperparametrs you want! +3. Configure your project in [project_config.yaml](project/project_config.yaml) 4. Run training with chosen run config
```bash - python train.py --run_config MNIST_CLASSIFIER_V1 + python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST ```

@@ -192,7 +190,7 @@ Next, you can train model without logging # train model without Weights&Biases # choose run config from project/run_configs.yaml cd project -python train.py --no_wandb --run_config MNIST_CLASSIFIER_V1 +python train.py --no_wandb --run_config SIMPLE_CONFIG_EXAMPLE_MNIST ``` Or you can train model with Weights&Biases logging @@ -207,10 +205,10 @@ loggers: # train model with Weights&Biases # choose run config from project/run_configs.yaml cd project -python train.py --run_config MNIST_CLASSIFIER_V1 +python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST ``` -Optionally you can install project as package with [setup.py](setup.py) +Optionally you can install project as a package with [setup.py](setup.py) ```bash pip install -e . ``` diff --git a/project/datamodules/mnist_datamodule/datasets.py b/project/datamodules/mnist_datamodule/datasets.py index e64627e..2a97b97 100644 --- a/project/datamodules/mnist_datamodule/datasets.py +++ b/project/datamodules/mnist_datamodule/datasets.py @@ -5,8 +5,8 @@ import os class TestDataset(Dataset): """ - Example dataset class for loading images from folder. - 'Dataset' classes can be used by 'DataModule' class. + Example dataset class for loading images from folder. + 'Dataset' classes can be used by 'DataModule' class. """ def __init__(self, img_dir, transform): @@ -14,7 +14,8 @@ class TestDataset(Dataset): self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)] def __getitem__(self, idx): - image = Image.open(self.images[idx]).convert("RGB") + image = Image.open(self.images[idx]).convert("L") # convert to black and white + # image = Image.open(self.images[idx]).convert("RGB") if self.transform is not None: image = self.transform(image) diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index 0c75428..9bcf4c0 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -9,18 +9,16 @@ from models.simple_mnist_classifier.models import * class LitModel(pl.LightningModule): """ - This is example of lightning model for MNIST digits classification. - All models should be located in separate folders with file named 'lightning_module.py' containing class which - is always called 'LitModel'! + This is example of lightning model for MNIST digits classification. - The folder name of model used during training should be specified in run config and all parameters from - 'model' section will be passed in 'hparams' dictionary. + The path to model should be specified in your run config. (run_configs.yaml) + The 'hparams' dict contains your hparams specified in run 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. + 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. """ - def __init__(self, hparams=None): + def __init__(self, hparams: dict = None): super().__init__() if hparams: diff --git a/project/project_config.yaml b/project/project_config.yaml index f099dc2..4869a9c 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -4,11 +4,12 @@ num_of_gpus: 0 # Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) loggers: - Weights&Biases_config: + wandb: project: "project_template_test" - entity: "kino" # change to your username or name of your team on wandb - log_model: True # set True to automatically upload model checkpoint to wandb cloud after training - offline: False # set True to store all logs only locally + entity: "kino" # change to your username or name of your team on wandb + log_model: True # set True to automatically upload model checkpoint to wandb cloud after training + log_gradients: False # set True to log gradient histograms (avoid this for very big models) + offline: False # set True to store all logs only locally # default callbacks initialised on every run/experiment @@ -18,14 +19,14 @@ loggers: # all of the callback parameters will be passed to it on initialization default_callbacks: EarlyStopping: # name of PyTorch Lightning class for early stopping callback - monitor: "val_acc", - patience: 5, - mode: "max", + monitor: "val_acc" + patience: 5 + mode: "max" ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback - monitor: "val_acc", - save_top_k: 1, - save_last: True, - mode: "max", + monitor: "val_acc" + save_top_k: 1 + save_last: True + mode: "max" # configure things which are printed in terminal diff --git a/project/run_configs.yaml b/project/run_configs.yaml index 96a1315..df21e19 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -1,4 +1,4 @@ -# execute this run like this: +# to execute this run: # python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST SIMPLE_CONFIG_EXAMPLE_MNIST: seed: 1234 @@ -11,7 +11,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: model_class: "LitModel" hparams: lr: 0.001 - weight_decay: 1e-5 + weight_decay: 0.00001 input_size: 784 output_size: 10 lin1_size: 256 @@ -26,7 +26,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: train_val_test_split: [55_000, 5_000, 10_000] -# execute this run like this: +# to execute this run: # python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST ADVANCED_CONFIG_EXAMPLE_MNIST: seed: 1234 @@ -47,7 +47,7 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: model_class: "LitModel" hparams: # you can add here any parameters you want and then read them in model! lr: 0.001 - weight_decay: 1e-5 + weight_decay: 0.00001 input_size: 784 # img size is 1*28*28 output_size: 10 # there are 10 digit classes lin1_size: 256 @@ -70,14 +70,14 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: notes: "This is example run." callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py EarlyStopping: # name of PyTorch Lightning class for early stopping callback - monitor: "val_acc", - patience: 5, - mode: "max", + monitor: "val_acc" + patience: 5 + mode: "max" ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback - monitor: "val_acc", - save_top_k: 1, - save_last: True, - mode: "max", + monitor: "val_acc" + save_top_k: 1 + save_last: True + mode: "max" ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] resume_training: diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index c9cd76d..5b3efff 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -4,15 +4,40 @@ from pytorch_lightning.profiler import SimpleProfiler import pytorch_lightning as pl # normal imports -from typing import List +from typing import List, Tuple import importlib.util import os # template utils imports -import template_utils.callbacks +from template_utils import callbacks as custom_callbacks +from template_utils import wandb_callbacks -def init_model(model_config: dict, base_dir: str) -> pl.LightningModule: +def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]: + """ + Convert all config paths to absolute paths relatively to base_dir and normalize them. + """ + + if not os.path.isabs(project_config["data_dir"]): + project_config["data_dir"] = \ + os.path.normpath(os.path.join(base_dir, project_config["data_dir"])) + + if not os.path.isabs(project_config["logs_dir"]): + project_config["logs_dir"] =\ + os.path.normpath(os.path.join(base_dir, project_config["logs_dir"])) + + if not os.path.isabs(run_config["model"]["load_from"]["model_path"]): + run_config["model"]["load_from"]["model_path"] = \ + os.path.normpath(os.path.join(base_dir, run_config["model"]["load_from"]["model_path"])) + + if not os.path.isabs(run_config["datamodule"]["load_from"]["datamodule_path"]): + run_config["datamodule"]["load_from"]["datamodule_path"] = \ + os.path.normpath(os.path.join(base_dir, run_config["datamodule"]["load_from"]["datamodule_path"])) + + return project_config, run_config + + +def init_model(model_config: dict) -> pl.LightningModule: """ Load LightningModule from path specified in run config. """ @@ -20,9 +45,6 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule: model_path = model_config["load_from"]["model_path"] model_class = model_config["load_from"]["model_class"] - if not os.path.isabs(model_path): - model_path = os.path.join(base_dir, model_path) - assert os.path.isfile(model_path), f"incorrect model path: {model_path}" spec = importlib.util.spec_from_file_location("lightning_model", model_path) @@ -42,7 +64,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule: return model -def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl.LightningDataModule: +def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule: """ Load LightningDataModule from path specified in run config. """ @@ -50,13 +72,8 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl datamodule_path = datamodule_config["load_from"]["datamodule_path"] datamodule_class = datamodule_config["load_from"]["datamodule_class"] - if not os.path.isabs(datamodule_path): - datamodule_path = os.path.join(base_dir, datamodule_path) assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}" - if not os.path.isabs(data_dir): - data_dir = os.path.join(base_dir, data_dir) - spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path) lightning_module = importlib.util.module_from_spec(spec) spec.loader.exec_module(lightning_module) @@ -79,8 +96,7 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl def init_trainer(project_config: dict, run_config: dict, callbacks: List[pl.Callback], - loggers: List[pl.loggers.LightningLoggerBase], - base_dir: str) -> pl.Trainer: + loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer: """ Initialize PyTorch Lightning Trainer. """ @@ -125,8 +141,7 @@ def init_trainer(project_config: dict, def init_callbacks(project_config: dict, run_config: dict, - use_wandb: bool, - base_dir: str) -> List[pl.Callback]: + use_wandb: bool) -> List[pl.Callback]: """ Initialize default callbacks and callbacks specified in run config. """ @@ -134,26 +149,26 @@ def init_callbacks(project_config: dict, default_callbacks = project_config.get("default_callbacks", {}) run_callbacks = run_config.get("callbacks", {}) - print(default_callbacks) + # print(default_callbacks) callbacks = [] - for callback_config in default_callbacks: - callback_class = getattr(pl.callbacks, callback_config["callback_class"]) - callbacks.append(callback_class(**callback_config["args"])) - - for callback_config in run_callbacks: - callback_class = getattr(pl.callbacks, callback_config["callback_class"]) - callbacks.append(callback_class(**callback_config["args"])) - - if use_wandb: - callbacks.append( - template_utils.callbacks.SaveCodeToWandbCallback( - base_dir=os.path.dirname(os.path.dirname(__file__)), - wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"), - run_config=run_config - ) - ) + # for callback_config in default_callbacks: + # callback_class = getattr(pl.callbacks, callback_config["callback_class"]) + # callbacks.append(callback_class(**callback_config["args"])) + # + # for callback_config in run_callbacks: + # callback_class = getattr(pl.callbacks, callback_config["callback_class"]) + # callbacks.append(callback_class(**callback_config["args"])) + # + # if use_wandb: + # callbacks.append( + # wandb_callbacks.SaveCodeToWandbCallback( + # base_dir=os.path.dirname(os.path.dirname(__file__)), + # wandb_save_dir=project_config["logs_dir"], + # run_config=run_config + # ) + # ) return callbacks @@ -162,24 +177,35 @@ def init_loggers(project_config: dict, run_config: dict, model: pl.LightningModule, datamodule: pl.LightningDataModule, - use_wandb: bool, - base_dir: str) -> List[pl.loggers.LightningLoggerBase]: + use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]: """ Initialize loggers. """ + loggers = [] + if use_wandb: + wandb_logger = init_wandb_logger( + project_config=project_config, + run_config=run_config, + model=model, + datamodule=datamodule + ) + if wandb_logger: + loggers.append(wandb_logger) - return [] + return loggers def init_wandb_logger(project_config: dict, run_config: dict, - lit_model: pl.LightningModule, - datamodule: pl.LightningDataModule, - log_path: str = "logs/") -> pl.loggers.WandbLogger: + model: pl.LightningModule, + datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger: """ Initialize Weights&Biases logger. """ + if "loggers" not in project_config or "wandb" not in project_config["loggers"]: + return None + # 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 os.environ["WANDB_RESUME"] = "must" @@ -204,21 +230,27 @@ def init_wandb_logger(project_config: dict, and resume_from_checkpoint is not False and wandb_run_id is not False else None, - save_dir=log_path, + save_dir=project_config["logs_dir"], save_code=False ) - if not os.path.exists(log_path): - os.makedirs(log_path) + if not os.path.exists(project_config["logs_dir"]): + os.makedirs(project_config["logs_dir"]) - if hasattr(lit_model, 'model'): - wandb_logger.watch(lit_model.model, log=None) - wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__}) + if hasattr(model, 'model'): + if project_config["loggers"]["wandb"]["log_gradients"]: + wandb_logger.watch(model.model, log='gradients') + else: + wandb_logger.watch(model.model, log=None) + wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__}) else: - wandb_logger.watch(lit_model, log=None) + if project_config["loggers"]["wandb"]["log_gradients"]: + wandb_logger.watch(model, log='gradients') + else: + wandb_logger.watch(model, log=None) wandb_logger.log_hyperparams({ - "optimizer": lit_model.configure_optimizers().__class__.__name__, + "optimizer": model.configure_optimizers().__class__.__name__, "train_size": len(datamodule.data_train) if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, "val_size": len(datamodule.data_val) @@ -226,9 +258,12 @@ def init_wandb_logger(project_config: dict, "test_size": len(datamodule.data_test) if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0, }) - wandb_logger.log_hyperparams(run_config["trainer"]) - wandb_logger.log_hyperparams(run_config["model"]) - wandb_logger.log_hyperparams(run_config["dataset"]) + wandb_logger.log_hyperparams(project_config["num_of_gpus"]) + wandb_logger.log_hyperparams(run_config["trainer"]["args"]) + wandb_logger.log_hyperparams(run_config["model"]["hparams"]) + wandb_logger.log_hyperparams(run_config["model"]["load_from"]) + wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"]) + wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"]) return wandb_logger diff --git a/project/train.py b/project/train.py index 4575ec3..fc6dee1 100644 --- a/project/train.py +++ b/project/train.py @@ -1,16 +1,18 @@ # pytorch lightning imports -import torch from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback from pytorch_lightning.loggers import LightningLoggerBase +import torch # normal imports from argparse import ArgumentParser from typing import List +import pprint import yaml import os # template utils imports from template_utils.initializers import ( + normalize_config_paths, init_model, init_datamodule, init_callbacks, @@ -29,25 +31,29 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): if "seed" in run_config: torch.manual_seed(run_config["seed"]) + # Covert paths to absolute and normalize them + project_config, run_config = normalize_config_paths( + project_config=project_config, + run_config=run_config, + base_dir=BASE_DIR + ) + # Init PyTorch Lightning model ⚡ model: LightningModule = init_model( - model_config=run_config["model"], - base_dir=BASE_DIR + model_config=run_config["model"] ) # Init PyTorch Lightning datamodule ⚡ datamodule: LightningDataModule = init_datamodule( datamodule_config=run_config["datamodule"], - data_dir=project_config["data_dir"], - base_dir=BASE_DIR + data_dir=project_config["data_dir"] ) # Init PyTorch Lightning callbacks ⚡ callbacks: List[Callback] = init_callbacks( project_config=project_config, run_config=run_config, - use_wandb=use_wandb, - base_dir=BASE_DIR + use_wandb=use_wandb ) # Init PyTorch Lightning loggers ⚡ @@ -56,8 +62,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): run_config=run_config, model=model, datamodule=datamodule, - use_wandb=use_wandb, - base_dir=BASE_DIR + use_wandb=use_wandb ) # Init PyTorch Lightning trainer ⚡ @@ -65,8 +70,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): project_config=project_config, run_config=run_config, callbacks=callbacks, - loggers=loggers, - base_dir=BASE_DIR + loggers=loggers ) # Evaluate model on test set before training @@ -91,6 +95,10 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str, project_config: dict = load_config(path=project_config_path) run_config: dict = load_config(path=run_configs_path)[run_config_name] + print("EXECUTING RUN:", run_config_name) + pprint.pprint(run_config, sort_dicts=False) + print() + # Train model train(project_config=project_config, run_config=run_config, use_wandb=use_wandb) From 23e9c4fecf2012371b7e49d05106e9e555e68d0a Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 12 Dec 2020 22:39:40 +0100 Subject: [PATCH 4/6] more comments and explanations --- README.md | 34 +++++++++++-------- .../mnist_datamodule/datamodule.py | 4 +-- .../datamodules/mnist_datamodule/datasets.py | 5 +-- .../mnist_datamodule/transforms.py | 3 ++ .../lightning_module.py | 4 +-- 5 files changed, 29 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 5b0eb6f..189978d 100644 --- a/README.md +++ b/README.md @@ -3,13 +3,14 @@ A convenient starting template for most deep learning projects. Built with Py Click on "Use this template" button above to initialize new repository.
## Features -- All advantages of PyTorch Lightning - Predefined folder structure - Storing project configuration in a convenient way ([project_config.yaml](project/project_config.yaml)) - Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml)) +- All advantages of PyTorch Lightning +- Weights&Biases integration: + - Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud + - Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py)) - Automates the whole training process and initialization, you only need to create `model` and `datamodule` and specify them in [run_configs.yaml](project/run_configs.yaml) -- Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud -- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py)) - Scheduling execution of many experiments ([execute_all_runs.py](project/template_utils/execute_all_runs.py)) - Built in requirements ([requirements.txt](requirements.txt)) - Built in conda environment initialization ([conda_env.yaml](conda_env.yaml)) @@ -36,16 +37,16 @@ The directory structure of new project looks like this: │ │ ├── init_utils.py <- Useful initializers │ │ └── predict_example.py <- Example of inference with trained model │ │ -│ ├── data_modules <- All your data modules should be located here! -│ │ ├── example_datamodule <- Each datamodule should be located in separate folder! +│ ├── datamodules <- All your datamodules should be located here! +│ │ ├── example_datamodule <- It's best to locate each datamodule in separate folder! │ │ │ ├── datamodule.py <- Contains class of type 'LightningDataModule' -│ │ │ ├── datasets.py <- Optional file -│ │ │ └── transforms.py <- Optional file +│ │ │ ├── transforms.py <- Some optional file +│ │ │ └── ... │ │ ├── ... │ │ └── ... │ │ │ ├── models <- All your models should be located here! -│ │ ├── example_model <- Each model should be located in separate folder! +│ │ ├── example_model <- It's best to locate each model in separate folder! │ │ │ ├── lightning_module.py <- Contains class of type 'LightningModule' │ │ │ └── models.py <- Model architectures used by 'LightningModule' │ │ ├── ... @@ -93,6 +94,9 @@ printing: progress_bar_refresh_rate: 5 <- refresh rate of training bar in terminal weights_summary: "top" <- print summary of model (alternatively "full") profiler: False <- set True if you want to see execution time profiling + +data_dir: "data/" <- path to data folder +logs_dir: "logs/" <- path to logs folder ```
@@ -129,20 +133,20 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: To start training with this configuration run: `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
-Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.
+Sections `seed`, `callbacks`, `wandb` and `resume_training` are optional and can be removed (see advanced config example in [run_configs.yaml](project/run_configs.yaml)).
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).
-Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).
+Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).

## Workflow -1. Create model in PyTorch Lightning -2. Create datamodule in PyTorch Lightning +1. Create PyTorch Lightning model +2. Create PyTorch Lightning datamodule 3. Create new run config in [run_configs.yaml](project/run_configs.yaml) - specify path to your model class - specify path to your datamodule class - - you can add there and hyperparametrs you want! + - you can add there and hyperparameters you want! 3. Configure your project in [project_config.yaml](project/project_config.yaml) 4. Run training with chosen run config
```bash @@ -166,8 +170,8 @@ Every parameter specified in datamodule hparams section will be passed to your d -## Description -What it does +## Description +What it does ## How to run First, install dependencies diff --git a/project/datamodules/mnist_datamodule/datamodule.py b/project/datamodules/mnist_datamodule/datamodule.py index 25e35b4..3470394 100644 --- a/project/datamodules/mnist_datamodule/datamodule.py +++ b/project/datamodules/mnist_datamodule/datamodule.py @@ -9,9 +9,9 @@ class MNISTDataModule(LightningDataModule): This is example of datamodule for MNIST dataset. The path to datamodule should be specified in your run config. (run_configs.yaml) - The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml) - + The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml) """ + def __init__(self, data_dir: str, hparams: dict): super().__init__() diff --git a/project/datamodules/mnist_datamodule/datasets.py b/project/datamodules/mnist_datamodule/datasets.py index 2a97b97..14076d6 100644 --- a/project/datamodules/mnist_datamodule/datasets.py +++ b/project/datamodules/mnist_datamodule/datasets.py @@ -5,8 +5,9 @@ import os class TestDataset(Dataset): """ - Example dataset class for loading images from folder. - 'Dataset' classes can be used by 'DataModule' class. + Example dataset class for loading images from folder and converting them to monochromatic. + Can be used to perform inference with trained MNIST model. + 'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by datamodules. """ def __init__(self, img_dir, transform): diff --git a/project/datamodules/mnist_datamodule/transforms.py b/project/datamodules/mnist_datamodule/transforms.py index ca1ff4c..7b22102 100644 --- a/project/datamodules/mnist_datamodule/transforms.py +++ b/project/datamodules/mnist_datamodule/transforms.py @@ -1,3 +1,6 @@ +""" +Example file containing data transformations which can be used by datamodule. +""" from torchvision import transforms diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index 9bcf4c0..7a981b2 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -3,7 +3,7 @@ import pytorch_lightning as pl import torch.nn.functional as F import torch -# custom models +# import custom models from models.simple_mnist_classifier.models import * @@ -12,7 +12,7 @@ class LitModel(pl.LightningModule): This is example of lightning model for MNIST digits classification. The path to model should be specified in your run config. (run_configs.yaml) - The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml) + The 'hparams' dict contains your hparams specified in run 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. From f75d2a83ef680969d4f9728faddf2d4d1870f8a6 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 13 Dec 2020 21:48:54 +0100 Subject: [PATCH 5/6] callbacks work --- README.md | 4 +- project/run_configs.yaml | 4 +- project/template_utils/initializers.py | 52 +++++++++++++++-------- project/template_utils/wandb_callbacks.py | 22 +++++++--- project/train.py | 5 ++- 5 files changed, 59 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 189978d..a431ba8 100644 --- a/README.md +++ b/README.md @@ -30,11 +30,11 @@ The directory structure of new project looks like this: │ │ │ ├── notebooks <- Jupyter notebooks │ │ -│ ├── utils <- Different utilities +│ ├── template_utils <- Different utilities │ │ ├── callbacks.py <- Useful training callbacks │ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps │ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other -│ │ ├── init_utils.py <- Useful initializers +│ │ ├── initializers.py <- Useful initializers │ │ └── predict_example.py <- Example of inference with trained model │ │ │ ├── datamodules <- All your datamodules should be located here! diff --git a/project/run_configs.yaml b/project/run_configs.yaml index df21e19..4a5c1d1 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -40,7 +40,7 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: limit_train_batches: 0.8 # train only on 80% of training data limit_val_batches: 1.0 # validate on 100% of validation data limit_test_batches: 1.0 # test on 100% of test data - val_check_interval: 2 # perform validation every 2 epochs + val_check_interval: 0.5 # perform twice per epoch model: load_from: model_path: "models/simple_mnist_classifier/lightning_module.py" @@ -80,6 +80,8 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: mode: "max" ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + MetricsHeatmapLoggerCallback: # some custom callback class from template_utils/callbacks.py + class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] resume_training: checkpoint_path: None # path to your checkpoint wandb_run_id: None # you can add id of wandb run you want to resume but it's optional diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 5b3efff..6de8388 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -9,6 +9,7 @@ import importlib.util import os # template utils imports +from pytorch_lightning import callbacks as lightning_callbacks from template_utils import callbacks as custom_callbacks from template_utils import wandb_callbacks @@ -141,7 +142,8 @@ def init_trainer(project_config: dict, def init_callbacks(project_config: dict, run_config: dict, - use_wandb: bool) -> List[pl.Callback]: + use_wandb: bool, + base_dir: str) -> List[pl.Callback]: """ Initialize default callbacks and callbacks specified in run config. """ @@ -149,26 +151,40 @@ def init_callbacks(project_config: dict, default_callbacks = project_config.get("default_callbacks", {}) run_callbacks = run_config.get("callbacks", {}) - # print(default_callbacks) + # namespaces in which callbacks will be searched for + namespaces = [ + lightning_callbacks, + custom_callbacks, + wandb_callbacks, + ] callbacks = [] - # for callback_config in default_callbacks: - # callback_class = getattr(pl.callbacks, callback_config["callback_class"]) - # callbacks.append(callback_class(**callback_config["args"])) - # - # for callback_config in run_callbacks: - # callback_class = getattr(pl.callbacks, callback_config["callback_class"]) - # callbacks.append(callback_class(**callback_config["args"])) - # - # if use_wandb: - # callbacks.append( - # wandb_callbacks.SaveCodeToWandbCallback( - # base_dir=os.path.dirname(os.path.dirname(__file__)), - # wandb_save_dir=project_config["logs_dir"], - # run_config=run_config - # ) - # ) + all_callback_configs = {} + for callback_config in default_callbacks: + all_callback_configs[callback_config] = default_callbacks[callback_config] + for callback_config in run_callbacks: + all_callback_configs[callback_config] = run_callbacks[callback_config] + + for callback_config in all_callback_configs: + found = False + for namespace in namespaces: + if hasattr(namespace, callback_config): + callback_class = getattr(namespace, callback_config) + callbacks.append(callback_class(**all_callback_configs[callback_config])) + found = True + break + if not found: + raise ModuleNotFoundError(f"Callback '{callback_config}' not found.") + + if use_wandb: + callbacks.append( + wandb_callbacks.SaveCodeToWandbCallback( + base_dir=base_dir, + wandb_save_dir=project_config["logs_dir"], + run_config=run_config + ) + ) return callbacks diff --git a/project/template_utils/wandb_callbacks.py b/project/template_utils/wandb_callbacks.py index ab23ee7..f56783e 100644 --- a/project/template_utils/wandb_callbacks.py +++ b/project/template_utils/wandb_callbacks.py @@ -1,4 +1,6 @@ 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 torch @@ -88,8 +90,13 @@ class MetricsHeatmapLoggerCallback(Callback): r = recall_score(self.preds, self.targets, average=None) p = precision_score(self.preds, self.targets, average=None) - trainer.logger.experiment.log({ - f"f1_p_r_heatmap_{trainer.current_epoch}_{trainer.logger.id}": wandb.plots.HeatMap( + logger = None + for some_logger in trainer.logger.experiment: + if isinstance(some_logger, wandb_run): + logger = some_logger + + logger.log({ + f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap( x_labels=self.class_names, y_labels=["f1", "precision", "recall"], matrix_values=[f1, p, r], @@ -129,7 +136,12 @@ class ConfusionMatrixLoggerCallback(Callback): self.preds = torch.cat(self.preds).tolist() self.targets = torch.cat(self.targets).tolist() - trainer.logger.experiment.log({ + logger = None + for some_logger in trainer.logger.experiment: + if isinstance(some_logger, wandb_run): + logger = some_logger + + logger.log({ f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix( self.preds, self.targets, @@ -147,8 +159,8 @@ class SaveCodeToWandbCallback(Callback): 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"]["model_folder"] - self.datamodule_folder = run_config["dataset"]["datamodule_folder"] + 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/callbacks.py", "template_utils/initializers.py", diff --git a/project/train.py b/project/train.py index fc6dee1..d26643e 100644 --- a/project/train.py +++ b/project/train.py @@ -53,7 +53,8 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): callbacks: List[Callback] = init_callbacks( project_config=project_config, run_config=run_config, - use_wandb=use_wandb + use_wandb=use_wandb, + base_dir=BASE_DIR ) # Init PyTorch Lightning loggers ⚡ @@ -96,7 +97,7 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str, run_config: dict = load_config(path=run_configs_path)[run_config_name] print("EXECUTING RUN:", run_config_name) - pprint.pprint(run_config, sort_dicts=False) + # pprint.pprint(run_config, sort_dicts=False) print() # Train model From afb4e17b2c9e21c84979cf98d490796b0d51f3fa Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 13 Dec 2020 22:36:20 +0100 Subject: [PATCH 6/6] many small improvements --- README.md | 11 ++++++---- .../lightning_module.py | 2 +- project/project_config.yaml | 20 +++++++++--------- project/run_configs.yaml | 4 ++-- project/template_utils/execute_all_runs.py | 18 +++++----------- project/template_utils/execute_sweep.py | 14 ++++++------- project/template_utils/initializers.py | 2 +- project/template_utils/wandb_callbacks.py | 6 +++--- project/train.py | 21 +++++++++++++++---- 9 files changed, 53 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index a431ba8..f6f4214 100644 --- a/README.md +++ b/README.md @@ -130,12 +130,15 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: batch_size: 64 train_val_test_split: [55_000, 5_000, 10_000] ``` -To start training with this configuration run: `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` +To start training with this configuration run:
+ `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` + +Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
+EVERY OTHER SECTION IS OPTIONAL! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)
-Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
-Sections `seed`, `callbacks`, `wandb` and `resume_training` are optional and can be removed (see advanced config example in [run_configs.yaml](project/run_configs.yaml)).
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).
+ Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).

@@ -146,7 +149,7 @@ Every parameter specified in datamodule hparams section will be passed to your d 3. Create new run config in [run_configs.yaml](project/run_configs.yaml) - specify path to your model class - specify path to your datamodule class - - you can add there and hyperparameters you want! + - you can add there any hyperparameters you want! 3. Configure your project in [project_config.yaml](project/project_config.yaml) 4. Run training with chosen run config
```bash diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index 7a981b2..99d7617 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -12,7 +12,7 @@ class LitModel(pl.LightningModule): This is example of lightning model for MNIST digits classification. The path to model should be specified in your run config. (run_configs.yaml) - The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml) + The 'hparams' dict contains your hparams specified in your run 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. diff --git a/project/project_config.yaml b/project/project_config.yaml index 4869a9c..ff29583 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -1,5 +1,5 @@ # set -1 to train on all GPUs abailable, set 0 to train on CPU only -num_of_gpus: 0 +num_of_gpus: -1 # Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) @@ -18,15 +18,15 @@ loggers: # if you specify the same callback class also in run config then it will overwrite the one set here # all of the callback parameters will be passed to it on initialization default_callbacks: - EarlyStopping: # name of PyTorch Lightning class for early stopping callback - monitor: "val_acc" - patience: 5 - mode: "max" - ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback - monitor: "val_acc" - save_top_k: 1 - save_last: True - mode: "max" + ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback + monitor: "val_acc" # name of the logged metric which determines when model is improving + save_top_k: 1 # save k best models (determined by above metric) + save_last: True # additionaly always save model from last epoch + mode: "max" # can be "max" or "min" + EarlyStopping: # name of PyTorch Lightning class for early stopping callback + 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 + mode: "max" # can be "max" or "min" # configure things which are printed in terminal diff --git a/project/run_configs.yaml b/project/run_configs.yaml index 4a5c1d1..22d5196 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -78,9 +78,9 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: save_top_k: 1 save_last: True mode: "max" - ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py + ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - MetricsHeatmapLoggerCallback: # some custom callback class from template_utils/callbacks.py + MetricsHeatmapWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] resume_training: checkpoint_path: None # path to your checkpoint diff --git a/project/template_utils/execute_all_runs.py b/project/template_utils/execute_all_runs.py index 4c5ce61..193f9e6 100644 --- a/project/template_utils/execute_all_runs.py +++ b/project/template_utils/execute_all_runs.py @@ -2,7 +2,7 @@ # YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS from argparse import ArgumentParser -from train import train +import train import wandb import yaml import os @@ -18,25 +18,17 @@ def main(project_config_path, run_configs_path): # EXECUTE ALL RUNS ONE AFTER THE OTHER for conf_name in run_configs: - print() - print("EXECUTING RUN:", conf_name) - print("CONFIG:") - for section in run_configs[conf_name]: - print(" " + section + ":") - for key in run_configs[conf_name][section]: - print(" " + key + ":", run_configs[conf_name][section][key]) - print() - - train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True) + 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(os.path.dirname(os.path.dirname(__file__)), "project_config.yaml")) + default=os.path.join(train.BASE_DIR, "project_config.yaml")) parser.add_argument("-r", "--run_configs_path", type=str, - default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "run_configs.yaml")) + 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/execute_sweep.py b/project/template_utils/execute_sweep.py index 9442d6a..7a205ab 100644 --- a/project/template_utils/execute_sweep.py +++ b/project/template_utils/execute_sweep.py @@ -6,7 +6,7 @@ import train # Choose which run config to optimize -RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1" +RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST" # Load configs project_config = train.load_config("project_config.yaml") @@ -20,12 +20,12 @@ sweep_hparams = wandb.Config._as_dict(wandb.config) for key, value in sweep_hparams.items(): if key == "_wandb": continue - elif key in run_config["trainer"].keys(): - run_config["trainer"][key] = value - elif key in run_config["model"].keys(): - run_config["model"][key] = value - elif key in run_config["dataset"].keys(): - run_config["dataset"][key] = value + elif key in run_config["trainer"]["args"]: + run_config["trainer"]["args"][key] = value + elif key in run_config["model"]["hparams"]: + run_config["model"]["hparams"][key] = value + elif key in run_config["datamodule"]["hparams"]: + run_config["datamodule"]["hparams"][key] = value # Execute run train.train(project_config=project_config, run_config=run_config, use_wandb=True) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 6de8388..8a1e067 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -274,7 +274,7 @@ def init_wandb_logger(project_config: dict, "test_size": len(datamodule.data_test) if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0, }) - wandb_logger.log_hyperparams(project_config["num_of_gpus"]) + wandb_logger.log_hyperparams({"num_of_gpus": project_config["num_of_gpus"]}) wandb_logger.log_hyperparams(run_config["trainer"]["args"]) wandb_logger.log_hyperparams(run_config["model"]["hparams"]) wandb_logger.log_hyperparams(run_config["model"]["load_from"]) diff --git a/project/template_utils/wandb_callbacks.py b/project/template_utils/wandb_callbacks.py index f56783e..3a4b94a 100644 --- a/project/template_utils/wandb_callbacks.py +++ b/project/template_utils/wandb_callbacks.py @@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback): wandb.save(file_path, base_path=self.wandb_save_dir) -class ImagePredictionLoggerCallback(Callback): +class ImagePredictionWandbLoggerCallback(Callback): """ Each epoch upload to wandb a couple of the same images with predicted labels. """ @@ -58,7 +58,7 @@ class ImagePredictionLoggerCallback(Callback): ]}, commit=False) -class MetricsHeatmapLoggerCallback(Callback): +class MetricsHeatmapWandbLoggerCallback(Callback): """ Generate f1, precision and recall heatmap from validation epoch outputs. Expects validation step to return predictions and targets. @@ -107,7 +107,7 @@ class MetricsHeatmapLoggerCallback(Callback): self.targets = [] -class ConfusionMatrixLoggerCallback(Callback): +class ConfusionMatrixWandbLoggerCallback(Callback): """ Generate Confusion Matrix. Expects validation step to return predictions and targets. diff --git a/project/train.py b/project/train.py index d26643e..514493c 100644 --- a/project/train.py +++ b/project/train.py @@ -106,10 +106,23 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str, if __name__ == "__main__": parser = ArgumentParser() - parser.add_argument("--project_config_path", type=str, default="project_config.yaml") - parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") - parser.add_argument("--run_config_name", type=str, default="SIMPLE_CONFIG_EXAMPLE_MNIST") - parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') + parser.add_argument("--project_config_path", + type=str, + default="project_config.yaml", + help="Path to file containing your project configuration") + parser.add_argument("--run_configs_path", + type=str, + default="run_configs.yaml", + help="Path to file containing your run configurations") + parser.add_argument("--run_config_name", + type=str, + default="SIMPLE_CONFIG_EXAMPLE_MNIST", + help="Name of you configuration in run_configs.yaml") + parser.add_argument("--no_wandb", + dest='use_wandb', + action='store_false', + help="Whether to use Weights&Biases or not") + parser.set_defaults(use_wandb=True) args = parser.parse_args()