diff --git a/conda_env.yaml b/conda_env.yaml index e5f8012..7703647 100644 --- a/conda_env.yaml +++ b/conda_env.yaml @@ -6,6 +6,7 @@ channels: dependencies: - python=3.8 - pip + - notebook - cudatoolkit - pytorch - torchvision diff --git a/project/configs/callbacks/default_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml index 074f80a..cc0ca4a 100644 --- a/project/configs/callbacks/default_callbacks.yaml +++ b/project/configs/callbacks/default_callbacks.yaml @@ -1,7 +1,7 @@ # @package _group_ model_checkpoint: - class: "pytorch_lightning.callbacks.ModelCheckpoint" + class: pytorch_lightning.callbacks.ModelCheckpoint args: monitor: "val_acc" # name of the logged metric which determines when model is improving save_top_k: 1 # save k best lightning_models (determined by above metric) @@ -11,7 +11,7 @@ model_checkpoint: early_stopping: - class: "pytorch_lightning.callbacks.EarlyStopping" + class: pytorch_lightning.callbacks.EarlyStopping args: monitor: "val_acc" # name of the logged metric which determines when model is improving patience: 100 # how many epochs of not improving until training stops diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml index 89192fd..70f8ea0 100644 --- a/project/configs/callbacks/wandb_callbacks.yaml +++ b/project/configs/callbacks/wandb_callbacks.yaml @@ -1,24 +1,18 @@ # @package _group_ -defaults: - - default_callbacks.yaml - - save_best_metric_scores_to_wandb: - class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb" + class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb args: {} + save_code_to_wandb_as_artifact: - class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb" + class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb args: code_dir: ${work_dir}/ -save_confusion_matrix_to_wandb: - class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveConfusionMatrixToWandb" - args: - class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') -save_f1_heatmap_to_wandb: - class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb" +upload_ckpts_to_wandb_as_artifact: + class: pytorch_modules.lightning_callbacks.wandb_callbacks.UploadAllCheckpointsToWandb args: - class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') + ckpt_dir: "checkpoints/" + upload_best_only: True diff --git a/project/configs/config.yaml b/project/configs/config.yaml index 3e302f2..e450c51 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -9,15 +9,12 @@ defaults: - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks - logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`) - # path to working directory (the directory that `train.py` was executed from in command line) work_dir: ${hydra:runtime.cwd} - # path to folder with data data_dir: ${work_dir}/data/ - # hydra output paths hydra: run: @@ -26,7 +23,6 @@ hydra: dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S} subdir: ${hydra.job.num} - # extra things that are logged by all loggers as hyperparameters, before training starts extra_logs: log_seeds: True diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml index c557e0d..f31d726 100644 --- a/project/configs/datamodule/mnist_datamodule.yaml +++ b/project/configs/datamodule/mnist_datamodule.yaml @@ -1,6 +1,6 @@ # @package _group_ -class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" +class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule args: batch_size: 64 train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/experiment/exp_example_advanced.yaml b/project/configs/experiment/exp_example_advanced.yaml index ebf468a..0d60efc 100644 --- a/project/configs/experiment/exp_example_advanced.yaml +++ b/project/configs/experiment/exp_example_advanced.yaml @@ -7,8 +7,10 @@ defaults: - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder - override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder - override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder - - override /optimizer: adam.yaml # choose datamodule from 'configs/datamodule/' folder + - override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder + - override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder - override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder + - override /logger: null # choose logger from 'configs/logger/' folder seeds: pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule) @@ -24,7 +26,7 @@ trainer: limit_val_batches: 0.9 # validate on 90% of validation data limit_test_batches: 1.0 # test on 100% of test data val_check_interval: 0.5 # perform validation twice per epoch -# resume_from_checkpoint: "last.ckpt" # use this to resume training from checkpoint + # resume_from_checkpoint: ${work_dir}/last.ckpt # use this to resume training from checkpoint model: args: # you can add here any params you want and then access them in lightning model @@ -46,12 +48,12 @@ optimizer: lr: 0.001 weight_decay: 0.00001 -loggers: +logger: wandb: args: # you can add here additional logger arguments specific for this experiment - tags: [best_model"] - notes: "" + tags: ["best_model", "uwu"] + notes: "Description of this model." group: "" comet: args: - tags: [best_model", "uwu"] + tags: ["best_model"] diff --git a/project/configs/experiment/exp_example_simple.yaml b/project/configs/experiment/exp_example_simple.yaml index e265293..9f3d6ea 100644 --- a/project/configs/experiment/exp_example_simple.yaml +++ b/project/configs/experiment/exp_example_simple.yaml @@ -7,8 +7,10 @@ defaults: - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder - override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder - override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder - - override /optimizer: adam.yaml # choose datamodule from 'configs/datamodule/' folder + - override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder + - override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder - override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder + - override /logger: null # choose logger from 'configs/logger/' folder seeds: pytorch_seed: 12345 diff --git a/project/configs/model/simple_mnist_classifier.yaml b/project/configs/model/simple_mnist_classifier.yaml index bcdd393..10989d0 100644 --- a/project/configs/model/simple_mnist_classifier.yaml +++ b/project/configs/model/simple_mnist_classifier.yaml @@ -1,6 +1,6 @@ # @package _group_ -class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" +class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel args: lr: 0.001 weight_decay: 0.00001 diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml index aff06d4..49c42d5 100644 --- a/project/configs/trainer/default_trainer.yaml +++ b/project/configs/trainer/default_trainer.yaml @@ -3,8 +3,8 @@ # default args passed to Lightning Trainer on every experiment # they can be combined or overwritten with args set in experiment config args: -# gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only -# auto_select_gpus: True + gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only + auto_select_gpus: True num_sanity_val_steps: 3 progress_bar_refresh_rate: 10 weights_summary: null # null in yaml represents python None value diff --git a/project/pytorch_modules/datasets/img_test_dataset.py b/project/pytorch_modules/datasets/img_test_dataset.py index 22feb4e..14076d6 100644 --- a/project/pytorch_modules/datasets/img_test_dataset.py +++ b/project/pytorch_modules/datasets/img_test_dataset.py @@ -7,7 +7,7 @@ class TestDataset(Dataset): """ 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 lightning_datamodules. + '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/pytorch_modules/lightning_callbacks/custom_callbacks.py b/project/pytorch_modules/lightning_callbacks/custom_callbacks.py index 31785a2..4a94532 100644 --- a/project/pytorch_modules/lightning_callbacks/custom_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/custom_callbacks.py @@ -17,7 +17,7 @@ class ExampleCallback(Callback): class UnfreezeModelCallback(Callback): """ - Unfreeze model after a few epochs. + Unfreeze model after a few epochs. """ def __init__(self, wait_epochs=5): self.wait_epochs = wait_epochs diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 1158f49..10566e4 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -2,7 +2,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 -import random import torch import wandb import glob @@ -24,31 +23,22 @@ class SaveCodeToWandb(Callback): wandb.run.use_artifact(code) -# class SaveImagePredictionsToWandb(Callback): -# """ -# Each epoch upload to wandb a couple of the same images with predicted labels. -# """ -# def __init__(self, datamodule, num_samples=8): -# first_batch = next(iter(datamodule.train_dataloader())) -# self.imgs, self.labels = first_batch -# self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples] -# self.ready = True -# -# def on_sanity_check_end(self, trainer, pl_module): -# """Start executing this callback only after all validation sanity checks end.""" -# self.ready = True -# -# def on_validation_epoch_end(self, trainer, pl_module): -# if self.ready: -# imgs = self.imgs.to(device=pl_module.device) -# logits = pl_module(imgs) -# preds = torch.argmax(logits, -1) -# trainer.logger.experiment.log({f"img_examples": [ -# wandb.Image( -# x, -# caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}" -# ) for x, pred, y in zip(imgs, preds, self.labels) -# ]}, commit=False) +class UploadAllCheckpointsToWandb(Callback): + def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False): + self.ckpt_dir = ckpt_dir + self.upload_best_only = upload_best_only + + def on_train_end(self, trainer, pl_module): + """Upload ckpts when training ends.""" + ckpts = wandb.Artifact('experiment-ckpts', type='checkpoints') + + if self.upload_best_only: + ckpts.add_file(trainer.checkpoint_callback.best_model_path) + else: + for path in glob.glob(os.path.join(self.ckpt_dir, '**/*.ckpt'), recursive=True): + ckpts.add_file(path) + + wandb.run.use_artifact(ckpts) class SaveMetricsHeatmapToWandb(Callback): @@ -77,8 +67,8 @@ class SaveMetricsHeatmapToWandb(Callback): 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) + self.preds = torch.cat(self.preds).cpu() + self.targets = torch.cat(self.targets).cpu() 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) @@ -202,3 +192,30 @@ class SaveBestMetricScoresToWandb(Callback): logger.log({"val_acc_best": self.val_acc_best}, commit=False) self.clear_lists() + + +# class SaveImagePredictionsToWandb(Callback): +# """ +# Each epoch upload to wandb a couple of the same images with predicted labels. +# """ +# def __init__(self, datamodule, num_samples=8): +# first_batch = next(iter(datamodule.train_dataloader())) +# self.imgs, self.labels = first_batch +# self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples] +# self.ready = True +# +# def on_sanity_check_end(self, trainer, pl_module): +# """Start executing this callback only after all validation sanity checks end.""" +# self.ready = True +# +# def on_validation_epoch_end(self, trainer, pl_module): +# if self.ready: +# imgs = self.imgs.to(device=pl_module.device) +# logits = pl_module(imgs) +# preds = torch.argmax(logits, -1) +# trainer.logger.experiment.log({f"img_examples": [ +# wandb.Image( +# x, +# caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}" +# ) for x, pred, y in zip(imgs, preds, self.labels) +# ]}, commit=False) diff --git a/project/pytorch_modules/transforms/mnist_transforms.py b/project/pytorch_modules/transforms/mnist_transforms.py index 05e4d22..7ab835b 100644 --- a/project/pytorch_modules/transforms/mnist_transforms.py +++ b/project/pytorch_modules/transforms/mnist_transforms.py @@ -9,5 +9,5 @@ mnist_train_transforms = transforms.Compose([ ]) mnist_test_transforms = transforms.Compose([ - transforms.ToTensor() + transforms.ToTensor(), ]) diff --git a/project/train.py b/project/train.py index fa1a50b..6cf1e1d 100644 --- a/project/train.py +++ b/project/train.py @@ -4,7 +4,7 @@ import pytorch_lightning as pl import torch # hydra imports -from omegaconf import DictConfig, OmegaConf +from omegaconf import DictConfig import hydra # normal imports