From fa8b9ecc16403dc89e485e82077cf1db2064298b Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 29 Dec 2020 01:48:44 +0100 Subject: [PATCH 01/15] start redesigning project structure for version 4.0 --- README.md | 14 +-- .../callbacks_configs/mnist_callbacks.yaml} | 0 .../advanced_mnist_experiment_config.yaml | 59 +++++++++++++ .../simple_mnist_experiment_config.yaml | 28 ++++++ .../predict_example.py | 6 +- project/models/.gitkeep | 0 project/project_config.yaml | 49 +++++++---- .../architectures/simple_mnist.py} | 0 .../datasets/img_test_dataset.py} | 2 +- .../lightning_callbacks/custom_callbacks.py} | 0 .../lightning_callbacks}/wandb_callbacks.py | 4 +- .../mnist_datamodule.py} | 0 .../simple_mnist_classifier.py} | 4 +- .../transforms/mnist_transforms.py} | 0 project/run_configs.yaml | 87 ------------------- ...all_runs.py => execute_all_experiments.py} | 0 project/template_utils/initializers.py | 15 ++-- project/train.py | 2 +- 18 files changed, 140 insertions(+), 130 deletions(-) rename project/{datamodules/.gitkeep => configs/callbacks_configs/mnist_callbacks.yaml} (100%) create mode 100644 project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml create mode 100644 project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml rename project/{template_utils => inference}/predict_example.py (80%) delete mode 100644 project/models/.gitkeep rename project/{models/simple_mnist_classifier/models.py => pytorch_modules/architectures/simple_mnist.py} (100%) rename project/{datamodules/mnist_datamodule/datasets.py => pytorch_modules/datasets/img_test_dataset.py} (93%) rename project/{template_utils/callbacks.py => pytorch_modules/lightning_callbacks/custom_callbacks.py} (100%) rename project/{template_utils => pytorch_modules/lightning_callbacks}/wandb_callbacks.py (98%) rename project/{datamodules/mnist_datamodule/datamodule.py => pytorch_modules/lightning_datamodules/mnist_datamodule.py} (100%) rename project/{models/simple_mnist_classifier/lightning_module.py => pytorch_modules/lightning_models/simple_mnist_classifier.py} (96%) rename project/{datamodules/mnist_datamodule/transforms.py => pytorch_modules/transforms/mnist_transforms.py} (100%) delete mode 100644 project/run_configs.yaml rename project/template_utils/{execute_all_runs.py => execute_all_experiments.py} (100%) diff --git a/README.md b/README.md index 62f2d01..32551c7 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,12 @@ Click on "Use this template" button above to initialize new repository. @@ -83,7 +83,7 @@ loggers: 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_top_k: 1 <- save k best lightning_models (determined by above metric) save_last: True <- additionaly always save model from last epoch mode: "max" <- can be "max" or "min" EarlyStopping: @@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: max_epochs: 10 model: load_from: - model_path: "models/simple_mnist_classifier/lightning_module.py" + model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py" model_class: "LitModel" hparams: lr: 0.001 @@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: lin3_size: 128 datamodule: load_from: - datamodule_path: "datamodules/mnist_datamodule/datamodule.py" + datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py" datamodule_class: "MNISTDataModule" hparams: batch_size: 64 @@ -138,9 +138,9 @@ Each run configuration needs to contain sections `trainer`, `model` and `datamod Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)
-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 model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/pytorch_modules/lightning_models/simple_mnist_classifier.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)).
+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/pytorch_modules/lightning_datamodules/mnist_datamodule.py)).

diff --git a/project/datamodules/.gitkeep b/project/configs/callbacks_configs/mnist_callbacks.yaml similarity index 100% rename from project/datamodules/.gitkeep rename to project/configs/callbacks_configs/mnist_callbacks.yaml diff --git a/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml b/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml new file mode 100644 index 0000000..0a4e776 --- /dev/null +++ b/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml @@ -0,0 +1,59 @@ +# to execute this run: +# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST_v2 + +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: 0.5 # perform validation twice per epoch +model: + load_from: + model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py" + model_class: "LitModel" + hparams: # you can add here any parameters you want and then read them in model! + lr: 0.001 + weight_decay: 0.00001 + 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: "lightning_datamodules/mnist_datamodule/mnist_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_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/custom_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" + ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py + class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + 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 + wandb_run_id: None # you can add id of wandb run you want to resume but it's optional diff --git a/project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml b/project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml new file mode 100644 index 0000000..6358cd7 --- /dev/null +++ b/project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml @@ -0,0 +1,28 @@ +# to execute this run: +# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST + +seed: 1234 + +trainer_args: + max_epochs: 10 + +model: + load_from: + model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.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: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py" + datamodule_class: "MNISTDataModule" + hparams: + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/template_utils/predict_example.py b/project/inference/predict_example.py similarity index 80% rename from project/template_utils/predict_example.py rename to project/inference/predict_example.py index 8f31156..b1667d5 100644 --- a/project/template_utils/predict_example.py +++ b/project/inference/predict_example.py @@ -1,8 +1,8 @@ -from datamodules.mnist_datamodule import transforms +from pytorch_modules.lightning_datamodules.mnist_datamodule import transforms from PIL import Image # the LitModel you import should be the same as the one you used for training! -from models.simple_mnist_classifier.lightning_module import LitModel +from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel def predict(): @@ -10,7 +10,7 @@ def predict(): This method is example of inference with a trained model. It Loads trained image classification model from checkpoint. Then it loads example image and predicts its label. - Model used in lightning_module.py should be the same as during training!!! + Model used in simple_mnist_classifier.py should be the same as during training!!! """ CKPT_PATH = "epoch=0.ckpt" diff --git a/project/models/.gitkeep b/project/models/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/project/project_config.yaml b/project/project_config.yaml index ff29583..c6846d4 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -1,26 +1,37 @@ -# set -1 to train on all GPUs abailable, set 0 to train on CPU only -num_of_gpus: -1 +# default args passed to Lightning Trainer on every run/experiment +# if you specify the same args in experiment config then they will overwrite the ones set here +default_trainer_args: + num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + progress_bar_refresh_rate: 10 # refresh terminal every 10 batches + weights_summary: "top" # print model summary (alternatively "full") -# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) -loggers: - 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 - 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 loggers initialised on every run/experiment +# if you specify this section in experiment config then it will be totally overwritten +default_loggers: + wandb: # Weights&Biases config (just remove this section if you don't want tu ever use Weights&Biases) + use_wandb: True + log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) + log_optimizer_name: True + log_train_val_test_data_lengths: True + default_args: + 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 + tensorboard: + use_tensorboard: False + default_args: {} -# default callbacks initialised on every run/experiment +# default lightning_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 -# if you specify the same callback class also in run config then it will overwrite the one set here +# if you specify the same callback class also in experiment config then it will overwrite the one set here # all of the callback parameters will be passed to it on initialization default_callbacks: 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_top_k: 1 # save k best lightning_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 @@ -29,11 +40,11 @@ default_callbacks: mode: "max" # can be "max" or "min" -# configure things which are printed in terminal -printing: - progress_bar_refresh_rate: 10 # refresh every 10 batches - weights_summary: "top" # print model summary (alternatively "full") - profiler: False # set True to print execution time profiling after training ends +# use profiler to print execution time profiling after training ends +profiler: + use_profiler: True + class: "pytorch_lightning.profiler.SimpleProfiler" + args: {} # path to data folder (either absolute or relative to placement of 'train.py' file) diff --git a/project/models/simple_mnist_classifier/models.py b/project/pytorch_modules/architectures/simple_mnist.py similarity index 100% rename from project/models/simple_mnist_classifier/models.py rename to project/pytorch_modules/architectures/simple_mnist.py diff --git a/project/datamodules/mnist_datamodule/datasets.py b/project/pytorch_modules/datasets/img_test_dataset.py similarity index 93% rename from project/datamodules/mnist_datamodule/datasets.py rename to project/pytorch_modules/datasets/img_test_dataset.py index 14076d6..22feb4e 100644 --- a/project/datamodules/mnist_datamodule/datasets.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 datamodules. + 'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by lightning_datamodules. """ def __init__(self, img_dir, transform): diff --git a/project/template_utils/callbacks.py b/project/pytorch_modules/lightning_callbacks/custom_callbacks.py similarity index 100% rename from project/template_utils/callbacks.py rename to project/pytorch_modules/lightning_callbacks/custom_callbacks.py diff --git a/project/template_utils/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py similarity index 98% rename from project/template_utils/wandb_callbacks.py rename to project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 3a4b94a..70f54de 100644 --- a/project/template_utils/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -11,7 +11,7 @@ import os class SaveOnnxModelToWandbCallback(Callback): """ Save model in .onnx format and upload to wandb. - Might crash since not all models are compatible with onnx. + Might crash since not all lightning_models are compatible with onnx. """ def __init__(self, datamodule, wandb_save_dir): first_batch = next(iter(datamodule.train_dataloader())) @@ -162,7 +162,7 @@ class SaveCodeToWandbCallback(Callback): 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/custom_callbacks.py", "template_utils/initializers.py", "train.py", "project_config.yaml", diff --git a/project/datamodules/mnist_datamodule/datamodule.py b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py similarity index 100% rename from project/datamodules/mnist_datamodule/datamodule.py rename to project/pytorch_modules/lightning_datamodules/mnist_datamodule.py diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py similarity index 96% rename from project/models/simple_mnist_classifier/lightning_module.py rename to project/pytorch_modules/lightning_models/simple_mnist_classifier.py index 7a981b2..27960d2 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -3,8 +3,8 @@ import pytorch_lightning as pl import torch.nn.functional as F import torch -# import custom models -from models.simple_mnist_classifier.models import * +# import custom lightning_models +from pytorch_modules.lightning_models.simple_mnist_classifier.models import * class LitModel(pl.LightningModule): diff --git a/project/datamodules/mnist_datamodule/transforms.py b/project/pytorch_modules/transforms/mnist_transforms.py similarity index 100% rename from project/datamodules/mnist_datamodule/transforms.py rename to project/pytorch_modules/transforms/mnist_transforms.py diff --git a/project/run_configs.yaml b/project/run_configs.yaml deleted file mode 100644 index 22d5196..0000000 --- a/project/run_configs.yaml +++ /dev/null @@ -1,87 +0,0 @@ -# to execute this run: -# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST -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] - - -# to execute this run: -# 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: 0.5 # perform twice per epoch - 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: 0.00001 - 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_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" - ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - 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 - 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/execute_all_runs.py b/project/template_utils/execute_all_experiments.py similarity index 100% rename from project/template_utils/execute_all_runs.py rename to project/template_utils/execute_all_experiments.py diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index cd493d2..22d29e3 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,5 +1,5 @@ # pytorch lightning imports -from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger +from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.profiler import SimpleProfiler import pytorch_lightning as pl @@ -10,8 +10,7 @@ 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 +from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]: @@ -24,7 +23,7 @@ def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str 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"] =\ + 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"]): @@ -112,7 +111,7 @@ def init_trainer(project_config: dict, # experiment logging logger=loggers, - # useful callbacks + # useful lightning_callbacks callbacks=callbacks, # resume training from checkpoint if it was set in the run config @@ -145,13 +144,13 @@ def init_callbacks(project_config: dict, use_wandb: bool, base_dir: str) -> List[pl.Callback]: """ - Initialize default callbacks and callbacks specified in run config. + Initialize default lightning_callbacks and lightning_callbacks specified in run config. """ default_callbacks = project_config.get("default_callbacks", {}) - run_callbacks = run_config.get("callbacks", {}) + run_callbacks = run_config.get("lightning_callbacks", {}) - # namespaces in which callbacks will be searched for + # namespaces in which lightning_callbacks will be searched for namespaces = [ lightning_callbacks, custom_callbacks, diff --git a/project/train.py b/project/train.py index 514493c..e9c00d4 100644 --- a/project/train.py +++ b/project/train.py @@ -49,7 +49,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): data_dir=project_config["data_dir"] ) - # Init PyTorch Lightning callbacks ⚡ + # Init PyTorch Lightning lightning_callbacks ⚡ callbacks: List[Callback] = init_callbacks( project_config=project_config, run_config=run_config, From 99ac2a90624a01aa9c2c796fcc22e295d387aa57 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 29 Dec 2020 02:35:14 +0100 Subject: [PATCH 02/15] improvements... --- .../callbacks_configs/mnist_callbacks.yaml | 16 +++++ .../advanced_mnist_experiment_config.yaml | 59 ---------------- .../mnist_classifier_advanced_conf.yaml | 67 +++++++++++++++++++ ...yaml => mnist_classifier_simple_conf.yaml} | 8 +-- project/project_config.yaml | 31 ++++++--- .../template_utils/execute_all_experiments.py | 3 +- 6 files changed, 108 insertions(+), 76 deletions(-) delete mode 100644 project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml create mode 100644 project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml rename project/configs/experiment_configs/mnist_experiments/{simple_mnist_experiment_config.yaml => mnist_classifier_simple_conf.yaml} (69%) diff --git a/project/configs/callbacks_configs/mnist_callbacks.yaml b/project/configs/callbacks_configs/mnist_callbacks.yaml index e69de29..f86281f 100644 --- a/project/configs/callbacks_configs/mnist_callbacks.yaml +++ b/project/configs/callbacks_configs/mnist_callbacks.yaml @@ -0,0 +1,16 @@ +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" + +ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py + class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] + +MetricsHeatmapWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py + class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] diff --git a/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml b/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml deleted file mode 100644 index 0a4e776..0000000 --- a/project/configs/experiment_configs/mnist_experiments/advanced_mnist_experiment_config.yaml +++ /dev/null @@ -1,59 +0,0 @@ -# to execute this run: -# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST_v2 - -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: 0.5 # perform validation twice per epoch -model: - load_from: - model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py" - model_class: "LitModel" - hparams: # you can add here any parameters you want and then read them in model! - lr: 0.001 - weight_decay: 0.00001 - 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: "lightning_datamodules/mnist_datamodule/mnist_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_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/custom_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" - ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - 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 - wandb_run_id: None # you can add id of wandb run you want to resume but it's optional diff --git a/project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml b/project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml new file mode 100644 index 0000000..9aa548c --- /dev/null +++ b/project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml @@ -0,0 +1,67 @@ +# to execute this experiment run: +# python train.py --exp_conf configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml + +# (required section) +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: 0.5 # perform validation twice per epoch + +# (required section) +model: + load_from: + model_path: "pytorch_modules/lightning_models/simple_mnist_classifier.py" + model_class: "LitModel" + hparams: # you can add here any parameters you want and then read them in model + lr: 0.001 + weight_decay: 0.00001 + 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 + +# (required section) +datamodule: + load_from: + datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_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_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 + +# (optional section) +# pytorch seed for this experiment +# it also affects random_split() method used in mnist_datamodule.py +# overwrites default pytorch seed set in project_config.yaml +pytorch_seed: + use_seed: True + pytorch_seed: 1234 + +# (optional section) +# Weights&Biases logger args +# this will be combained with default wandb args set in project_config.yaml (overwrites repeating args) +wandb_args: + group: "" + job_type: "train" + tags: ["v2", "uwu"] + notes: "This is example run." + +# (optional section) +# path to .yaml file containing configurations of all callbacks which will be used for this experiment +# this will be combained with default callbacks set in project_config.yaml (overwrites repeating callbacks) +callbacks_configs_path: "configs/callbacks_configs/mnist_callabcks.yaml" + +# (optional section) +# use this if you want to resume training from checkpoint +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/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml b/project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml similarity index 69% rename from project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml rename to project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml index 6358cd7..4073603 100644 --- a/project/configs/experiment_configs/mnist_experiments/simple_mnist_experiment_config.yaml +++ b/project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml @@ -1,14 +1,12 @@ -# to execute this run: -# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST - -seed: 1234 +# to execute this experiment run: +# python train.py --exp_conf configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml trainer_args: max_epochs: 10 model: load_from: - model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py" + model_path: "pytorch_modules/lightning_models/simple_mnist_classifier.py" model_class: "LitModel" hparams: lr: 0.001 diff --git a/project/project_config.yaml b/project/project_config.yaml index c6846d4..70192c4 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -1,11 +1,18 @@ # default args passed to Lightning Trainer on every run/experiment # if you specify the same args in experiment config then they will overwrite the ones set here default_trainer_args: - num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + num_of_gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only progress_bar_refresh_rate: 10 # refresh terminal every 10 batches weights_summary: "top" # print model summary (alternatively "full") +# default pytorch seed used on every run/experiment +# this can be overwritten by +default_pytorch_seed: + use_seed: True + pytorch_seed: 1234 + + # default loggers initialised on every run/experiment # if you specify this section in experiment config then it will be totally overwritten default_loggers: @@ -29,15 +36,19 @@ default_loggers: # if you specify the same callback class also in experiment config then it will overwrite the one set here # all of the callback parameters will be passed to it on initialization default_callbacks: - 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 lightning_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" + chekpointing: + 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) + save_last: True # additionaly always save model from last epoch + mode: "max" # can be "max" or "min" + early_stopping: + class: "pytorch_lightning.callbacks.EarlyStopping" + args: + 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" # use profiler to print execution time profiling after training ends diff --git a/project/template_utils/execute_all_experiments.py b/project/template_utils/execute_all_experiments.py index 193f9e6..c84e7ae 100644 --- a/project/template_utils/execute_all_experiments.py +++ b/project/template_utils/execute_all_experiments.py @@ -1,5 +1,4 @@ -# THIS FILE WILL EXECUTE ALL RUNS SPECIFIED IN run_configs.yaml ONE AFTER THE OTHER -# YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS +# THIS FILE WILL EXECUTE ALL EXPERIMENT CONFIGS LOCATED IN SPECIFIED FOLDER ONE AFTER THE OTHER from argparse import ArgumentParser import train From 2726557906200e73ca48d5c80e2a1cc517b25455 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 2 Jan 2021 17:25:54 +0100 Subject: [PATCH 03/15] start introduction of Hydra for config management --- README.md | 6 +- .../callbacks_configs/mnist_callbacks.yaml | 16 ----- ..._advanced_conf.yaml => advanced_conf.yaml} | 22 +++---- .../mnist_classifier_simple_conf.yaml | 26 -------- .../mnist_experiments/simple_conf.yaml | 25 +++++++ project/configs/project_config.yaml | 14 ++++ .../callbacks/mnist_callbacks.yaml | 17 +++++ .../datamodule/mnist_datamodule.yaml | 12 ++++ .../configs/project_config/logger/comet.yaml | 10 +++ .../project_config/logger/tensorboard.yaml | 5 ++ .../configs/project_config/logger/wandb.yaml | 12 ++++ .../model/simple_mnist_classifier.yaml | 12 ++++ .../trainer/default_trainer.yaml | 13 ++++ project/project_config.yaml | 66 ------------------- .../lightning_datamodules/mnist_datamodule.py | 3 + .../simple_mnist_classifier.py | 7 +- project/template_utils/initializers.py | 10 ++- .../predict_example.py | 0 project_config.yaml | 54 +++++++++++++++ 19 files changed, 203 insertions(+), 127 deletions(-) delete mode 100644 project/configs/callbacks_configs/mnist_callbacks.yaml rename project/configs/experiment_configs/mnist_experiments/{mnist_classifier_advanced_conf.yaml => advanced_conf.yaml} (83%) delete mode 100644 project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml create mode 100644 project/configs/experiment_configs/mnist_experiments/simple_conf.yaml create mode 100644 project/configs/project_config.yaml create mode 100644 project/configs/project_config/callbacks/mnist_callbacks.yaml create mode 100644 project/configs/project_config/datamodule/mnist_datamodule.yaml create mode 100644 project/configs/project_config/logger/comet.yaml create mode 100644 project/configs/project_config/logger/tensorboard.yaml create mode 100644 project/configs/project_config/logger/wandb.yaml create mode 100644 project/configs/project_config/model/simple_mnist_classifier.yaml create mode 100644 project/configs/project_config/trainer/default_trainer.yaml delete mode 100644 project/project_config.yaml rename project/{inference => template_utils}/predict_example.py (100%) create mode 100644 project_config.yaml diff --git a/README.md b/README.md index 32551c7..22247af 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Click on "Use this template" button above to initialize new repository. -## Project config parameters ([project_config.yaml](project/project_config.yaml)) +## Project config parameters ([project_config.yaml](project_config.yaml)) Example project configuration: ```yaml num_of_gpus: -1 <- '-1' to train on all GPUs available, '0' to train on CPU @@ -151,7 +151,7 @@ Every parameter specified in datamodule hparams section will be passed to your d - specify path to your model class - specify path to your datamodule class - you can add there any hyperparameters you want! -3. Configure your project in [project_config.yaml](project/project_config.yaml) +3. Configure your project in [project_config.yaml](project_config.yaml) 4. Run training with chosen run config
```bash python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST diff --git a/project/configs/callbacks_configs/mnist_callbacks.yaml b/project/configs/callbacks_configs/mnist_callbacks.yaml deleted file mode 100644 index f86281f..0000000 --- a/project/configs/callbacks_configs/mnist_callbacks.yaml +++ /dev/null @@ -1,16 +0,0 @@ -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" - -ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] - -MetricsHeatmapWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py - class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] diff --git a/project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml b/project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml similarity index 83% rename from project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml rename to project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml index 9aa548c..6e564d8 100644 --- a/project/configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml +++ b/project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml @@ -1,10 +1,17 @@ # to execute this experiment run: -# python train.py --exp_conf configs/experiment_configs/mnist_experiments/mnist_classifier_advanced_conf.yaml +# python train.py --exp_conf configs/experiment/mnist_experiments/advanced_conf.yaml + + +# (optional section) +# pytorch seed for this experiment +# it also affects random_split() method used in mnist_datamodule.py +# overwrites default pytorch seed set in project_config.yaml +seed: 1234 # (required section) trainer_args: min_epochs: 1 # train for at least this many epochs (denies early stopping) - max_epochs: 10 + max_epochs: 10 # train for maximum this many epochs 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 @@ -38,13 +45,6 @@ datamodule: 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 -# (optional section) -# pytorch seed for this experiment -# it also affects random_split() method used in mnist_datamodule.py -# overwrites default pytorch seed set in project_config.yaml -pytorch_seed: - use_seed: True - pytorch_seed: 1234 # (optional section) # Weights&Biases logger args @@ -55,10 +55,6 @@ wandb_args: tags: ["v2", "uwu"] notes: "This is example run." -# (optional section) -# path to .yaml file containing configurations of all callbacks which will be used for this experiment -# this will be combained with default callbacks set in project_config.yaml (overwrites repeating callbacks) -callbacks_configs_path: "configs/callbacks_configs/mnist_callabcks.yaml" # (optional section) # use this if you want to resume training from checkpoint diff --git a/project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml b/project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml deleted file mode 100644 index 4073603..0000000 --- a/project/configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml +++ /dev/null @@ -1,26 +0,0 @@ -# to execute this experiment run: -# python train.py --exp_conf configs/experiment_configs/mnist_experiments/mnist_classifier_simple_conf.yaml - -trainer_args: - max_epochs: 10 - -model: - load_from: - model_path: "pytorch_modules/lightning_models/simple_mnist_classifier.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: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py" - datamodule_class: "MNISTDataModule" - hparams: - batch_size: 64 - train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/experiment_configs/mnist_experiments/simple_conf.yaml b/project/configs/experiment_configs/mnist_experiments/simple_conf.yaml new file mode 100644 index 0000000..45fad18 --- /dev/null +++ b/project/configs/experiment_configs/mnist_experiments/simple_conf.yaml @@ -0,0 +1,25 @@ +# to execute this experiment run: +# python train.py --exp_conf configs/experiment/mnist_experiments/simple_conf.yaml + + +seed: 1234 + +trainer_args: + max_epochs: 10 + +model: + class: "pytorch_modules.lightning_models.simple_mnist_classifier.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: + class: "lightning_datamodules.mnist_datamodule.mnist_datamodule.MNISTDataModule" + hparams: + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/project_config.yaml b/project/configs/project_config.yaml new file mode 100644 index 0000000..4666265 --- /dev/null +++ b/project/configs/project_config.yaml @@ -0,0 +1,14 @@ +defaults: + - project_config/trainer: default_trainer +# - model: simple_mnist_classifier +# - datamodule: mnist_datamodule +# - logger: comet +# - callbacks: mnist_callbacks + + +# path to data folder (either absolute or relative to placement of 'train.py' file) +data_dir: "data/" + + +# path to logs folder (either absolute or relative to placement of 'train.py' file) +logs_dir: "logs/" diff --git a/project/configs/project_config/callbacks/mnist_callbacks.yaml b/project/configs/project_config/callbacks/mnist_callbacks.yaml new file mode 100644 index 0000000..c36fa30 --- /dev/null +++ b/project/configs/project_config/callbacks/mnist_callbacks.yaml @@ -0,0 +1,17 @@ +# @package _group_ + +model_checkpoint: + 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) + save_last: True # additionaly always save model from last epoch + mode: "max" # can be "max" or "min" + + +early_stopping: + class: "pytorch_lightning.callbacks.EarlyStopping" + args: + 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" diff --git a/project/configs/project_config/datamodule/mnist_datamodule.yaml b/project/configs/project_config/datamodule/mnist_datamodule.yaml new file mode 100644 index 0000000..d0ec339 --- /dev/null +++ b/project/configs/project_config/datamodule/mnist_datamodule.yaml @@ -0,0 +1,12 @@ +# @package _group_ + +class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" + +hparams: + lr: 0.001 + weight_decay: 0.00001 + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 diff --git a/project/configs/project_config/logger/comet.yaml b/project/configs/project_config/logger/comet.yaml new file mode 100644 index 0000000..83182f2 --- /dev/null +++ b/project/configs/project_config/logger/comet.yaml @@ -0,0 +1,10 @@ +# @package _group_ +# Comet logger config + +args: + api_key: "sadfhgadfhsdfhadgkajdgsdg" + project_name: "project_template_test" + +extra_options: + log_optimizer_name: True + log_train_val_test_sizes: True diff --git a/project/configs/project_config/logger/tensorboard.yaml b/project/configs/project_config/logger/tensorboard.yaml new file mode 100644 index 0000000..ad67a99 --- /dev/null +++ b/project/configs/project_config/logger/tensorboard.yaml @@ -0,0 +1,5 @@ +# Tensorboard logger config + +args: {} + +extra_options: {} diff --git a/project/configs/project_config/logger/wandb.yaml b/project/configs/project_config/logger/wandb.yaml new file mode 100644 index 0000000..ec03aec --- /dev/null +++ b/project/configs/project_config/logger/wandb.yaml @@ -0,0 +1,12 @@ +# Weights&Biases logger config + +args: + project: "project_template_test" + entity: "" # 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 + +extra_options: + log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) + log_optimizer_name: True + log_train_val_test_sizes: True diff --git a/project/configs/project_config/model/simple_mnist_classifier.yaml b/project/configs/project_config/model/simple_mnist_classifier.yaml new file mode 100644 index 0000000..f2c3453 --- /dev/null +++ b/project/configs/project_config/model/simple_mnist_classifier.yaml @@ -0,0 +1,12 @@ +# @package _group_ + +class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" + +hparams: + lr: 0.001 + weight_decay: 0.00001 + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 diff --git a/project/configs/project_config/trainer/default_trainer.yaml b/project/configs/project_config/trainer/default_trainer.yaml new file mode 100644 index 0000000..8b0487a --- /dev/null +++ b/project/configs/project_config/trainer/default_trainer.yaml @@ -0,0 +1,13 @@ +# @package _group_ + +# args passed to Lightning Trainer on every experiment +# they will be combined with trainer args specified in experiment config +# (if the argument repeats in experiment config, then it will override the one set here) +args: + num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + auto_select_gpus: True + num_sanity_val_steps: 3 + progress_bar_refresh_rate: 10 + weights_summary: "top" + max_epochs: 100 + profiler: "simple" # use profiler to print execution time profiling after training ends diff --git a/project/project_config.yaml b/project/project_config.yaml deleted file mode 100644 index 70192c4..0000000 --- a/project/project_config.yaml +++ /dev/null @@ -1,66 +0,0 @@ -# default args passed to Lightning Trainer on every run/experiment -# if you specify the same args in experiment config then they will overwrite the ones set here -default_trainer_args: - num_of_gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only - progress_bar_refresh_rate: 10 # refresh terminal every 10 batches - weights_summary: "top" # print model summary (alternatively "full") - - -# default pytorch seed used on every run/experiment -# this can be overwritten by -default_pytorch_seed: - use_seed: True - pytorch_seed: 1234 - - -# default loggers initialised on every run/experiment -# if you specify this section in experiment config then it will be totally overwritten -default_loggers: - wandb: # Weights&Biases config (just remove this section if you don't want tu ever use Weights&Biases) - use_wandb: True - log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) - log_optimizer_name: True - log_train_val_test_data_lengths: True - default_args: - 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 - tensorboard: - use_tensorboard: False - default_args: {} - - -# default lightning_callbacks initialised on every run/experiment -# you can just remove this section or certain callback if you don't want tu use it -# if you specify the same callback class also in experiment config then it will overwrite the one set here -# all of the callback parameters will be passed to it on initialization -default_callbacks: - chekpointing: - 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) - save_last: True # additionaly always save model from last epoch - mode: "max" # can be "max" or "min" - early_stopping: - class: "pytorch_lightning.callbacks.EarlyStopping" - args: - 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" - - -# use profiler to print execution time profiling after training ends -profiler: - use_profiler: True - class: "pytorch_lightning.profiler.SimpleProfiler" - args: {} - - -# path to data folder (either absolute or relative to placement of 'train.py' file) -data_dir: "data/" - - -# path to logs folder (either absolute or relative to placement of 'train.py' file) -logs_dir: "logs/" diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py index 3470394..6978c53 100644 --- a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py +++ b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py @@ -10,6 +10,9 @@ class MNISTDataModule(LightningDataModule): 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) + + To learn how to create datamodules visit: + https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html """ def __init__(self, data_dir: str, hparams: dict): diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index 27960d2..746ac64 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -3,8 +3,8 @@ import pytorch_lightning as pl import torch.nn.functional as F import torch -# import custom lightning_models -from pytorch_modules.lightning_models.simple_mnist_classifier.models import * +# import custom architectures +from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier class LitModel(pl.LightningModule): @@ -16,6 +16,9 @@ class LitModel(pl.LightningModule): This class enables you to specify what happens during training, validation and test step. You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training. + + To learn how to create lightning models visit: + https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html """ def __init__(self, hparams: dict = None): diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 22d29e3..43e182e 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,5 +1,5 @@ # pytorch lightning imports -from pytorch_lightning.loggers import WandbLogger +from pytorch_lightning.loggers import WandbLogger, CometLogger from pytorch_lightning.profiler import SimpleProfiler import pytorch_lightning as pl @@ -287,3 +287,11 @@ def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: """Initialize tensorboard logger""" # TODO return None + + +def init_comet_logger(project_config: dict, + run_config: dict, + model: pl.LightningModule, + datamodule: pl.LightningDataModule) -> pl.loggers.CometLogger: + + comet_logger = CometLogger() diff --git a/project/inference/predict_example.py b/project/template_utils/predict_example.py similarity index 100% rename from project/inference/predict_example.py rename to project/template_utils/predict_example.py diff --git a/project_config.yaml b/project_config.yaml new file mode 100644 index 0000000..ef8f9c6 --- /dev/null +++ b/project_config.yaml @@ -0,0 +1,54 @@ +# default args passed to Lightning Trainer on every run/experiment +# they will be combined with trainer args specified in experiment config +default_args: + num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + auto_select_gpus: True + num_sanity_val_steps: 3 + progress_bar_refresh_rate: 10 # refresh terminal every 10 batches + weights_summary: "top" # print model summary before training starts (alternatively "full") + + +# use profiler to print execution time profiling after training ends +profiler: + use_profiler: True + class: "pytorch_lightning.profiler.SimpleProfiler" + args: {} + + +loggers: + + # Comet logger config + comet: + use_comet: True + default_args: + api_key: "sadfhgadfhsdfhadgkajdgsdg" + project_name: "project_template_test" + extra_options: + log_optimizer_name: True + log_train_val_test_sizes: True + + # Weights&Biases logger config + wandb: + use_wandb: False + default_args: + project: "project_template_test" + entity: "" # 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 + extra_options: + log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) + log_optimizer_name: True + log_train_val_test_sizes: True + + # Tensorboard logger config + tensorboard: + use_tensorboard: False + default_args: {} + + +# path to data folder (either absolute or relative to placement of 'train.py' file) +data_dir: "data/" + + +# path to logs folder (either absolute or relative to placement of 'train.py' file) +logs_dir: "logs/" From fe81cbb304b63d9fdef764e4ee22137bc257dbbb Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 2 Jan 2021 21:39:43 +0100 Subject: [PATCH 04/15] configuration almost finished --- .../default_callbacks.yaml} | 0 .../default_datamodule.yaml} | 0 project/configs/experiment/xxx.yaml | 32 ++++++++++ project/configs/experiment/xxx2.yaml | 52 +++++++++++++++ .../mnist_experiments/advanced_conf.yaml | 63 ------------------- .../mnist_experiments/simple_conf.yaml | 25 -------- .../{project_config => }/logger/comet.yaml | 0 .../logger/tensorboard.yaml | 1 + .../{project_config => }/logger/wandb.yaml | 1 + .../default_model.yaml} | 0 project/configs/optimizer/adam.yaml | 1 + project/configs/project_config.yaml | 25 +++++--- .../trainer/default_trainer.yaml | 2 +- project/logs/.gitkeep | 0 project/test.py | 12 ++++ project_config.yaml | 54 ---------------- requirements.txt | 1 + 17 files changed, 117 insertions(+), 152 deletions(-) rename project/configs/{project_config/callbacks/mnist_callbacks.yaml => callbacks/default_callbacks.yaml} (100%) rename project/configs/{project_config/datamodule/mnist_datamodule.yaml => datamodule/default_datamodule.yaml} (100%) create mode 100644 project/configs/experiment/xxx.yaml create mode 100644 project/configs/experiment/xxx2.yaml delete mode 100644 project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml delete mode 100644 project/configs/experiment_configs/mnist_experiments/simple_conf.yaml rename project/configs/{project_config => }/logger/comet.yaml (100%) rename project/configs/{project_config => }/logger/tensorboard.yaml (75%) rename project/configs/{project_config => }/logger/wandb.yaml (96%) rename project/configs/{project_config/model/simple_mnist_classifier.yaml => model/default_model.yaml} (100%) create mode 100644 project/configs/optimizer/adam.yaml rename project/configs/{project_config => }/trainer/default_trainer.yaml (100%) delete mode 100644 project/logs/.gitkeep create mode 100644 project/test.py delete mode 100644 project_config.yaml diff --git a/project/configs/project_config/callbacks/mnist_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml similarity index 100% rename from project/configs/project_config/callbacks/mnist_callbacks.yaml rename to project/configs/callbacks/default_callbacks.yaml diff --git a/project/configs/project_config/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/default_datamodule.yaml similarity index 100% rename from project/configs/project_config/datamodule/mnist_datamodule.yaml rename to project/configs/datamodule/default_datamodule.yaml diff --git a/project/configs/experiment/xxx.yaml b/project/configs/experiment/xxx.yaml new file mode 100644 index 0000000..178d223 --- /dev/null +++ b/project/configs/experiment/xxx.yaml @@ -0,0 +1,32 @@ +# @package _global_ +# to execute this experiment run: +# python train.py +experiment=xxx + +defaults: + - override /trainer: default_trainer.yaml + - override /model: default_classifier.yaml + - override /datamodule: default_datamodule.yaml + - override /logger: comet.yaml + +pytorch_seed: 12345 + +trainer: + args: + max_epochs: 10 + +model: + class: "pytorch_modules.lightning_models.simple_mnist_classifier.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: + class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" + hparams: + batch_size: 32 + train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/experiment/xxx2.yaml b/project/configs/experiment/xxx2.yaml new file mode 100644 index 0000000..c2cf27c --- /dev/null +++ b/project/configs/experiment/xxx2.yaml @@ -0,0 +1,52 @@ +# @package _global_ +# to execute this experiment run: +# python train.py +experiment=xxx2 + +defaults: + - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder + - override /model: default_model.yaml # choose model from 'configs/model/' folder + - override /datamodule: default_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder + - override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder + - override /logger: comet.yaml # choose logger from 'configs/logger/' folder + +pytorch_seed: 12345 # pytorch seed for this experiment (also affects lightning random_split() method) + +trainer: + args: + min_epochs: 1 # train for at least this many epochs (denies early stopping) + max_epochs: 10 # train for maximum this many epochs + 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: 0.5 # perform validation twice per epoch + +model: + class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" + hparams: # you can add here any params you want and then access them in lightning model + lr: 0.001 + weight_decay: 0.00001 + 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: + class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" + hparams: # you can add here any params you want and then access them in lightning datamodule + batch_size: 64 + 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 + +logger: + args: # you can add here additional logger arguments specific for this experiment + tags: ["uwu", "best_model"] + +resume_training: # use this if you want to resume training from checkpoint + checkpoint_path: False # path to your checkpoint + wandb_run_id: False # you can add id of wandb run you want to resume but it's optional + comet_run_id: False # you can add id of comet run you want to resume but it's optional diff --git a/project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml b/project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml deleted file mode 100644 index 6e564d8..0000000 --- a/project/configs/experiment_configs/mnist_experiments/advanced_conf.yaml +++ /dev/null @@ -1,63 +0,0 @@ -# to execute this experiment run: -# python train.py --exp_conf configs/experiment/mnist_experiments/advanced_conf.yaml - - -# (optional section) -# pytorch seed for this experiment -# it also affects random_split() method used in mnist_datamodule.py -# overwrites default pytorch seed set in project_config.yaml -seed: 1234 - -# (required section) -trainer_args: - min_epochs: 1 # train for at least this many epochs (denies early stopping) - max_epochs: 10 # train for maximum this many epochs - 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: 0.5 # perform validation twice per epoch - -# (required section) -model: - load_from: - model_path: "pytorch_modules/lightning_models/simple_mnist_classifier.py" - model_class: "LitModel" - hparams: # you can add here any parameters you want and then read them in model - lr: 0.001 - weight_decay: 0.00001 - 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 - -# (required section) -datamodule: - load_from: - datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_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_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 - - -# (optional section) -# Weights&Biases logger args -# this will be combained with default wandb args set in project_config.yaml (overwrites repeating args) -wandb_args: - group: "" - job_type: "train" - tags: ["v2", "uwu"] - notes: "This is example run." - - -# (optional section) -# use this if you want to resume training from checkpoint -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/configs/experiment_configs/mnist_experiments/simple_conf.yaml b/project/configs/experiment_configs/mnist_experiments/simple_conf.yaml deleted file mode 100644 index 45fad18..0000000 --- a/project/configs/experiment_configs/mnist_experiments/simple_conf.yaml +++ /dev/null @@ -1,25 +0,0 @@ -# to execute this experiment run: -# python train.py --exp_conf configs/experiment/mnist_experiments/simple_conf.yaml - - -seed: 1234 - -trainer_args: - max_epochs: 10 - -model: - class: "pytorch_modules.lightning_models.simple_mnist_classifier.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: - class: "lightning_datamodules.mnist_datamodule.mnist_datamodule.MNISTDataModule" - hparams: - batch_size: 64 - train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/project_config/logger/comet.yaml b/project/configs/logger/comet.yaml similarity index 100% rename from project/configs/project_config/logger/comet.yaml rename to project/configs/logger/comet.yaml diff --git a/project/configs/project_config/logger/tensorboard.yaml b/project/configs/logger/tensorboard.yaml similarity index 75% rename from project/configs/project_config/logger/tensorboard.yaml rename to project/configs/logger/tensorboard.yaml index ad67a99..4defa66 100644 --- a/project/configs/project_config/logger/tensorboard.yaml +++ b/project/configs/logger/tensorboard.yaml @@ -1,3 +1,4 @@ +# @package _group_ # Tensorboard logger config args: {} diff --git a/project/configs/project_config/logger/wandb.yaml b/project/configs/logger/wandb.yaml similarity index 96% rename from project/configs/project_config/logger/wandb.yaml rename to project/configs/logger/wandb.yaml index ec03aec..db170a9 100644 --- a/project/configs/project_config/logger/wandb.yaml +++ b/project/configs/logger/wandb.yaml @@ -1,3 +1,4 @@ +# @package _group_ # Weights&Biases logger config args: diff --git a/project/configs/project_config/model/simple_mnist_classifier.yaml b/project/configs/model/default_model.yaml similarity index 100% rename from project/configs/project_config/model/simple_mnist_classifier.yaml rename to project/configs/model/default_model.yaml diff --git a/project/configs/optimizer/adam.yaml b/project/configs/optimizer/adam.yaml new file mode 100644 index 0000000..3a0ec6e --- /dev/null +++ b/project/configs/optimizer/adam.yaml @@ -0,0 +1 @@ +# @package _group_ diff --git a/project/configs/project_config.yaml b/project/configs/project_config.yaml index 4666265..cd240b8 100644 --- a/project/configs/project_config.yaml +++ b/project/configs/project_config.yaml @@ -1,14 +1,21 @@ +# @package _global_ + defaults: - - project_config/trainer: default_trainer -# - model: simple_mnist_classifier -# - datamodule: mnist_datamodule -# - logger: comet -# - callbacks: mnist_callbacks + - trainer: default_trainer.yaml + - model: default_model.yaml + - datamodule: default_datamodule.yaml + - callbacks: default_callbacks.yaml + - logger: comet.yaml -# path to data folder (either absolute or relative to placement of 'train.py' file) -data_dir: "data/" +paths: + data_dir: "data/" # path to data folder (either absolute or relative to placement of 'train.py' file) + logs_dir: "logs/" # path to logs folder (either absolute or relative to placement of 'train.py' file) -# path to logs folder (either absolute or relative to placement of 'train.py' file) -logs_dir: "logs/" +hydra: + run: + dir: ${paths.logs_dir}/hydra_logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} + sweep: + dir: ${paths.logs_dir}/hydra_logs/sweeps/${now:%Y-%m-%d_%H-%M-%S} + subdir: ${hydra.job.num} diff --git a/project/configs/project_config/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml similarity index 100% rename from project/configs/project_config/trainer/default_trainer.yaml rename to project/configs/trainer/default_trainer.yaml index 8b0487a..8a9f577 100644 --- a/project/configs/project_config/trainer/default_trainer.yaml +++ b/project/configs/trainer/default_trainer.yaml @@ -9,5 +9,5 @@ args: num_sanity_val_steps: 3 progress_bar_refresh_rate: 10 weights_summary: "top" - max_epochs: 100 profiler: "simple" # use profiler to print execution time profiling after training ends + max_epochs: 100 diff --git a/project/logs/.gitkeep b/project/logs/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/project/test.py b/project/test.py new file mode 100644 index 0000000..644443a --- /dev/null +++ b/project/test.py @@ -0,0 +1,12 @@ +from omegaconf import DictConfig, OmegaConf +import hydra.conf.hydra.output + + +@hydra.main(config_path="configs/", config_name="project_config.yaml") +def my_app(cfg: DictConfig) -> None: + # print(cfg) + print(OmegaConf.to_yaml(cfg)) + + +if __name__ == "__main__": + my_app() diff --git a/project_config.yaml b/project_config.yaml deleted file mode 100644 index ef8f9c6..0000000 --- a/project_config.yaml +++ /dev/null @@ -1,54 +0,0 @@ -# default args passed to Lightning Trainer on every run/experiment -# they will be combined with trainer args specified in experiment config -default_args: - num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only - auto_select_gpus: True - num_sanity_val_steps: 3 - progress_bar_refresh_rate: 10 # refresh terminal every 10 batches - weights_summary: "top" # print model summary before training starts (alternatively "full") - - -# use profiler to print execution time profiling after training ends -profiler: - use_profiler: True - class: "pytorch_lightning.profiler.SimpleProfiler" - args: {} - - -loggers: - - # Comet logger config - comet: - use_comet: True - default_args: - api_key: "sadfhgadfhsdfhadgkajdgsdg" - project_name: "project_template_test" - extra_options: - log_optimizer_name: True - log_train_val_test_sizes: True - - # Weights&Biases logger config - wandb: - use_wandb: False - default_args: - project: "project_template_test" - entity: "" # 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 - extra_options: - log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) - log_optimizer_name: True - log_train_val_test_sizes: True - - # Tensorboard logger config - tensorboard: - use_tensorboard: False - default_args: {} - - -# path to data folder (either absolute or relative to placement of 'train.py' file) -data_dir: "data/" - - -# path to logs folder (either absolute or relative to placement of 'train.py' file) -logs_dir: "logs/" diff --git a/requirements.txt b/requirements.txt index aa3d615..fef496e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,6 +2,7 @@ torch>=1.7.0 torchvision>=0.8.1 torchaudio>=0.7.0 pytorch-lightning>=1.0.8 +hydra-core wandb>=0.10.12 PyYAML>=5.3.1 scikit-learn>=0.23.2 From 9cffc61c20a3b67362fb3e324d0c64ef3fc7b848 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Mon, 4 Jan 2021 02:11:16 +0100 Subject: [PATCH 05/15] improve experiment configs --- .../configs/callbacks/mnist_callbacks.yaml | 0 .../datamodule/default_datamodule.yaml | 12 --- .../configs/datamodule/mnist_datamodule.yaml | 7 ++ project/configs/experiment/f/xxx.yaml | 33 +++++++ .../experiment/{xxx.yaml => f/xxx2.yaml} | 11 ++- project/configs/experiment/f/xxx3.yaml | 31 +++++++ project/configs/experiment/xxx2.yaml | 29 ++++--- project/configs/logger/comet.yaml | 10 --- project/configs/logger/tensorboard.yaml | 6 -- project/configs/logger/wandb.yaml | 13 --- project/configs/loggers/all_loggers.yaml | 9 ++ project/configs/loggers/comet.yaml | 13 +++ project/configs/loggers/csv_logger.yaml | 9 ++ project/configs/loggers/neptune.yaml | 11 +++ project/configs/loggers/tensorboard.yaml | 9 ++ project/configs/loggers/wandb.yaml | 16 ++++ project/configs/model/modelX.yaml | 6 ++ ...odel.yaml => simple_mnist_classifier.yaml} | 1 + .../configs/optimizer/_default_optimizer.yaml | 0 project/configs/project_config.yaml | 6 +- .../simple_mnist_classifier.py | 6 +- project/template_utils/initializers.py | 85 +++++++------------ project/test.py | 2 + project/train.py | 1 - setup.py | 2 +- 25 files changed, 204 insertions(+), 124 deletions(-) create mode 100644 project/configs/callbacks/mnist_callbacks.yaml delete mode 100644 project/configs/datamodule/default_datamodule.yaml create mode 100644 project/configs/datamodule/mnist_datamodule.yaml create mode 100644 project/configs/experiment/f/xxx.yaml rename project/configs/experiment/{xxx.yaml => f/xxx2.yaml} (55%) create mode 100644 project/configs/experiment/f/xxx3.yaml delete mode 100644 project/configs/logger/comet.yaml delete mode 100644 project/configs/logger/tensorboard.yaml delete mode 100644 project/configs/logger/wandb.yaml create mode 100644 project/configs/loggers/all_loggers.yaml create mode 100644 project/configs/loggers/comet.yaml create mode 100644 project/configs/loggers/csv_logger.yaml create mode 100644 project/configs/loggers/neptune.yaml create mode 100644 project/configs/loggers/tensorboard.yaml create mode 100644 project/configs/loggers/wandb.yaml create mode 100644 project/configs/model/modelX.yaml rename project/configs/model/{default_model.yaml => simple_mnist_classifier.yaml} (99%) create mode 100644 project/configs/optimizer/_default_optimizer.yaml diff --git a/project/configs/callbacks/mnist_callbacks.yaml b/project/configs/callbacks/mnist_callbacks.yaml new file mode 100644 index 0000000..e69de29 diff --git a/project/configs/datamodule/default_datamodule.yaml b/project/configs/datamodule/default_datamodule.yaml deleted file mode 100644 index d0ec339..0000000 --- a/project/configs/datamodule/default_datamodule.yaml +++ /dev/null @@ -1,12 +0,0 @@ -# @package _group_ - -class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" - -hparams: - lr: 0.001 - weight_decay: 0.00001 - input_size: 784 - output_size: 10 - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml new file mode 100644 index 0000000..272ffba --- /dev/null +++ b/project/configs/datamodule/mnist_datamodule.yaml @@ -0,0 +1,7 @@ +# @package _group_ + +class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" + +hparams: + batch_size: 64 + train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/f/xxx.yaml b/project/configs/experiment/f/xxx.yaml new file mode 100644 index 0000000..3382e67 --- /dev/null +++ b/project/configs/experiment/f/xxx.yaml @@ -0,0 +1,33 @@ +# @package _global_ + +# to execute this experiment run: +# python train.py +experiment=xxx + +defaults: + - override /trainer: default_trainer.yaml + - override /model: null + - override /datamodule: null + - override /callbacks: default_callbacks.yaml + +pytorch_seed: 12345 + +trainer: + args: + max_epochs: 10 + +model: + class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel + args: + lr: 0.001 + weight_decay: 0.00001 + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + +datamodule: + class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule + args: + batch_size: 32 + train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/xxx.yaml b/project/configs/experiment/f/xxx2.yaml similarity index 55% rename from project/configs/experiment/xxx.yaml rename to project/configs/experiment/f/xxx2.yaml index 178d223..ef07d9c 100644 --- a/project/configs/experiment/xxx.yaml +++ b/project/configs/experiment/f/xxx2.yaml @@ -1,12 +1,11 @@ # @package _global_ + # to execute this experiment run: # python train.py +experiment=xxx defaults: - override /trainer: default_trainer.yaml - - override /model: default_classifier.yaml - - override /datamodule: default_datamodule.yaml - - override /logger: comet.yaml + - override /logger: wandb.yaml pytorch_seed: 12345 @@ -15,7 +14,7 @@ trainer: max_epochs: 10 model: - class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" + class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel hparams: lr: 0.001 weight_decay: 0.00001 @@ -26,7 +25,7 @@ model: lin3_size: 128 datamodule: - class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" + class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule hparams: batch_size: 32 - train_val_test_split: [55_000, 5_000, 10_000] + train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/f/xxx3.yaml b/project/configs/experiment/f/xxx3.yaml new file mode 100644 index 0000000..ef07d9c --- /dev/null +++ b/project/configs/experiment/f/xxx3.yaml @@ -0,0 +1,31 @@ +# @package _global_ + +# to execute this experiment run: +# python train.py +experiment=xxx + +defaults: + - override /trainer: default_trainer.yaml + - override /logger: wandb.yaml + +pytorch_seed: 12345 + +trainer: + args: + max_epochs: 10 + +model: + class: pytorch_modules.lightning_models.simple_mnist_classifier.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: + class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule + hparams: + batch_size: 32 + train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/xxx2.yaml b/project/configs/experiment/xxx2.yaml index c2cf27c..2200c08 100644 --- a/project/configs/experiment/xxx2.yaml +++ b/project/configs/experiment/xxx2.yaml @@ -1,13 +1,13 @@ # @package _global_ + # to execute this experiment run: # python train.py +experiment=xxx2 defaults: - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder - - override /model: default_model.yaml # choose model from 'configs/model/' folder - - override /datamodule: default_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder + - override /model: null # choose model from 'configs/model/' folder + - override /datamodule: null # choose datamodule from 'configs/datamodule/' folder - override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder - - override /logger: comet.yaml # choose logger from 'configs/logger/' folder pytorch_seed: 12345 # pytorch seed for this experiment (also affects lightning random_split() method) @@ -24,8 +24,8 @@ trainer: val_check_interval: 0.5 # perform validation twice per epoch model: - class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" - hparams: # you can add here any params you want and then access them in lightning model + class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel + args: # you can add here any params you want and then access them in lightning model lr: 0.001 weight_decay: 0.00001 input_size: 784 # img size is 1*28*28 @@ -35,18 +35,21 @@ model: lin3_size: 128 datamodule: - class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" - hparams: # you can add here any params you want and then access them in lightning datamodule + class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule + args: # you can add here any params you want and then access them in lightning datamodule batch_size: 64 - train_val_test_split: [55_000, 5_000, 10_000] + 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 -logger: - args: # you can add here additional logger arguments specific for this experiment - tags: ["uwu", "best_model"] +loggers: + wandb: + args: # you can add here additional loggers arguments specific for this experiment + tags: ["uwu", "best_model"] + comet: + args: + tags: ["uwu", "best_model"] resume_training: # use this if you want to resume training from checkpoint checkpoint_path: False # path to your checkpoint - wandb_run_id: False # you can add id of wandb run you want to resume but it's optional - comet_run_id: False # you can add id of comet run you want to resume but it's optional + logger_run_id: False # loggers experiment id that you want to resume (optional) diff --git a/project/configs/logger/comet.yaml b/project/configs/logger/comet.yaml deleted file mode 100644 index 83182f2..0000000 --- a/project/configs/logger/comet.yaml +++ /dev/null @@ -1,10 +0,0 @@ -# @package _group_ -# Comet logger config - -args: - api_key: "sadfhgadfhsdfhadgkajdgsdg" - project_name: "project_template_test" - -extra_options: - log_optimizer_name: True - log_train_val_test_sizes: True diff --git a/project/configs/logger/tensorboard.yaml b/project/configs/logger/tensorboard.yaml deleted file mode 100644 index 4defa66..0000000 --- a/project/configs/logger/tensorboard.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# @package _group_ -# Tensorboard logger config - -args: {} - -extra_options: {} diff --git a/project/configs/logger/wandb.yaml b/project/configs/logger/wandb.yaml deleted file mode 100644 index db170a9..0000000 --- a/project/configs/logger/wandb.yaml +++ /dev/null @@ -1,13 +0,0 @@ -# @package _group_ -# Weights&Biases logger config - -args: - project: "project_template_test" - entity: "" # 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 - -extra_options: - log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models) - log_optimizer_name: True - log_train_val_test_sizes: True diff --git a/project/configs/loggers/all_loggers.yaml b/project/configs/loggers/all_loggers.yaml new file mode 100644 index 0000000..2988033 --- /dev/null +++ b/project/configs/loggers/all_loggers.yaml @@ -0,0 +1,9 @@ +# @package _group_ + +# train with all loggers at once +defaults: + - comet + - csv_logger + - neptune + - tensorboard + - wandb diff --git a/project/configs/loggers/comet.yaml b/project/configs/loggers/comet.yaml new file mode 100644 index 0000000..69f6964 --- /dev/null +++ b/project/configs/loggers/comet.yaml @@ -0,0 +1,13 @@ +# @package _group_ + +# Comet loggers config +comet: + class: pytorch_lightning.loggers.CometLogger + + args: + api_key: ??? + project_name: "project_template_test" + + extra_options: + log_optimizer_name: True + log_train_val_test_sizes: True diff --git a/project/configs/loggers/csv_logger.yaml b/project/configs/loggers/csv_logger.yaml new file mode 100644 index 0000000..8e5739b --- /dev/null +++ b/project/configs/loggers/csv_logger.yaml @@ -0,0 +1,9 @@ +# @package _group_ + +# default loggers is just lightning CSVLogger which doesn't require any additional dependencies +csv_logger: + class: pytorch_lightning.loggers.CSVLogger + + args: {} + + extra_options: {} diff --git a/project/configs/loggers/neptune.yaml b/project/configs/loggers/neptune.yaml new file mode 100644 index 0000000..78aeb1e --- /dev/null +++ b/project/configs/loggers/neptune.yaml @@ -0,0 +1,11 @@ +# @package _group_ + +# Neptune loggers config +neptune: + class: pytorch_lightning.loggers.NeptuneLogger + + args: {} + + extra_options: + log_optimizer_name: True + log_train_val_test_sizes: True diff --git a/project/configs/loggers/tensorboard.yaml b/project/configs/loggers/tensorboard.yaml new file mode 100644 index 0000000..89f11b5 --- /dev/null +++ b/project/configs/loggers/tensorboard.yaml @@ -0,0 +1,9 @@ +# @package _group_ + +# Tensorboard loggers config +tensorboard: + class: pytorch_lightning.loggers.TensorboardLogger + + args: {} + + extra_options: {} diff --git a/project/configs/loggers/wandb.yaml b/project/configs/loggers/wandb.yaml new file mode 100644 index 0000000..ea61559 --- /dev/null +++ b/project/configs/loggers/wandb.yaml @@ -0,0 +1,16 @@ +# @package _group_ + +# Weights&Biases loggers config +wandb: + class: pytorch_lightning.loggers.WandbLogger + + args: + project: "project_template_test" + entity: "" # 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 + + extra_options: + log_gradients: False # set True to log gradient histograms (avoid this for very big models) + log_optimizer_name: True + log_train_val_test_sizes: True diff --git a/project/configs/model/modelX.yaml b/project/configs/model/modelX.yaml new file mode 100644 index 0000000..22a8275 --- /dev/null +++ b/project/configs/model/modelX.yaml @@ -0,0 +1,6 @@ +# @package _group_ + +class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" + +hparams: + YYYYYYY: XXXXXXXXXXXXXXXXXXX diff --git a/project/configs/model/default_model.yaml b/project/configs/model/simple_mnist_classifier.yaml similarity index 99% rename from project/configs/model/default_model.yaml rename to project/configs/model/simple_mnist_classifier.yaml index f2c3453..1f2c2c5 100644 --- a/project/configs/model/default_model.yaml +++ b/project/configs/model/simple_mnist_classifier.yaml @@ -10,3 +10,4 @@ hparams: lin1_size: 256 lin2_size: 256 lin3_size: 128 + diff --git a/project/configs/optimizer/_default_optimizer.yaml b/project/configs/optimizer/_default_optimizer.yaml new file mode 100644 index 0000000..e69de29 diff --git a/project/configs/project_config.yaml b/project/configs/project_config.yaml index cd240b8..9b5f312 100644 --- a/project/configs/project_config.yaml +++ b/project/configs/project_config.yaml @@ -2,10 +2,10 @@ defaults: - trainer: default_trainer.yaml - - model: default_model.yaml - - datamodule: default_datamodule.yaml + - model: simple_mnist_classifier.yaml + - datamodule: mnist_datamodule.yaml - callbacks: default_callbacks.yaml - - logger: comet.yaml + - loggers: null paths: diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index 746ac64..356027e 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -21,11 +21,9 @@ class LitModel(pl.LightningModule): https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html """ - def __init__(self, hparams: dict = None): + def __init__(self, **kwargs): super().__init__() - - if hparams: - self.save_hyperparameters(hparams) + self.save_hyperparameters(kwargs) self.model = SimpleMNISTClassifier(hparams=self.hparams) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 43e182e..84e1b12 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,6 +1,4 @@ # pytorch lightning imports -from pytorch_lightning.loggers import WandbLogger, CometLogger -from pytorch_lightning.profiler import SimpleProfiler import pytorch_lightning as pl # normal imports @@ -11,82 +9,59 @@ import os # template utils imports from pytorch_lightning import callbacks as lightning_callbacks from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks +from pytorch_lightning.loggers import CSVLogger -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. - """ +def format_path(path: str, base_dir: str): + """Convert path to absolute relatively to base_dir and normalize it.""" + if not os.path.isabs(path): + path = os.path.join(base_dir, path) + return os.path.normpath(path) - 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"])) +def format_config_paths(config: dict, base_dir: str) -> dict: + config["paths"]["data_dir"] = format_path(config["paths"]["data_dir"], base_dir) + config["paths"]["logs_dir"] = format_path(config["paths"]["logs_dir"], base_dir) + return config - 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"])) +def load_object(obj_path): + obj_path, obj_name = obj_path.rsplit('.', 1) + module = importlib.import_module(obj_path) - return project_config, run_config + assert hasattr(module, obj_name), \ + f'Object `{obj_name}` cannot be loaded from `{obj_path}`.' + + return getattr(module, obj_name) def init_model(model_config: dict) -> pl.LightningModule: """ Load LightningModule from path specified in run config. """ + model_class = model_config["class"] + model_hparams = model_config["hparams"] - model_path = model_config["load_from"]["model_path"] - model_class = model_config["load_from"]["model_class"] - - 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 exist in file '{model_path}'" - - LitModel = getattr(lightning_module, model_class) - + LitModel = load_object(model_class) assert issubclass(LitModel, pl.LightningModule), \ - f"specified model class '{model_class}' is not a 'LightningModule' type" + f"Specified model class `{model_class}` is not a subclass of `LightningModule`." - model = LitModel(hparams=model_config["hparams"]) - - return model + return LitModel(hparams=model_hparams) def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule: """ Load LightningDataModule from path specified in run config. """ + datamodule_class = datamodule_config["class"] + datamodule_hparams = datamodule_config["hparams"] - datamodule_path = datamodule_config["load_from"]["datamodule_path"] - datamodule_class = datamodule_config["load_from"]["datamodule_class"] - - assert os.path.isfile(datamodule_path), f"incorrect datamodule path '{datamodule_path}'" - - spec = importlib.util.spec_from_file_location("lightning_datamodule", 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 exist in file '{datamodule_path}'" - - DataModule = getattr(lightning_module, datamodule_class) + DataModule = load_object(datamodule_class) assert issubclass(DataModule, pl.LightningDataModule), \ - f"specified datamodule class '{datamodule_class}' is not a 'LightningDataModule' type" + f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`" - datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"]) + datamodule = DataModule(data_dir=data_dir, hparams=datamodule_hparams) datamodule.prepare_data() datamodule.setup() @@ -129,7 +104,7 @@ def init_trainer(project_config: dict, # number of validation sanity checks num_sanity_val_steps=3, - # default log dir if no logger is found + # default log dir if no loggers is found default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"), # insert all other trainer args specified in run config @@ -215,7 +190,7 @@ def init_wandb_logger(project_config: dict, model: pl.LightningModule, datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger: """ - Initialize Weights&Biases logger. + Initialize Weights&Biases loggers. """ if "loggers" not in project_config or "wandb" not in project_config["loggers"]: @@ -284,7 +259,7 @@ def init_wandb_logger(project_config: dict, def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: - """Initialize tensorboard logger""" + """Initialize tensorboard loggers""" # TODO return None diff --git a/project/test.py b/project/test.py index 644443a..74e3b28 100644 --- a/project/test.py +++ b/project/test.py @@ -1,5 +1,7 @@ from omegaconf import DictConfig, OmegaConf import hydra.conf.hydra.output +from hydra.experimental import initialize, compose +import comet_ml @hydra.main(config_path="configs/", config_name="project_config.yaml") diff --git a/project/train.py b/project/train.py index e9c00d4..1699302 100644 --- a/project/train.py +++ b/project/train.py @@ -6,7 +6,6 @@ import torch # normal imports from argparse import ArgumentParser from typing import List -import pprint import yaml import os diff --git a/setup.py b/setup.py index 9fa9614..9a89f33 100644 --- a/setup.py +++ b/setup.py @@ -9,6 +9,6 @@ setup( author='', author_email='', url='https://github.com/kinoai/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK - install_requires=['pytorch-lightning', 'PyYAML'], + install_requires=['pytorch-lightning'], packages=find_packages(), ) From 610117f161f0b93aceb2a76d3609079c925f5527 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Wed, 6 Jan 2021 02:49:30 +0100 Subject: [PATCH 06/15] training with hydra works --- README.md | 2 +- .../{project_config.yaml => config.yaml} | 8 +- .../configs/datamodule/mnist_datamodule.yaml | 5 +- .../{xxx2.yaml => exp_example_advanced.yaml} | 32 ++- .../experiment/exp_example_simple.yaml | 36 +++ project/configs/experiment/f/xxx.yaml | 33 --- project/configs/experiment/f/xxx2.yaml | 31 --- project/configs/experiment/f/xxx3.yaml | 31 --- project/configs/loggers/all_loggers.yaml | 3 +- project/configs/loggers/comet.yaml | 7 +- project/configs/loggers/csv_logger.yaml | 5 +- project/configs/loggers/neptune.yaml | 11 - project/configs/loggers/tensorboard.yaml | 5 +- project/configs/loggers/wandb.yaml | 29 +- project/configs/model/modelX.yaml | 6 - .../model/simple_mnist_classifier.yaml | 3 +- .../configs/optimizer/_default_optimizer.yaml | 0 project/configs/optimizer/adam.yaml | 5 + project/configs/trainer/debug_trainer.yaml | 17 ++ project/configs/trainer/default_trainer.yaml | 7 +- .../lightning_callbacks/wandb_callbacks.py | 2 +- .../lightning_datamodules/mnist_datamodule.py | 16 +- .../simple_mnist_classifier.py | 14 +- project/template_utils/initializers.py | 259 ++++++------------ project/template_utils/predict_example.py | 2 + project/train.py | 107 ++------ requirements.txt | 1 - 27 files changed, 247 insertions(+), 430 deletions(-) rename project/configs/{project_config.yaml => config.yaml} (61%) rename project/configs/experiment/{xxx2.yaml => exp_example_advanced.yaml} (66%) create mode 100644 project/configs/experiment/exp_example_simple.yaml delete mode 100644 project/configs/experiment/f/xxx.yaml delete mode 100644 project/configs/experiment/f/xxx2.yaml delete mode 100644 project/configs/experiment/f/xxx3.yaml delete mode 100644 project/configs/loggers/neptune.yaml delete mode 100644 project/configs/model/modelX.yaml delete mode 100644 project/configs/optimizer/_default_optimizer.yaml create mode 100644 project/configs/trainer/debug_trainer.yaml diff --git a/README.md b/README.md index 22247af..1da4dc5 100644 --- a/README.md +++ b/README.md @@ -203,7 +203,7 @@ python train.py --no_wandb --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST Or you can train model with Weights&Biases logging ```yaml -# set project and entity names in project/project_config.yaml +# set project and entity names in project/config.yaml loggers: wandb: project: "your_project_name" diff --git a/project/configs/project_config.yaml b/project/configs/config.yaml similarity index 61% rename from project/configs/project_config.yaml rename to project/configs/config.yaml index 9b5f312..a978184 100644 --- a/project/configs/project_config.yaml +++ b/project/configs/config.yaml @@ -4,14 +4,16 @@ defaults: - trainer: default_trainer.yaml - model: simple_mnist_classifier.yaml - datamodule: mnist_datamodule.yaml + - optimizer: adam.yaml - callbacks: default_callbacks.yaml - loggers: null +seeds: + pytorch_seed: 12345 paths: - data_dir: "data/" # path to data folder (either absolute or relative to placement of 'train.py' file) - logs_dir: "logs/" # path to logs folder (either absolute or relative to placement of 'train.py' file) - + data_dir: "data" # path to data folder (either absolute or relative to placement of 'train.py' file) + logs_dir: "logs" # path to logs folder (either absolute or relative to placement of 'train.py' file) hydra: run: diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml index 272ffba..7628e2c 100644 --- a/project/configs/datamodule/mnist_datamodule.yaml +++ b/project/configs/datamodule/mnist_datamodule.yaml @@ -1,7 +1,6 @@ # @package _group_ class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" - -hparams: +args: batch_size: 64 - train_val_test_split: (55_000, 5_000, 10_000) + train_val_test_split: [55_000, 5_000, 10_000] diff --git a/project/configs/experiment/xxx2.yaml b/project/configs/experiment/exp_example_advanced.yaml similarity index 66% rename from project/configs/experiment/xxx2.yaml rename to project/configs/experiment/exp_example_advanced.yaml index 2200c08..e9bc170 100644 --- a/project/configs/experiment/xxx2.yaml +++ b/project/configs/experiment/exp_example_advanced.yaml @@ -1,15 +1,17 @@ # @package _global_ # to execute this experiment run: -# python train.py +experiment=xxx2 +# python train.py +experiment=exp_example_advanced defaults: - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder - - override /model: null # choose model from 'configs/model/' folder - - override /datamodule: null # choose datamodule from 'configs/datamodule/' 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 /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder -pytorch_seed: 12345 # pytorch seed for this experiment (also affects lightning random_split() method) +seeds: + pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule) trainer: args: @@ -18,16 +20,14 @@ trainer: 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_train_batches: 0.6 # train on 60% of training data + 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 model: - class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel - args: # you can add here any params you want and then access them in lightning model - lr: 0.001 - weight_decay: 0.00001 + args: # you can add here any params you want and then access them in lightning model input_size: 784 # img size is 1*28*28 output_size: 10 # there are 10 digit classes lin1_size: 256 @@ -35,21 +35,23 @@ model: lin3_size: 128 datamodule: - class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule args: # you can add here any params you want and then access them in lightning datamodule batch_size: 64 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 +optimizer: + args: + lr: 0.001 + weight_decay: 0.00001 + loggers: wandb: args: # you can add here additional loggers arguments specific for this experiment tags: ["uwu", "best_model"] + notes: "" + group: "" comet: args: tags: ["uwu", "best_model"] - -resume_training: # use this if you want to resume training from checkpoint - checkpoint_path: False # path to your checkpoint - logger_run_id: False # loggers experiment id that you want to resume (optional) diff --git a/project/configs/experiment/exp_example_simple.yaml b/project/configs/experiment/exp_example_simple.yaml new file mode 100644 index 0000000..5eed61c --- /dev/null +++ b/project/configs/experiment/exp_example_simple.yaml @@ -0,0 +1,36 @@ +# @package _global_ + +# to execute this experiment run: +# python train.py +experiment=exp_example_simple + +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 /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder + +seeds: + pytorch_seed: 12345 + +trainer: + args: + max_epochs: 10 + +model: + args: + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + +datamodule: + args: + batch_size: 32 + train_val_test_split: (55_000, 5_000, 10_000) + +optimizer: + args: + lr: 0.001 + weight_decay: 0.00001 diff --git a/project/configs/experiment/f/xxx.yaml b/project/configs/experiment/f/xxx.yaml deleted file mode 100644 index 3382e67..0000000 --- a/project/configs/experiment/f/xxx.yaml +++ /dev/null @@ -1,33 +0,0 @@ -# @package _global_ - -# to execute this experiment run: -# python train.py +experiment=xxx - -defaults: - - override /trainer: default_trainer.yaml - - override /model: null - - override /datamodule: null - - override /callbacks: default_callbacks.yaml - -pytorch_seed: 12345 - -trainer: - args: - max_epochs: 10 - -model: - class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel - args: - lr: 0.001 - weight_decay: 0.00001 - input_size: 784 - output_size: 10 - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 - -datamodule: - class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule - args: - batch_size: 32 - train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/f/xxx2.yaml b/project/configs/experiment/f/xxx2.yaml deleted file mode 100644 index ef07d9c..0000000 --- a/project/configs/experiment/f/xxx2.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# @package _global_ - -# to execute this experiment run: -# python train.py +experiment=xxx - -defaults: - - override /trainer: default_trainer.yaml - - override /logger: wandb.yaml - -pytorch_seed: 12345 - -trainer: - args: - max_epochs: 10 - -model: - class: pytorch_modules.lightning_models.simple_mnist_classifier.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: - class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule - hparams: - batch_size: 32 - train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/experiment/f/xxx3.yaml b/project/configs/experiment/f/xxx3.yaml deleted file mode 100644 index ef07d9c..0000000 --- a/project/configs/experiment/f/xxx3.yaml +++ /dev/null @@ -1,31 +0,0 @@ -# @package _global_ - -# to execute this experiment run: -# python train.py +experiment=xxx - -defaults: - - override /trainer: default_trainer.yaml - - override /logger: wandb.yaml - -pytorch_seed: 12345 - -trainer: - args: - max_epochs: 10 - -model: - class: pytorch_modules.lightning_models.simple_mnist_classifier.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: - class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule - hparams: - batch_size: 32 - train_val_test_split: (55_000, 5_000, 10_000) diff --git a/project/configs/loggers/all_loggers.yaml b/project/configs/loggers/all_loggers.yaml index 2988033..a866cf8 100644 --- a/project/configs/loggers/all_loggers.yaml +++ b/project/configs/loggers/all_loggers.yaml @@ -1,9 +1,8 @@ # @package _group_ -# train with all loggers at once +# Train with all loggers at once defaults: - comet - csv_logger - - neptune - tensorboard - wandb diff --git a/project/configs/loggers/comet.yaml b/project/configs/loggers/comet.yaml index 69f6964..86aac49 100644 --- a/project/configs/loggers/comet.yaml +++ b/project/configs/loggers/comet.yaml @@ -1,13 +1,8 @@ # @package _group_ -# Comet loggers config +# Comet logger config comet: class: pytorch_lightning.loggers.CometLogger - args: api_key: ??? project_name: "project_template_test" - - extra_options: - log_optimizer_name: True - log_train_val_test_sizes: True diff --git a/project/configs/loggers/csv_logger.yaml b/project/configs/loggers/csv_logger.yaml index 8e5739b..71ac7f9 100644 --- a/project/configs/loggers/csv_logger.yaml +++ b/project/configs/loggers/csv_logger.yaml @@ -1,9 +1,6 @@ # @package _group_ -# default loggers is just lightning CSVLogger which doesn't require any additional dependencies +# Csv logger config csv_logger: class: pytorch_lightning.loggers.CSVLogger - args: {} - - extra_options: {} diff --git a/project/configs/loggers/neptune.yaml b/project/configs/loggers/neptune.yaml deleted file mode 100644 index 78aeb1e..0000000 --- a/project/configs/loggers/neptune.yaml +++ /dev/null @@ -1,11 +0,0 @@ -# @package _group_ - -# Neptune loggers config -neptune: - class: pytorch_lightning.loggers.NeptuneLogger - - args: {} - - extra_options: - log_optimizer_name: True - log_train_val_test_sizes: True diff --git a/project/configs/loggers/tensorboard.yaml b/project/configs/loggers/tensorboard.yaml index 89f11b5..4ce390e 100644 --- a/project/configs/loggers/tensorboard.yaml +++ b/project/configs/loggers/tensorboard.yaml @@ -1,9 +1,6 @@ # @package _group_ -# Tensorboard loggers config +# Tensorboard logger config tensorboard: class: pytorch_lightning.loggers.TensorboardLogger - args: {} - - extra_options: {} diff --git a/project/configs/loggers/wandb.yaml b/project/configs/loggers/wandb.yaml index ea61559..51d4d16 100644 --- a/project/configs/loggers/wandb.yaml +++ b/project/configs/loggers/wandb.yaml @@ -1,16 +1,27 @@ # @package _group_ -# Weights&Biases loggers config +# Weights&Biases logger config wandb: class: pytorch_lightning.loggers.WandbLogger - args: project: "project_template_test" - entity: "" # 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: "" # change to your username or name of your team on wandb + offline: False # set True to store all logs only locally + job_type: "train" + save_dir: ${paths.logs_dir} - extra_options: - log_gradients: False # set True to log gradient histograms (avoid this for very big models) - log_optimizer_name: True - log_train_val_test_sizes: True + # some extra things which will be logged by the environment + extra_logs: + watch_model: True # make wandb watch model + log_gradients: False # log gradient histograms (avoid this for very big models) + + log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset + + log_model_args: True # log + log_datamodule_args: True # log + log_optimizer_args: True # log + log_trainer_args: False # log + + log_model_class_name: True + log_datamodule_class_name: True + log_optimizer_class_name: True diff --git a/project/configs/model/modelX.yaml b/project/configs/model/modelX.yaml deleted file mode 100644 index 22a8275..0000000 --- a/project/configs/model/modelX.yaml +++ /dev/null @@ -1,6 +0,0 @@ -# @package _group_ - -class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" - -hparams: - YYYYYYY: XXXXXXXXXXXXXXXXXXX diff --git a/project/configs/model/simple_mnist_classifier.yaml b/project/configs/model/simple_mnist_classifier.yaml index 1f2c2c5..bcdd393 100644 --- a/project/configs/model/simple_mnist_classifier.yaml +++ b/project/configs/model/simple_mnist_classifier.yaml @@ -1,8 +1,7 @@ # @package _group_ class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel" - -hparams: +args: lr: 0.001 weight_decay: 0.00001 input_size: 784 diff --git a/project/configs/optimizer/_default_optimizer.yaml b/project/configs/optimizer/_default_optimizer.yaml deleted file mode 100644 index e69de29..0000000 diff --git a/project/configs/optimizer/adam.yaml b/project/configs/optimizer/adam.yaml index 3a0ec6e..f325327 100644 --- a/project/configs/optimizer/adam.yaml +++ b/project/configs/optimizer/adam.yaml @@ -1 +1,6 @@ # @package _group_ + +class: torch.optim.Adam +args: + lr: 0.001 + weight_decay: 0.000001 diff --git a/project/configs/trainer/debug_trainer.yaml b/project/configs/trainer/debug_trainer.yaml new file mode 100644 index 0000000..dae0ecb --- /dev/null +++ b/project/configs/trainer/debug_trainer.yaml @@ -0,0 +1,17 @@ +# @package _group_ + +# trainer args for debugging model +args: + gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + auto_select_gpus: True + + fast_dev_run: True + limit_train_batches: 1.0 + limit_val_batches: 1.0 + limit_test_batches: 1.0 + val_check_interval: 1.0 + profiler: "simple" # use profiler to print execution time profiling after training ends + + progress_bar_refresh_rate: 10 + weights_summary: "top" + default_root_dir: ${paths.logs_dir}/lightning_logs diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml index 8a9f577..7e706af 100644 --- a/project/configs/trainer/default_trainer.yaml +++ b/project/configs/trainer/default_trainer.yaml @@ -4,10 +4,9 @@ # they will be combined with trainer args specified in experiment config # (if the argument repeats in experiment config, then it will override the one set here) args: - num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + 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: "top" - profiler: "simple" # use profiler to print execution time profiling after training ends - max_epochs: 100 + progress_bar_refresh_rate: 10 + default_root_dir: ${paths.logs_dir}/lightning_logs diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 70f54de..15bb7c8 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -165,7 +165,7 @@ class SaveCodeToWandbCallback(Callback): "template_utils/custom_callbacks.py", "template_utils/initializers.py", "train.py", - "project_config.yaml", + "config.yaml", "run_configs.yaml", ] diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py index 6978c53..df351b1 100644 --- a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py +++ b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py @@ -8,22 +8,22 @@ 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 path to datamodule should be specified in your run config. + The 'args' dict contains datamodule args specified in config. To learn how to create datamodules visit: https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html """ - def __init__(self, data_dir: str, hparams: dict): + def __init__(self, data_dir, **args): super().__init__() - self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml + self.data_dir = data_dir + "/MNIST" # data_dir is specified in config.yaml - self.batch_size = hparams.get("batch_size") or 64 - 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 + self.batch_size = args.get("batch_size") or 64 + self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000] + self.num_workers = args.get("num_workers") or 1 + self.pin_memory = args.get("pin_memory") or False self.transforms = transforms.ToTensor() diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index 356027e..17edaa1 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -2,6 +2,7 @@ from sklearn.metrics import accuracy_score import pytorch_lightning as pl import torch.nn.functional as F import torch +from template_utils.initializers import init_optimizer # import custom architectures from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier @@ -9,10 +10,10 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier class LitModel(pl.LightningModule): """ - This is example of lightning model for MNIST digits classification. + This is example of lightning model for MNIST classification. The path to model should be specified in your run config. (run_configs.yaml) - The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml) + The 'hparams' dict contains model args specified in config. (run_configs.yaml) This class enables you to specify what happens during training, validation and test step. You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training. @@ -21,11 +22,12 @@ class LitModel(pl.LightningModule): https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html """ - def __init__(self, **kwargs): + def __init__(self, optimizer_config, **hparams): super().__init__() - self.save_hyperparameters(kwargs) + self.optimizer_config = optimizer_config + self.save_hyperparameters(hparams) - self.model = SimpleMNISTClassifier(hparams=self.hparams) + self.model = SimpleMNISTClassifier(hparams=hparams) def forward(self, x): return self.model(x) @@ -77,4 +79,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 init_optimizer(optimizer_config=self.optimizer_config, model=self) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 84e1b12..148adbc 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -7,9 +7,8 @@ import importlib.util import os # template utils imports -from pytorch_lightning import callbacks as lightning_callbacks -from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks -from pytorch_lightning.loggers import CSVLogger +from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger +import torch def format_path(path: str, base_dir: str): @@ -28,245 +27,161 @@ def format_config_paths(config: dict, base_dir: str) -> dict: def load_object(obj_path): obj_path, obj_name = obj_path.rsplit('.', 1) module = importlib.import_module(obj_path) - assert hasattr(module, obj_name), \ f'Object `{obj_name}` cannot be loaded from `{obj_path}`.' - return getattr(module, obj_name) -def init_model(model_config: dict) -> pl.LightningModule: +def init_object(obj_path, args): + return load_object(obj_path)(**args) + + +def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule: """ - Load LightningModule from path specified in run config. + Load LightningModule from path specified in config. """ model_class = model_config["class"] - model_hparams = model_config["hparams"] - + model_args = model_config["args"] LitModel = load_object(model_class) assert issubclass(LitModel, pl.LightningModule), \ f"Specified model class `{model_class}` is not a subclass of `LightningModule`." - - return LitModel(hparams=model_hparams) + return LitModel(optimizer_config, **model_args) def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule: """ - Load LightningDataModule from path specified in run config. + Load LightningDataModule from path specified config. """ datamodule_class = datamodule_config["class"] - datamodule_hparams = datamodule_config["hparams"] - + datamodule_args = datamodule_config["args"] DataModule = load_object(datamodule_class) - assert issubclass(DataModule, pl.LightningDataModule), \ f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`" - - datamodule = DataModule(data_dir=data_dir, hparams=datamodule_hparams) + datamodule = DataModule(data_dir=data_dir, **datamodule_args) datamodule.prepare_data() datamodule.setup() - return datamodule -def init_trainer(project_config: dict, - run_config: dict, +def init_optimizer(optimizer_config, model): + optimizer_class = optimizer_config["class"] + optimizer_args = optimizer_config["args"] + Optim = load_object(optimizer_class) + assert issubclass(Optim, torch.optim.Optimizer), \ + f"Specified optimizer class `{optimizer_class}` is not a subclass of `torch.optim.Optimizer`." + return Optim(model.parameters(), **optimizer_args) + + +def init_trainer(trainer_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 lightning_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 loggers is found - default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"), - - # insert all other trainer args specified in run config - **run_config["trainer"]["args"] + logger=loggers, + **trainer_config["args"] ) - return trainer -def init_callbacks(project_config: dict, - run_config: dict, - use_wandb: bool, - base_dir: str) -> List[pl.Callback]: +def init_callbacks(config: dict) -> List[pl.Callback]: """ - Initialize default lightning_callbacks and lightning_callbacks specified in run config. + Initialize callbacks specified in config. """ - - default_callbacks = project_config.get("default_callbacks", {}) - run_callbacks = run_config.get("lightning_callbacks", {}) - - # namespaces in which lightning_callbacks will be searched for - namespaces = [ - lightning_callbacks, - custom_callbacks, - wandb_callbacks, - ] - + callbacks_config = config.get("callbacks", None) callbacks = [] - 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] + if not callbacks_config: + return callbacks - 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 - ) - ) + for callback_name, callback_conf in callbacks_config.items(): + callback_class = callback_conf.get("class", None) + if callback_class: + callback_obj = init_object(callback_class, callback_conf.get("args", {})) + callbacks.append(callback_obj) return callbacks -def init_loggers(project_config: dict, - run_config: dict, +def init_loggers(config: dict, model: pl.LightningModule, - datamodule: pl.LightningDataModule, - use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]: + datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]: """ - Initialize loggers. + Initialize loggers specified in config. """ + loggers_config = config.get("loggers", None) 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) + + if not loggers_config: + return loggers + + for logger_name, logger_conf in loggers_config.items(): + logger_class = loggers_config.get("class", None) + if logger_class: + if logger_class == "pytorch_lightning.loggers.WandbLogger": + logger_obj = init_wandb(config, model, datamodule) + else: + logger_obj = init_object(logger_class, logger_conf.get("args", {})) + loggers.append(logger_obj) return loggers -def init_wandb_logger(project_config: dict, - run_config: dict, - model: pl.LightningModule, - datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger: +def init_wandb(config: dict, + model: pl.LightningModule, + datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger: """ - Initialize Weights&Biases loggers. + 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" - 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_config = config["loggers"]["wandb"] + wandb_logger = WandbLogger(**wandb_config["args"]) - 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=project_config["logs_dir"], - save_code=False - ) - - if not os.path.exists(project_config["logs_dir"]): - os.makedirs(project_config["logs_dir"]) + # make save dir path if it doesn't exists to prevent throwing errors by wandb + if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]): + os.makedirs(wandb_config["args"]["save_dir"]) if hasattr(model, 'model'): - if project_config["loggers"]["wandb"]["log_gradients"]: + if wandb_config["extra_options"]["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: - if project_config["loggers"]["wandb"]["log_gradients"]: + if wandb_config["extra_options"]["log_gradients"]: wandb_logger.watch(model, log='gradients') else: wandb_logger.watch(model, log=None) - wandb_logger.log_hyperparams({ - "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) - 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({"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"]) - wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"]) - wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"]) + if wandb_config["extra_options"]["log_train_val_test_sizes"]: + wandb_logger.log_hyperparams({ + "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, + }) + + if wandb_config["extra_options"]["log_model_args"]: + wandb_logger.log_hyperparams(config["model"]["args"]) + if wandb_config["extra_options"]["log_datamodule_args"]: + wandb_logger.log_hyperparams(config["datamodule"]["args"]) + if wandb_config["extra_options"]["log_optimizer_args"]: + wandb_logger.log_hyperparams(config["optimizer"]["args"]) + if wandb_config["extra_options"]["log_trainer_args"]: + wandb_logger.log_hyperparams(config["trainer"]["args"]) + + if wandb_config["extra_options"]["log_model_class_name"]: + wandb_logger.log_hyperparams({"model_class": config["model"]["class"]}) + if wandb_config["extra_options"]["log_datamodule_class_name"]: + wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]}) + if wandb_config["extra_options"]["log_optimizer_class_name"]: + wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]}) return wandb_logger - - -def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: - """Initialize tensorboard loggers""" - # TODO - return None - - -def init_comet_logger(project_config: dict, - run_config: dict, - model: pl.LightningModule, - datamodule: pl.LightningDataModule) -> pl.loggers.CometLogger: - - comet_logger = CometLogger() diff --git a/project/template_utils/predict_example.py b/project/template_utils/predict_example.py index b1667d5..39965bb 100644 --- a/project/template_utils/predict_example.py +++ b/project/template_utils/predict_example.py @@ -4,6 +4,8 @@ from PIL import Image # the LitModel you import should be the same as the one you used for training! from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel +# ckpt can be a url! + def predict(): """ diff --git a/project/train.py b/project/train.py index 1699302..a8f46b9 100644 --- a/project/train.py +++ b/project/train.py @@ -1,17 +1,20 @@ # pytorch lightning imports -from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback from pytorch_lightning.loggers import LightningLoggerBase +import pytorch_lightning as pl import torch +# hydra imports +from omegaconf import DictConfig, OmegaConf +import hydra.conf.hydra.output + # normal imports -from argparse import ArgumentParser from typing import List -import yaml +import logging import os # template utils imports from template_utils.initializers import ( - normalize_config_paths, + format_config_paths, init_model, init_datamodule, init_callbacks, @@ -19,56 +22,44 @@ from template_utils.initializers import ( init_trainer ) - -# Everything will be loaded relatively to placement of 'train.py' file! BASE_DIR: str = os.path.dirname(__file__) +LOG = logging.getLogger(__name__) -def train(project_config: dict, run_config: dict, use_wandb: bool): +def train(config): # Set global PyTorch seed - if "seed" in run_config: - torch.manual_seed(run_config["seed"]) + if "seeds" in config and "pytorch_seed" in config["seeds"]: + torch.manual_seed(config["seeds"]["pytorch_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 - ) + config = format_config_paths(config=config, base_dir=BASE_DIR) # Init PyTorch Lightning model ⚡ - model: LightningModule = init_model( - model_config=run_config["model"] + model: pl.LightningModule = init_model( + model_config=config["model"], + optimizer_config=config["optimizer"] ) # Init PyTorch Lightning datamodule ⚡ - datamodule: LightningDataModule = init_datamodule( - datamodule_config=run_config["datamodule"], - data_dir=project_config["data_dir"] + datamodule: pl.LightningDataModule = init_datamodule( + datamodule_config=config["datamodule"], + data_dir=config["paths"]["data_dir"] ) - # Init PyTorch Lightning 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 callbacks ⚡ + callbacks: List[pl.Callback] = init_callbacks(config=config) # Init PyTorch Lightning loggers ⚡ - loggers: List[LightningLoggerBase] = init_loggers( - project_config=project_config, - run_config=run_config, + loggers: List[pl.loggers.LightningLoggerBase] = init_loggers( + config=config, model=model, - datamodule=datamodule, - use_wandb=use_wandb + datamodule=datamodule ) # Init PyTorch Lightning trainer ⚡ - trainer: Trainer = init_trainer( - project_config=project_config, - run_config=run_config, + trainer: pl.Trainer = init_trainer( + trainer_config=config["trainer"], callbacks=callbacks, loggers=loggers ) @@ -83,49 +74,11 @@ def train(project_config: dict, run_config: dict, use_wandb: bool): trainer.test() -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(project_config_path: str, run_configs_path: str, run_config_name: str, use_wandb: bool): - # Load configs - 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) +@hydra.main(config_path="configs/", config_name="config.yaml") +def main(config: DictConfig) -> None: + LOG.info(OmegaConf.to_yaml(config, resolve=True)) # print content of config + train(config) if __name__ == "__main__": - parser = ArgumentParser() - 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() - - 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) + main() diff --git a/requirements.txt b/requirements.txt index fef496e..0b22d92 100644 --- a/requirements.txt +++ b/requirements.txt @@ -4,6 +4,5 @@ torchaudio>=0.7.0 pytorch-lightning>=1.0.8 hydra-core wandb>=0.10.12 -PyYAML>=5.3.1 scikit-learn>=0.23.2 pandas>=1.1.5 From d24568e6861bd55d13abb9d1c09273dd0927bebe Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Thu, 7 Jan 2021 22:40:21 +0100 Subject: [PATCH 07/15] making progress with hydra --- project/configs/config.yaml | 19 ++-- .../experiment/exp_example_advanced.yaml | 4 +- .../experiment/exp_example_simple.yaml | 2 +- project/configs/logger/all_loggers.yaml | 8 ++ .../configs/{loggers => logger}/comet.yaml | 2 +- .../{loggers => logger}/csv_logger.yaml | 2 +- .../{loggers => logger}/tensorboard.yaml | 2 +- .../configs/{loggers => logger}/wandb.yaml | 14 +-- project/configs/loggers/all_loggers.yaml | 8 -- project/configs/seeds/default_seeds.yaml | 3 + project/configs/trainer/debug_trainer.yaml | 6 +- project/configs/trainer/default_trainer.yaml | 9 +- .../lightning_datamodules/mnist_datamodule.py | 2 +- .../template_utils/execute_all_experiments.py | 2 +- project/template_utils/execute_sweep.py | 2 +- project/template_utils/hydra_config_schema.py | 0 project/template_utils/initializers.py | 97 +++++++++---------- project/test.py | 23 ++++- project/train.py | 36 +++++-- requirements.txt | 1 + setup.py | 4 +- 21 files changed, 142 insertions(+), 104 deletions(-) create mode 100644 project/configs/logger/all_loggers.yaml rename project/configs/{loggers => logger}/comet.yaml (72%) rename project/configs/{loggers => logger}/csv_logger.yaml (58%) rename project/configs/{loggers => logger}/tensorboard.yaml (57%) rename project/configs/{loggers => logger}/wandb.yaml (66%) delete mode 100644 project/configs/loggers/all_loggers.yaml create mode 100644 project/configs/seeds/default_seeds.yaml create mode 100644 project/template_utils/hydra_config_schema.py diff --git a/project/configs/config.yaml b/project/configs/config.yaml index a978184..7b0d471 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -5,19 +5,20 @@ defaults: - model: simple_mnist_classifier.yaml - datamodule: mnist_datamodule.yaml - optimizer: adam.yaml - - callbacks: default_callbacks.yaml - - loggers: null + - seeds: default_seeds.yaml # set this to null if you don't want to use seeds + - 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`) -seeds: - pytorch_seed: 12345 +# path to working directory (the directory that `train.py` was executed from in command line) +work_dir: ${hydra:runtime.cwd} -paths: - data_dir: "data" # path to data folder (either absolute or relative to placement of 'train.py' file) - logs_dir: "logs" # path to logs folder (either absolute or relative to placement of 'train.py' file) +# path to folder with data +data_dir: ${work_dir}/data/ +# hydra output paths hydra: run: - dir: ${paths.logs_dir}/hydra_logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} + dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} sweep: - dir: ${paths.logs_dir}/hydra_logs/sweeps/${now:%Y-%m-%d_%H-%M-%S} + dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S} subdir: ${hydra.job.num} diff --git a/project/configs/experiment/exp_example_advanced.yaml b/project/configs/experiment/exp_example_advanced.yaml index e9bc170..d4b7768 100644 --- a/project/configs/experiment/exp_example_advanced.yaml +++ b/project/configs/experiment/exp_example_advanced.yaml @@ -37,7 +37,7 @@ model: datamodule: args: # you can add here any params you want and then access them in lightning datamodule batch_size: 64 - train_val_test_split: (55_000, 5_000, 10_000) + 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 @@ -48,7 +48,7 @@ optimizer: loggers: wandb: - args: # you can add here additional loggers arguments specific for this experiment + args: # you can add here additional logger arguments specific for this experiment tags: ["uwu", "best_model"] notes: "" group: "" diff --git a/project/configs/experiment/exp_example_simple.yaml b/project/configs/experiment/exp_example_simple.yaml index 5eed61c..e265293 100644 --- a/project/configs/experiment/exp_example_simple.yaml +++ b/project/configs/experiment/exp_example_simple.yaml @@ -28,7 +28,7 @@ model: datamodule: args: batch_size: 32 - train_val_test_split: (55_000, 5_000, 10_000) + train_val_test_split: [55_000, 5_000, 10_000] optimizer: args: diff --git a/project/configs/logger/all_loggers.yaml b/project/configs/logger/all_loggers.yaml new file mode 100644 index 0000000..64c302f --- /dev/null +++ b/project/configs/logger/all_loggers.yaml @@ -0,0 +1,8 @@ +# @package _group_ + +# Train with all logger at once +defaults: + - comet.yaml + - csv_logger.yaml + - tensorboard.yaml + - wandb.yaml diff --git a/project/configs/loggers/comet.yaml b/project/configs/logger/comet.yaml similarity index 72% rename from project/configs/loggers/comet.yaml rename to project/configs/logger/comet.yaml index 86aac49..39a12dc 100644 --- a/project/configs/loggers/comet.yaml +++ b/project/configs/logger/comet.yaml @@ -2,7 +2,7 @@ # Comet logger config comet: - class: pytorch_lightning.loggers.CometLogger + class: pytorch_lightning.logger.CometLogger args: api_key: ??? project_name: "project_template_test" diff --git a/project/configs/loggers/csv_logger.yaml b/project/configs/logger/csv_logger.yaml similarity index 58% rename from project/configs/loggers/csv_logger.yaml rename to project/configs/logger/csv_logger.yaml index 71ac7f9..70a58e9 100644 --- a/project/configs/loggers/csv_logger.yaml +++ b/project/configs/logger/csv_logger.yaml @@ -2,5 +2,5 @@ # Csv logger config csv_logger: - class: pytorch_lightning.loggers.CSVLogger + class: pytorch_lightning.logger.CSVLogger args: {} diff --git a/project/configs/loggers/tensorboard.yaml b/project/configs/logger/tensorboard.yaml similarity index 57% rename from project/configs/loggers/tensorboard.yaml rename to project/configs/logger/tensorboard.yaml index 4ce390e..543d590 100644 --- a/project/configs/loggers/tensorboard.yaml +++ b/project/configs/logger/tensorboard.yaml @@ -2,5 +2,5 @@ # Tensorboard logger config tensorboard: - class: pytorch_lightning.loggers.TensorboardLogger + class: pytorch_lightning.logger.TensorboardLogger args: {} diff --git a/project/configs/loggers/wandb.yaml b/project/configs/logger/wandb.yaml similarity index 66% rename from project/configs/loggers/wandb.yaml rename to project/configs/logger/wandb.yaml index 51d4d16..457e1fb 100644 --- a/project/configs/loggers/wandb.yaml +++ b/project/configs/logger/wandb.yaml @@ -2,13 +2,13 @@ # Weights&Biases logger config wandb: - class: pytorch_lightning.loggers.WandbLogger + class: pytorch_lightning.logger.WandbLogger args: project: "project_template_test" - entity: "" # change to your username or name of your team on wandb +# entity: "your_team_name" # set to name of your team on wandb offline: False # set True to store all logs only locally job_type: "train" - save_dir: ${paths.logs_dir} + save_dir: "./" # some extra things which will be logged by the environment extra_logs: @@ -17,10 +17,10 @@ wandb: log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset - log_model_args: True # log - log_datamodule_args: True # log - log_optimizer_args: True # log - log_trainer_args: False # log + log_model_args: True + log_datamodule_args: True + log_optimizer_args: True + log_trainer_args: False log_model_class_name: True log_datamodule_class_name: True diff --git a/project/configs/loggers/all_loggers.yaml b/project/configs/loggers/all_loggers.yaml deleted file mode 100644 index a866cf8..0000000 --- a/project/configs/loggers/all_loggers.yaml +++ /dev/null @@ -1,8 +0,0 @@ -# @package _group_ - -# Train with all loggers at once -defaults: - - comet - - csv_logger - - tensorboard - - wandb diff --git a/project/configs/seeds/default_seeds.yaml b/project/configs/seeds/default_seeds.yaml new file mode 100644 index 0000000..de05e44 --- /dev/null +++ b/project/configs/seeds/default_seeds.yaml @@ -0,0 +1,3 @@ +# @package _group_ + +pytorch_seed: 12345 diff --git a/project/configs/trainer/debug_trainer.yaml b/project/configs/trainer/debug_trainer.yaml index dae0ecb..3a8f840 100644 --- a/project/configs/trainer/debug_trainer.yaml +++ b/project/configs/trainer/debug_trainer.yaml @@ -2,7 +2,7 @@ # trainer args for debugging model args: - gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only + gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only auto_select_gpus: True fast_dev_run: True @@ -13,5 +13,5 @@ args: profiler: "simple" # use profiler to print execution time profiling after training ends progress_bar_refresh_rate: 10 - weights_summary: "top" - default_root_dir: ${paths.logs_dir}/lightning_logs + weights_summary: "full" + default_root_dir: "lightning_logs/" diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml index 7e706af..49c42d5 100644 --- a/project/configs/trainer/default_trainer.yaml +++ b/project/configs/trainer/default_trainer.yaml @@ -1,12 +1,11 @@ # @package _group_ -# args passed to Lightning Trainer on every experiment -# they will be combined with trainer args specified in experiment config -# (if the argument repeats in experiment config, then it will override the one set here) +# 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 num_sanity_val_steps: 3 - weights_summary: "top" progress_bar_refresh_rate: 10 - default_root_dir: ${paths.logs_dir}/lightning_logs + weights_summary: null # null in yaml represents python None value + default_root_dir: "lightning_logs/" diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py index df351b1..4abfe48 100644 --- a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py +++ b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py @@ -18,7 +18,7 @@ class MNISTDataModule(LightningDataModule): def __init__(self, data_dir, **args): super().__init__() - self.data_dir = data_dir + "/MNIST" # data_dir is specified in config.yaml + self.data_dir = data_dir # data_dir is specified in config.yaml self.batch_size = args.get("batch_size") or 64 self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000] diff --git a/project/template_utils/execute_all_experiments.py b/project/template_utils/execute_all_experiments.py index c84e7ae..ecec406 100644 --- a/project/template_utils/execute_all_experiments.py +++ b/project/template_utils/execute_all_experiments.py @@ -25,7 +25,7 @@ def main(project_config_path, run_configs_path): if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("-p", "--project_config_path", type=str, - default=os.path.join(train.BASE_DIR, "project_config.yaml")) + default=os.path.join(train.BASE_DIR, "config.yaml")) parser.add_argument("-r", "--run_configs_path", type=str, default=os.path.join(train.BASE_DIR, "run_configs.yaml")) args = parser.parse_args() diff --git a/project/template_utils/execute_sweep.py b/project/template_utils/execute_sweep.py index 7a205ab..c396584 100644 --- a/project/template_utils/execute_sweep.py +++ b/project/template_utils/execute_sweep.py @@ -9,7 +9,7 @@ import train RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST" # Load configs -project_config = train.load_config("project_config.yaml") +project_config = train.load_config("config.yaml") run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME] # Initialize wandb diff --git a/project/template_utils/hydra_config_schema.py b/project/template_utils/hydra_config_schema.py new file mode 100644 index 0000000..e69de29 diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 148adbc..622769a 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,39 +1,24 @@ # pytorch lightning imports import pytorch_lightning as pl - -# normal imports -from typing import List, Tuple -import importlib.util -import os - -# template utils imports from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger import torch - -def format_path(path: str, base_dir: str): - """Convert path to absolute relatively to base_dir and normalize it.""" - if not os.path.isabs(path): - path = os.path.join(base_dir, path) - return os.path.normpath(path) +# normal imports +from typing import List, Tuple +import importlib +import os -def format_config_paths(config: dict, base_dir: str) -> dict: - config["paths"]["data_dir"] = format_path(config["paths"]["data_dir"], base_dir) - config["paths"]["logs_dir"] = format_path(config["paths"]["logs_dir"], base_dir) - return config - - -def load_object(obj_path): - obj_path, obj_name = obj_path.rsplit('.', 1) - module = importlib.import_module(obj_path) +def load_class(class_path) -> type: + class_path, obj_name = class_path.rsplit('.', 1) + module = importlib.import_module(class_path) assert hasattr(module, obj_name), \ - f'Object `{obj_name}` cannot be loaded from `{obj_path}`.' + f'Object `{obj_name}` cannot be loaded from `{class_path}`.' return getattr(module, obj_name) -def init_object(obj_path, args): - return load_object(obj_path)(**args) +def init_object(class_path, args) -> object: + return load_class(class_path)(**args) def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule: @@ -42,7 +27,7 @@ def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule """ model_class = model_config["class"] model_args = model_config["args"] - LitModel = load_object(model_class) + LitModel = load_class(model_class) assert issubclass(LitModel, pl.LightningModule), \ f"Specified model class `{model_class}` is not a subclass of `LightningModule`." return LitModel(optimizer_config, **model_args) @@ -54,7 +39,7 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM """ datamodule_class = datamodule_config["class"] datamodule_args = datamodule_config["args"] - DataModule = load_object(datamodule_class) + DataModule = load_class(datamodule_class) assert issubclass(DataModule, pl.LightningDataModule), \ f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`" datamodule = DataModule(data_dir=data_dir, **datamodule_args) @@ -66,9 +51,9 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM def init_optimizer(optimizer_config, model): optimizer_class = optimizer_config["class"] optimizer_args = optimizer_config["args"] - Optim = load_object(optimizer_class) + Optim = load_class(optimizer_class) assert issubclass(Optim, torch.optim.Optimizer), \ - f"Specified optimizer class `{optimizer_class}` is not a subclass of `torch.optim.Optimizer`." + f"Specified optimizer class `{optimizer_class}` is not subclass of `torch.optim.Optimizer`." return Optim(model.parameters(), **optimizer_args) @@ -97,9 +82,11 @@ def init_callbacks(config: dict) -> List[pl.Callback]: return callbacks for callback_name, callback_conf in callbacks_config.items(): - callback_class = callback_conf.get("class", None) - if callback_class: - callback_obj = init_object(callback_class, callback_conf.get("args", {})) + class_path = callback_conf.get("class", None) + if class_path: + callback_obj = init_object(class_path=class_path, args=callback_conf.get("args", {})) + assert issubclass(callback_obj.__class__, pl.Callback), \ + f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`." callbacks.append(callback_obj) return callbacks @@ -109,21 +96,23 @@ def init_loggers(config: dict, model: pl.LightningModule, datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]: """ - Initialize loggers specified in config. + Initialize logger specified in config. """ - loggers_config = config.get("loggers", None) + loggers_config = config.get("logger", None) loggers = [] if not loggers_config: return loggers for logger_name, logger_conf in loggers_config.items(): - logger_class = loggers_config.get("class", None) - if logger_class: - if logger_class == "pytorch_lightning.loggers.WandbLogger": + class_path = logger_conf.get("class", None) + if class_path: + if class_path == "pytorch_lightning.logger.WandbLogger": logger_obj = init_wandb(config, model, datamodule) else: - logger_obj = init_object(logger_class, logger_conf.get("args", {})) + logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {})) + assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \ + f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`." loggers.append(logger_obj) return loggers @@ -139,7 +128,7 @@ def init_wandb(config: dict, # instead of auto-creating a new run os.environ["WANDB_RESUME"] = "must" - wandb_config = config["loggers"]["wandb"] + wandb_config = config["logger"]["wandb"] wandb_logger = WandbLogger(**wandb_config["args"]) # make save dir path if it doesn't exists to prevent throwing errors by wandb @@ -147,18 +136,18 @@ def init_wandb(config: dict, os.makedirs(wandb_config["args"]["save_dir"]) if hasattr(model, 'model'): - if wandb_config["extra_options"]["log_gradients"]: + if wandb_config["extra_logs"]["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: - if wandb_config["extra_options"]["log_gradients"]: + if wandb_config["extra_logs"]["log_gradients"]: wandb_logger.watch(model, log='gradients') else: wandb_logger.watch(model, log=None) - if wandb_config["extra_options"]["log_train_val_test_sizes"]: + if wandb_config["extra_logs"]["log_train_val_test_sizes"]: wandb_logger.log_hyperparams({ "train_size": len(datamodule.data_train) if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, @@ -168,20 +157,30 @@ def init_wandb(config: dict, if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0, }) - if wandb_config["extra_options"]["log_model_args"]: + if wandb_config["extra_logs"]["log_model_args"]: wandb_logger.log_hyperparams(config["model"]["args"]) - if wandb_config["extra_options"]["log_datamodule_args"]: + if wandb_config["extra_logs"]["log_datamodule_args"]: wandb_logger.log_hyperparams(config["datamodule"]["args"]) - if wandb_config["extra_options"]["log_optimizer_args"]: + if wandb_config["extra_logs"]["log_optimizer_args"]: wandb_logger.log_hyperparams(config["optimizer"]["args"]) - if wandb_config["extra_options"]["log_trainer_args"]: + if wandb_config["extra_logs"]["log_trainer_args"]: wandb_logger.log_hyperparams(config["trainer"]["args"]) - if wandb_config["extra_options"]["log_model_class_name"]: + if wandb_config["extra_logs"]["log_model_class_name"]: wandb_logger.log_hyperparams({"model_class": config["model"]["class"]}) - if wandb_config["extra_options"]["log_datamodule_class_name"]: + if wandb_config["extra_logs"]["log_datamodule_class_name"]: wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]}) - if wandb_config["extra_options"]["log_optimizer_class_name"]: + if wandb_config["extra_logs"]["log_optimizer_class_name"]: wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]}) return wandb_logger + + +def validate_config(config: dict): + # TODO + pass + + +def validate_obj_config(obj_config: dict): + # TODO + pass diff --git a/project/test.py b/project/test.py index 74e3b28..5c3af3c 100644 --- a/project/test.py +++ b/project/test.py @@ -1,14 +1,33 @@ +import torch +import yaml from omegaconf import DictConfig, OmegaConf import hydra.conf.hydra.output from hydra.experimental import initialize, compose import comet_ml +from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger +import logging -@hydra.main(config_path="configs/", config_name="project_config.yaml") +log = logging.getLogger(__name__) + + +@hydra.main(config_path="configs/", config_name="config.yaml") def my_app(cfg: DictConfig) -> None: + # pass # print(cfg) - print(OmegaConf.to_yaml(cfg)) + log.info(OmegaConf.to_yaml(cfg, resolve=True)) + + +def test_logger(): + logger = WandbLogger() + print(logger) if __name__ == "__main__": my_app() + + # with open("epoch=0.ckpt", "rb") as file: + # data = torch.load(file) + # print(data) + + # test_logger() diff --git a/project/train.py b/project/train.py index a8f46b9..72efa25 100644 --- a/project/train.py +++ b/project/train.py @@ -6,15 +6,15 @@ import torch # hydra imports from omegaconf import DictConfig, OmegaConf import hydra.conf.hydra.output +import hydra # normal imports from typing import List import logging -import os # template utils imports from template_utils.initializers import ( - format_config_paths, + validate_config, init_model, init_datamodule, init_callbacks, @@ -22,19 +22,16 @@ from template_utils.initializers import ( init_trainer ) -BASE_DIR: str = os.path.dirname(__file__) -LOG = logging.getLogger(__name__) +log = logging.getLogger(__name__) def train(config): + validate_config(config) # Set global PyTorch seed if "seeds" in config and "pytorch_seed" in config["seeds"]: torch.manual_seed(config["seeds"]["pytorch_seed"]) - # Covert paths to absolute and normalize them - config = format_config_paths(config=config, base_dir=BASE_DIR) - # Init PyTorch Lightning model ⚡ model: pl.LightningModule = init_model( model_config=config["model"], @@ -44,19 +41,38 @@ def train(config): # Init PyTorch Lightning datamodule ⚡ datamodule: pl.LightningDataModule = init_datamodule( datamodule_config=config["datamodule"], - data_dir=config["paths"]["data_dir"] + data_dir=config["data_dir"] ) # Init PyTorch Lightning callbacks ⚡ callbacks: List[pl.Callback] = init_callbacks(config=config) - # Init PyTorch Lightning loggers ⚡ + # Init PyTorch Lightning logger ⚡ loggers: List[pl.loggers.LightningLoggerBase] = init_loggers( config=config, model=model, datamodule=datamodule ) + message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n" + log.info(message) + + message = "Datamodule initialised:" + "\n" + datamodule.__module__ + "." + datamodule.__class__.__name__ + "\n" + log.info(message) + + message = "Callbacks initialised:" + "\n" + for cb in callbacks: + message += cb.__module__ + "." + cb.__class__.__name__ + "\n" + log.info(message) + + message = "Loggers initialised:" + "\n" + for logger in loggers: + message += logger.__module__ + "." + logger.__class__.__name__ + "\n" + log.info(message) + + if "seeds" in config and "pytorch_seed" in config["seeds"]: + log.info(f"Using pytorch seed: {config['seeds']['pytorch_seed']}\n") + # Init PyTorch Lightning trainer ⚡ trainer: pl.Trainer = init_trainer( trainer_config=config["trainer"], @@ -76,7 +92,7 @@ def train(config): @hydra.main(config_path="configs/", config_name="config.yaml") def main(config: DictConfig) -> None: - LOG.info(OmegaConf.to_yaml(config, resolve=True)) # print content of config + log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") # print content of config train(config) diff --git a/requirements.txt b/requirements.txt index 0b22d92..0340ea5 100644 --- a/requirements.txt +++ b/requirements.txt @@ -6,3 +6,4 @@ hydra-core wandb>=0.10.12 scikit-learn>=0.23.2 pandas>=1.1.5 +hydra_colorlog diff --git a/setup.py b/setup.py index 9a89f33..a572dc8 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( description='Describe Your Cool Project', author='', author_email='', - url='https://github.com/kinoai/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK - install_requires=['pytorch-lightning'], + url='https://github.com/hobogalaxy/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK + install_requires=['pytorch-lightning', 'hydra-core'], packages=find_packages(), ) From 0030c94b17bdd837b536a177ae3b0725d2c3e74d Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sat, 9 Jan 2021 23:09:18 +0100 Subject: [PATCH 08/15] add callback for saving best metrics scores to wandb --- .../configs/callbacks/default_callbacks.yaml | 4 +- .../configs/callbacks/mnist_callbacks.yaml | 2 + project/configs/config.yaml | 11 ++++ .../experiment/exp_example_advanced.yaml | 4 +- project/configs/logger/csv_logger.yaml | 6 +- project/configs/logger/wandb.yaml | 22 +------ .../lightning_callbacks/wandb_callbacks.py | 60 +++++++++++++++++++ .../simple_mnist_classifier.py | 15 ++--- project/template_utils/initializers.py | 15 ++++- 9 files changed, 103 insertions(+), 36 deletions(-) diff --git a/project/configs/callbacks/default_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml index c36fa30..074f80a 100644 --- a/project/configs/callbacks/default_callbacks.yaml +++ b/project/configs/callbacks/default_callbacks.yaml @@ -7,11 +7,13 @@ model_checkpoint: save_top_k: 1 # save k best lightning_models (determined by above metric) save_last: True # additionaly always save model from last epoch mode: "max" # can be "max" or "min" + filepath: "checkpoints/{epoch}" early_stopping: class: "pytorch_lightning.callbacks.EarlyStopping" args: 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 + patience: 100 # how many epochs of not improving until training stops mode: "max" # can be "max" or "min" + min_delta: 0.0 # minimum change in the monitored metric needed to qualify as an improvement diff --git a/project/configs/callbacks/mnist_callbacks.yaml b/project/configs/callbacks/mnist_callbacks.yaml index e69de29..dfa4e43 100644 --- a/project/configs/callbacks/mnist_callbacks.yaml +++ b/project/configs/callbacks/mnist_callbacks.yaml @@ -0,0 +1,2 @@ +# @package _group_ + diff --git a/project/configs/config.yaml b/project/configs/config.yaml index 7b0d471..44dfee9 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -22,3 +22,14 @@ hydra: sweep: 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_train_val_test_sizes: True, + log_trainer_args: False, + log_model_args: True, + log_datamodule_args: True, + log_optimizer_args: True, + log_model_class_name: True, + log_datamodule_class_name: True, + log_optimizer_class_name: True diff --git a/project/configs/experiment/exp_example_advanced.yaml b/project/configs/experiment/exp_example_advanced.yaml index d4b7768..ebf468a 100644 --- a/project/configs/experiment/exp_example_advanced.yaml +++ b/project/configs/experiment/exp_example_advanced.yaml @@ -49,9 +49,9 @@ optimizer: loggers: wandb: args: # you can add here additional logger arguments specific for this experiment - tags: ["uwu", "best_model"] + tags: [best_model"] notes: "" group: "" comet: args: - tags: ["uwu", "best_model"] + tags: [best_model", "uwu"] diff --git a/project/configs/logger/csv_logger.yaml b/project/configs/logger/csv_logger.yaml index 70a58e9..88d2dea 100644 --- a/project/configs/logger/csv_logger.yaml +++ b/project/configs/logger/csv_logger.yaml @@ -2,5 +2,7 @@ # Csv logger config csv_logger: - class: pytorch_lightning.logger.CSVLogger - args: {} + class: pytorch_lightning.loggers.CSVLogger + args: + save_dir: "." + name: "csv_logger/" diff --git a/project/configs/logger/wandb.yaml b/project/configs/logger/wandb.yaml index 457e1fb..24c90ca 100644 --- a/project/configs/logger/wandb.yaml +++ b/project/configs/logger/wandb.yaml @@ -4,24 +4,8 @@ wandb: class: pytorch_lightning.logger.WandbLogger args: - project: "project_template_test" -# entity: "your_team_name" # set to name of your team on wandb + project: "env_tests" + entity: "lodz" # set to name of your wandb team or just remove offline: False # set True to store all logs only locally job_type: "train" - save_dir: "./" - - # some extra things which will be logged by the environment - extra_logs: - watch_model: True # make wandb watch model - log_gradients: False # log gradient histograms (avoid this for very big models) - - log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset - - log_model_args: True - log_datamodule_args: True - log_optimizer_args: True - log_trainer_args: False - - log_model_class_name: True - log_datamodule_class_name: True - log_optimizer_class_name: True + save_dir: "." diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 15bb7c8..6ac4850 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -173,3 +173,63 @@ class SaveCodeToWandbCallback(Callback): """Upload files when all validation sanity checks end.""" # upload additional files pass + + +class SaveBestMetricScores(Callback): + def __init__(self): + self.train_loss_list = [] + self.train_acc_list = [] + self.train_loss_best = None + self.train_acc_best = None + + self.val_loss_list = [] + self.val_acc_list = [] + self.val_loss_best = None + self.val_acc_best = None + + self.ready = False + + def clear_lists(self): + self.train_loss_list.clear() + self.train_acc_list.clear() + self.val_loss_list.clear() + self.val_acc_list.clear() + + 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: + loss, acc, preds, targets = outputs + self.val_loss_list.append(loss) + self.val_acc_list.append(acc) + + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): + """Gather data from single batch.""" + if self.ready: + loss, acc, preds, targets = outputs + self.train_loss_list.append(loss) + self.train_acc_list.append(acc) + + def on_epoch_end(self, trainer, pl_module): + if self.ready: + for logger in trainer.logger.experiment: + # currently works only for wandb + if isinstance(logger, wandb_run): + loss = sum(self.train_loss_list) / len(self.train_loss_list) + acc = sum(self.train_acc_list) / len(self.train_acc_list) + self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best + self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best + logger.log({"train_loss_best": self.train_loss_best}, commit=False) + logger.log({"train_acc_best": self.train_acc_best}, commit=False) + + loss = sum(self.val_loss_list) / len(self.val_loss_list) + acc = sum(self.val_acc_list) / len(self.val_acc_list) + self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best + self.val_acc_best = acc if self.val_acc_best is None or acc > self.val_acc_best else self.val_acc_best + logger.log({"val_loss_best": self.val_loss_best}, commit=False) + logger.log({"val_acc_best": self.val_acc_best}, commit=False) + + self.clear_lists() diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index 17edaa1..ac4d6c3 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -40,12 +40,12 @@ class LitModel(pl.LightningModule): # training metrics preds = torch.argmax(logits, dim=1) - preds, y = preds.cpu(), y.cpu() - acc = accuracy_score(preds, y) + acc = accuracy_score(preds.cpu(), y.cpu()) self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) - return loss + # we can return here anything and then read it in some callback + return loss, acc, preds, y # logic for a single validation step def validation_step(self, batch, batch_idx): @@ -55,13 +55,11 @@ class LitModel(pl.LightningModule): # validation metrics preds = torch.argmax(logits, dim=1) - preds, y = preds.cpu(), y.cpu() - acc = accuracy_score(preds, y) + acc = accuracy_score(preds.cpu(), y.cpu()) self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) - # we can return here anything and then read it in some callback - return preds, y + return loss, acc, preds, y # logic for a single testing step def test_step(self, batch, batch_idx): @@ -71,8 +69,7 @@ class LitModel(pl.LightningModule): # test metrics preds = torch.argmax(logits, dim=1) - preds, y = preds.cpu(), y.cpu() - acc = accuracy_score(preds, y) + acc = accuracy_score(preds.cpu(), y.cpu()) self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 622769a..5d3c36e 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,6 +1,7 @@ # pytorch lightning imports import pytorch_lightning as pl from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger +from pytorch_lightning.callbacks.lr_monitor import LearningRateMonitor import torch # normal imports @@ -126,14 +127,14 @@ def init_wandb(config: dict, """ # 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" + # os.environ["WANDB_RESUME"] = "must" wandb_config = config["logger"]["wandb"] wandb_logger = WandbLogger(**wandb_config["args"]) # make save dir path if it doesn't exists to prevent throwing errors by wandb - if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]): - os.makedirs(wandb_config["args"]["save_dir"]) + # if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]): + # os.makedirs(wandb_config["args"]["save_dir"]) if hasattr(model, 'model'): if wandb_config["extra_logs"]["log_gradients"]: @@ -176,6 +177,14 @@ def init_wandb(config: dict, return wandb_logger +def log_extra_hparams(config: dict, + model: pl.LightningModule, + datamodule: pl.LightningDataModule, + loggers: List[pl.loggers.LightningLoggerBase], + callbacks: List[pl.callbacks.Callback]): + pass + + def validate_config(config: dict): # TODO pass From 66097c4bf36abcb6b50ddbdfbff1eb9b89518b12 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 10 Jan 2021 16:03:00 +0100 Subject: [PATCH 09/15] fix bugs --- .../configs/callbacks/wandb_callbacks.yaml | 5 + project/configs/config.yaml | 23 ++- .../configs/datamodule/mnist_datamodule.yaml | 2 + project/configs/logger/wandb.yaml | 4 +- project/configs/trainer/default_trainer.yaml | 4 +- .../lightning_callbacks/wandb_callbacks.py | 34 +--- .../lightning_datamodules/mnist_datamodule.py | 12 +- .../simple_mnist_classifier.py | 35 ++-- project/template_utils/initializers.py | 174 +++++++++--------- project/train.py | 67 +++---- requirements.txt | 2 +- 11 files changed, 162 insertions(+), 200 deletions(-) create mode 100644 project/configs/callbacks/wandb_callbacks.yaml diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml new file mode 100644 index 0000000..e228987 --- /dev/null +++ b/project/configs/callbacks/wandb_callbacks.yaml @@ -0,0 +1,5 @@ +# @package _group_ + +defaults: + - default_callbacks.yaml + diff --git a/project/configs/config.yaml b/project/configs/config.yaml index 44dfee9..3e302f2 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -9,12 +9,15 @@ 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: @@ -23,13 +26,17 @@ 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_train_val_test_sizes: True, - log_trainer_args: False, - log_model_args: True, - log_datamodule_args: True, - log_optimizer_args: True, - log_model_class_name: True, - log_datamodule_class_name: True, - log_optimizer_class_name: True + log_seeds: True + + log_trainer_args: False + log_datamodule_args: True + + log_model_class: True + log_optimizer_class: True + log_datamodule_class: True + + log_train_val_test_sizes: True + log_model_architecture_class_name: True diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml index 7628e2c..c557e0d 100644 --- a/project/configs/datamodule/mnist_datamodule.yaml +++ b/project/configs/datamodule/mnist_datamodule.yaml @@ -4,3 +4,5 @@ class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule" args: batch_size: 64 train_val_test_split: [55_000, 5_000, 10_000] + num_workers: 1 + pin_memory: False diff --git a/project/configs/logger/wandb.yaml b/project/configs/logger/wandb.yaml index 24c90ca..a9fa46f 100644 --- a/project/configs/logger/wandb.yaml +++ b/project/configs/logger/wandb.yaml @@ -2,10 +2,10 @@ # Weights&Biases logger config wandb: - class: pytorch_lightning.logger.WandbLogger + class: pytorch_lightning.loggers.wandb.WandbLogger args: project: "env_tests" - entity: "lodz" # set to name of your wandb team or just remove +# entity: "team_name" # set to name of your wandb team or just remove it offline: False # set True to store all logs only locally job_type: "train" save_dir: "." diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml index 49c42d5..aff06d4 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/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 6ac4850..4a8409d 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -8,7 +8,7 @@ import wandb import os -class SaveOnnxModelToWandbCallback(Callback): +class SaveOnnxModelToWandb(Callback): """ Save model in .onnx format and upload to wandb. Might crash since not all lightning_models are compatible with onnx. @@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback): wandb.save(file_path, base_path=self.wandb_save_dir) -class ImagePredictionWandbLoggerCallback(Callback): +class SaveImagePredictionsToWandb(Callback): """ Each epoch upload to wandb a couple of the same images with predicted labels. """ @@ -58,7 +58,7 @@ class ImagePredictionWandbLoggerCallback(Callback): ]}, commit=False) -class MetricsHeatmapWandbLoggerCallback(Callback): +class SaveMetricsHeatmapToWandb(Callback): """ Generate f1, precision and recall heatmap from validation epoch outputs. Expects validation step to return predictions and targets. @@ -107,7 +107,7 @@ class MetricsHeatmapWandbLoggerCallback(Callback): self.targets = [] -class ConfusionMatrixWandbLoggerCallback(Callback): +class SaveConfusionMatrixToWandb(Callback): """ Generate Confusion Matrix. Expects validation step to return predictions and targets. @@ -152,7 +152,7 @@ class ConfusionMatrixWandbLoggerCallback(Callback): self.targets = [] -class SaveCodeToWandbCallback(Callback): +class SaveCodeToWandb(Callback): """ Upload specified code files to wandb at the beginning of the run. """ @@ -175,13 +175,8 @@ class SaveCodeToWandbCallback(Callback): pass -class SaveBestMetricScores(Callback): +class SaveBestMetricScoresToWandb(Callback): def __init__(self): - self.train_loss_list = [] - self.train_acc_list = [] - self.train_loss_best = None - self.train_acc_best = None - self.val_loss_list = [] self.val_acc_list = [] self.val_loss_best = None @@ -190,8 +185,6 @@ class SaveBestMetricScores(Callback): self.ready = False def clear_lists(self): - self.train_loss_list.clear() - self.train_acc_list.clear() self.val_loss_list.clear() self.val_acc_list.clear() @@ -206,25 +199,10 @@ class SaveBestMetricScores(Callback): self.val_loss_list.append(loss) self.val_acc_list.append(acc) - def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): - """Gather data from single batch.""" - if self.ready: - loss, acc, preds, targets = outputs - self.train_loss_list.append(loss) - self.train_acc_list.append(acc) - def on_epoch_end(self, trainer, pl_module): if self.ready: for logger in trainer.logger.experiment: - # currently works only for wandb if isinstance(logger, wandb_run): - loss = sum(self.train_loss_list) / len(self.train_loss_list) - acc = sum(self.train_acc_list) / len(self.train_acc_list) - self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best - self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best - logger.log({"train_loss_best": self.train_loss_best}, commit=False) - logger.log({"train_acc_best": self.train_acc_best}, commit=False) - loss = sum(self.val_loss_list) / len(self.val_loss_list) acc = sum(self.val_acc_list) / len(self.val_acc_list) self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py index 4abfe48..113b280 100644 --- a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py +++ b/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py @@ -7,10 +7,6 @@ from torchvision.datasets import MNIST class MNISTDataModule(LightningDataModule): """ This is example of datamodule for MNIST dataset. - - The path to datamodule should be specified in your run config. - The 'args' dict contains datamodule args specified in config. - To learn how to create datamodules visit: https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html """ @@ -20,10 +16,10 @@ class MNISTDataModule(LightningDataModule): self.data_dir = data_dir # data_dir is specified in config.yaml - self.batch_size = args.get("batch_size") or 64 - self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000] - self.num_workers = args.get("num_workers") or 1 - self.pin_memory = args.get("pin_memory") or False + self.batch_size = args["batch_size"] + self.train_val_test_split = args["train_val_test_split"] + self.num_workers = args["num_workers"] + self.pin_memory = args["pin_memory"] self.transforms = transforms.ToTensor() diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index ac4d6c3..d7c2e79 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -2,7 +2,7 @@ from sklearn.metrics import accuracy_score import pytorch_lightning as pl import torch.nn.functional as F import torch -from template_utils.initializers import init_optimizer +from template_utils.initializers import load_class # import custom architectures from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier @@ -11,23 +11,19 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier class LitModel(pl.LightningModule): """ This is example of lightning model for MNIST classification. - - The path to model should be specified in your run config. (run_configs.yaml) - The 'hparams' dict contains model args specified in config. (run_configs.yaml) - This class enables you to specify what happens during training, validation and test step. You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training. - To learn how to create lightning models visit: https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html """ - def __init__(self, optimizer_config, **hparams): + def __init__(self, model_config, optimizer_config): super().__init__() - self.optimizer_config = optimizer_config + hparams = {**model_config["args"], **optimizer_config["args"]} self.save_hyperparameters(hparams) + self.optimizer_config = optimizer_config - self.model = SimpleMNISTClassifier(hparams=hparams) + self.model = SimpleMNISTClassifier(hparams=self.hparams) def forward(self, x): return self.model(x) @@ -41,11 +37,10 @@ class LitModel(pl.LightningModule): # training metrics preds = torch.argmax(logits, dim=1) acc = accuracy_score(preds.cpu(), y.cpu()) - self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) - self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) + self.log('train_loss', loss, on_step=False, on_epoch=True) + self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - # we can return here anything and then read it in some callback - return loss, acc, preds, y + return loss # logic for a single validation step def validation_step(self, batch, batch_idx): @@ -56,10 +51,11 @@ class LitModel(pl.LightningModule): # validation metrics preds = torch.argmax(logits, dim=1) acc = accuracy_score(preds.cpu(), y.cpu()) - self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) - self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) + self.log('val_loss', loss, on_step=False, on_epoch=True) + self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - return loss, acc, preds, y + # we can return here anything and then read it in some callback + return loss, {"preds": preds, "acc": acc, "y": y} # logic for a single testing step def test_step(self, batch, batch_idx): @@ -70,10 +66,11 @@ class LitModel(pl.LightningModule): # test metrics preds = torch.argmax(logits, dim=1) acc = accuracy_score(preds.cpu(), y.cpu()) - self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True) - self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True) + self.log('test_loss', loss, on_step=False, on_epoch=True) + self.log('test_acc', acc, on_step=False, on_epoch=True) return loss def configure_optimizers(self): - return init_optimizer(optimizer_config=self.optimizer_config, model=self) + Optimizer = load_class(self.optimizer_config["class"]) + return Optimizer(self.parameters(), **self.optimizer_config["args"]) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 5d3c36e..d7bd4de 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -1,13 +1,16 @@ # pytorch lightning imports +from pytorch_lightning.loggers.wandb import WandbLogger import pytorch_lightning as pl -from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger -from pytorch_lightning.callbacks.lr_monitor import LearningRateMonitor -import torch + +# hydra imports +from omegaconf import DictConfig, OmegaConf # normal imports -from typing import List, Tuple +from typing import List import importlib -import os +import logging + +log = logging.getLogger(__name__) def load_class(class_path) -> type: @@ -27,11 +30,10 @@ def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule Load LightningModule from path specified in config. """ model_class = model_config["class"] - model_args = model_config["args"] LitModel = load_class(model_class) assert issubclass(LitModel, pl.LightningModule), \ f"Specified model class `{model_class}` is not a subclass of `LightningModule`." - return LitModel(optimizer_config, **model_args) + return LitModel(model_config=model_config, optimizer_config=optimizer_config) def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule: @@ -49,15 +51,6 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM return datamodule -def init_optimizer(optimizer_config, model): - optimizer_class = optimizer_config["class"] - optimizer_args = optimizer_config["args"] - Optim = load_class(optimizer_class) - assert issubclass(Optim, torch.optim.Optimizer), \ - f"Specified optimizer class `{optimizer_class}` is not subclass of `torch.optim.Optimizer`." - return Optim(model.parameters(), **optimizer_args) - - def init_trainer(trainer_config: dict, callbacks: List[pl.Callback], loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer: @@ -72,16 +65,11 @@ def init_trainer(trainer_config: dict, return trainer -def init_callbacks(config: dict) -> List[pl.Callback]: +def init_callbacks(callbacks_config: dict) -> List[pl.Callback]: """ Initialize callbacks specified in config. """ - callbacks_config = config.get("callbacks", None) callbacks = [] - - if not callbacks_config: - return callbacks - for callback_name, callback_conf in callbacks_config.items(): class_path = callback_conf.get("class", None) if class_path: @@ -89,100 +77,108 @@ def init_callbacks(config: dict) -> List[pl.Callback]: assert issubclass(callback_obj.__class__, pl.Callback), \ f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`." callbacks.append(callback_obj) - return callbacks -def init_loggers(config: dict, - model: pl.LightningModule, - datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]: +def init_loggers(loggers_config: dict) -> List[pl.loggers.LightningLoggerBase]: """ - Initialize logger specified in config. + Initialize loggers specified in config. """ - loggers_config = config.get("logger", None) loggers = [] - - if not loggers_config: - return loggers - for logger_name, logger_conf in loggers_config.items(): class_path = logger_conf.get("class", None) if class_path: - if class_path == "pytorch_lightning.logger.WandbLogger": - logger_obj = init_wandb(config, model, datamodule) - else: - logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {})) + logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {})) assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \ f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`." loggers.append(logger_obj) - return loggers -def init_wandb(config: dict, - model: pl.LightningModule, - datamodule: pl.LightningDataModule) -> 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" +def get_wandb_logger(loggers: List[pl.loggers.LightningLoggerBase]) -> WandbLogger: + for logger in loggers: + if isinstance(logger, WandbLogger): + return logger - wandb_config = config["logger"]["wandb"] - wandb_logger = WandbLogger(**wandb_config["args"]) - # make save dir path if it doesn't exists to prevent throwing errors by wandb - # if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]): - # os.makedirs(wandb_config["args"]["save_dir"]) - - if hasattr(model, 'model'): - if wandb_config["extra_logs"]["log_gradients"]: - wandb_logger.watch(model.model, log='gradients') - else: +def make_wandb_watch_model(loggers: List[pl.loggers.LightningLoggerBase], model: pl.LightningModule): + wandb_logger = get_wandb_logger(loggers) + if wandb_logger: + if hasattr(model, 'model'): wandb_logger.watch(model.model, log=None) - wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__}) - else: - if wandb_config["extra_logs"]["log_gradients"]: - wandb_logger.watch(model, log='gradients') else: wandb_logger.watch(model, log=None) - if wandb_config["extra_logs"]["log_train_val_test_sizes"]: - wandb_logger.log_hyperparams({ - "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, - }) - if wandb_config["extra_logs"]["log_model_args"]: - wandb_logger.log_hyperparams(config["model"]["args"]) - if wandb_config["extra_logs"]["log_datamodule_args"]: - wandb_logger.log_hyperparams(config["datamodule"]["args"]) - if wandb_config["extra_logs"]["log_optimizer_args"]: - wandb_logger.log_hyperparams(config["optimizer"]["args"]) - if wandb_config["extra_logs"]["log_trainer_args"]: - wandb_logger.log_hyperparams(config["trainer"]["args"]) - - if wandb_config["extra_logs"]["log_model_class_name"]: - wandb_logger.log_hyperparams({"model_class": config["model"]["class"]}) - if wandb_config["extra_logs"]["log_datamodule_class_name"]: - wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]}) - if wandb_config["extra_logs"]["log_optimizer_class_name"]: - wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]}) - - return wandb_logger +def log_hparams(loggers: List[pl.loggers.LightningLoggerBase], hparams: dict): + for logger in loggers: + logger.log_hyperparams(hparams) -def log_extra_hparams(config: dict, +def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase], + config: dict, model: pl.LightningModule, datamodule: pl.LightningDataModule, - loggers: List[pl.loggers.LightningLoggerBase], callbacks: List[pl.callbacks.Callback]): - pass + if "extra_logs" not in config: + return + + extra_logs = config["extra_logs"] + + if "log_seeds" in extra_logs and extra_logs["log_seeds"] and "seeds" in config: + log_hparams(loggers, config["seeds"]) + + if "log_trainer_args" in extra_logs and extra_logs["log_trainer_args"]: + log_hparams(loggers, config["trainer"]["args"]) + if "log_model_args" in extra_logs and extra_logs["log_model_args"]: + log_hparams(loggers, config["model"]["args"]) + if "log_optimizer_args" in extra_logs and extra_logs["log_optimizer_args"]: + log_hparams(loggers, config["optimizer"]["args"]) + if "log_datamodule_args" in extra_logs and extra_logs["log_datamodule_args"]: + log_hparams(loggers, config["datamodule"]["args"]) + + if "log_model_class" in extra_logs and extra_logs["log_model_class"]: + log_hparams(loggers, {"model_class": config["model"]["class"]}) + if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]: + log_hparams(loggers, {"optimizer_class": config["optimizer"]["class"]}) + if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]: + log_hparams(loggers, {"datamodule_class": config["datamodule"]["class"]}) + + if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]: + hparams = {} + if hasattr(datamodule, 'data_train') and datamodule.data_train is not None: + hparams["train_size"] = len(datamodule.data_train) + if hasattr(datamodule, 'data_val') and datamodule.data_val is not None: + hparams["val_size"] = len(datamodule.data_val) + if hasattr(datamodule, 'data_test') and datamodule.data_test is not None: + hparams["test_size"] = len(datamodule.data_test) + log_hparams(loggers, hparams) + + if "log_model_architecture_class_name" in extra_logs and extra_logs["log_model_architecture_class_name"]: + if hasattr(model, "model"): + log_hparams(loggers, {"model_architecture_class_name": model.model.__class__.__name__}) + + +def show_init_info(model, datamodule, callbacks, loggers): + message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n" + log.info(message) + + message = "Datamodule initialised:" + "\n" + datamodule.__module__ + "." + datamodule.__class__.__name__ + "\n" + log.info(message) + + message = "Callbacks initialised:" + "\n" + for cb in callbacks: + message += cb.__module__ + "." + cb.__class__.__name__ + "\n" + log.info(message) + + message = "Loggers initialised:" + "\n" + for logger in loggers: + message += logger.__module__ + "." + logger.__class__.__name__ + "\n" + log.info(message) + + +def show_config(config: DictConfig): + log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") def validate_config(config: dict): diff --git a/project/train.py b/project/train.py index 72efa25..0d9c0ab 100644 --- a/project/train.py +++ b/project/train.py @@ -5,84 +5,65 @@ import torch # hydra imports from omegaconf import DictConfig, OmegaConf -import hydra.conf.hydra.output import hydra # normal imports from typing import List -import logging # template utils imports -from template_utils.initializers import ( - validate_config, - init_model, - init_datamodule, - init_callbacks, - init_loggers, - init_trainer -) - -log = logging.getLogger(__name__) +import template_utils.initializers as utils def train(config): - validate_config(config) + utils.validate_config(config=config) # Set global PyTorch seed if "seeds" in config and "pytorch_seed" in config["seeds"]: - torch.manual_seed(config["seeds"]["pytorch_seed"]) + torch.manual_seed(seed=config["seeds"]["pytorch_seed"]) # Init PyTorch Lightning model ⚡ - model: pl.LightningModule = init_model( + model: pl.LightningModule = utils.init_model( model_config=config["model"], optimizer_config=config["optimizer"] ) # Init PyTorch Lightning datamodule ⚡ - datamodule: pl.LightningDataModule = init_datamodule( + datamodule: pl.LightningDataModule = utils.init_datamodule( datamodule_config=config["datamodule"], data_dir=config["data_dir"] ) # Init PyTorch Lightning callbacks ⚡ - callbacks: List[pl.Callback] = init_callbacks(config=config) + callbacks = [] + if "callbacks" in config: + callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"]) - # Init PyTorch Lightning logger ⚡ - loggers: List[pl.loggers.LightningLoggerBase] = init_loggers( + # Init PyTorch Lightning loggers ⚡ + loggers = [] + if "logger" in config: + loggers: List[pl.loggers.LightningLoggerBase] = utils.init_loggers(loggers_config=config["logger"]) + + # If WandbLogger was initialized, make it watch the model + utils.make_wandb_watch_model(loggers=loggers, model=model) + + # Log to all loggers everything specified in 'extra_logs' section of config + utils.log_extra_hparams( + loggers=loggers, config=config, model=model, - datamodule=datamodule + datamodule=datamodule, + callbacks=callbacks ) - message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n" - log.info(message) - - message = "Datamodule initialised:" + "\n" + datamodule.__module__ + "." + datamodule.__class__.__name__ + "\n" - log.info(message) - - message = "Callbacks initialised:" + "\n" - for cb in callbacks: - message += cb.__module__ + "." + cb.__class__.__name__ + "\n" - log.info(message) - - message = "Loggers initialised:" + "\n" - for logger in loggers: - message += logger.__module__ + "." + logger.__class__.__name__ + "\n" - log.info(message) - - if "seeds" in config and "pytorch_seed" in config["seeds"]: - log.info(f"Using pytorch seed: {config['seeds']['pytorch_seed']}\n") + utils.show_init_info(model, datamodule, callbacks, loggers) # Init PyTorch Lightning trainer ⚡ - trainer: pl.Trainer = init_trainer( + trainer: pl.Trainer = utils.init_trainer( trainer_config=config["trainer"], callbacks=callbacks, loggers=loggers ) - # Evaluate model on test set before training - # trainer.test(model=model, datamodule=datamodule) - # Train the model trainer.fit(model=model, datamodule=datamodule) @@ -92,7 +73,7 @@ def train(config): @hydra.main(config_path="configs/", config_name="config.yaml") def main(config: DictConfig) -> None: - log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") # print content of config + utils.show_config(config) # print content of config train(config) diff --git a/requirements.txt b/requirements.txt index 0340ea5..fe195b6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ torch>=1.7.0 torchvision>=0.8.1 torchaudio>=0.7.0 -pytorch-lightning>=1.0.8 +pytorch-lightning>=1.1.3 hydra-core wandb>=0.10.12 scikit-learn>=0.23.2 From 90174d52c4316d3b679db7ef712fd0166ad988fa Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 10 Jan 2021 17:39:28 +0100 Subject: [PATCH 10/15] fix most of wandb callbacks --- .../configs/callbacks/wandb_callbacks.yaml | 19 +++ project/configs/logger/all_loggers.yaml | 4 +- .../lightning_callbacks/wandb_callbacks.py | 147 ++++++++---------- .../simple_mnist_classifier.py | 8 +- .../transforms/mnist_transforms.py | 2 +- .../template_utils/execute_all_experiments.py | 33 ---- project/template_utils/hydra_config_schema.py | 1 + ...redict_example.py => inference_example.py} | 4 +- project/train.py | 2 + 9 files changed, 100 insertions(+), 120 deletions(-) delete mode 100644 project/template_utils/execute_all_experiments.py rename project/template_utils/{predict_example.py => inference_example.py} (90%) diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml index e228987..89192fd 100644 --- a/project/configs/callbacks/wandb_callbacks.yaml +++ b/project/configs/callbacks/wandb_callbacks.yaml @@ -3,3 +3,22 @@ defaults: - default_callbacks.yaml + +save_best_metric_scores_to_wandb: + class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb" + args: {} + +save_code_to_wandb_as_artifact: + class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb" + args: + code_dir: ${work_dir}/ + +save_confusion_matrix_to_wandb: + class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveConfusionMatrixToWandb" + args: + class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') + +save_f1_heatmap_to_wandb: + class: "pytorch_modules.lightning_callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb" + args: + class_names: ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9') diff --git a/project/configs/logger/all_loggers.yaml b/project/configs/logger/all_loggers.yaml index 64c302f..76af7ec 100644 --- a/project/configs/logger/all_loggers.yaml +++ b/project/configs/logger/all_loggers.yaml @@ -2,7 +2,7 @@ # Train with all logger at once defaults: - - comet.yaml - csv_logger.yaml - - tensorboard.yaml - wandb.yaml + # - comet.yaml +# - tensorboard.yaml diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py index 4a8409d..1158f49 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py @@ -2,67 +2,60 @@ from sklearn.metrics import precision_score, recall_score, f1_score from pytorch_lightning.loggers import WandbLogger from wandb.sdk.wandb_run import Run as wandb_run from pytorch_lightning import Callback -from shutil import copy +import random import torch import wandb +import glob import os -class SaveOnnxModelToWandb(Callback): +class SaveCodeToWandb(Callback): """ - Save model in .onnx format and upload to wandb. - Might crash since not all lightning_models are compatible with onnx. + Upload all *.py files to wandb at the beginning of the run. """ - def __init__(self, datamodule, wandb_save_dir): - first_batch = next(iter(datamodule.train_dataloader())) - x, y = first_batch - self.dummy_input = x - self.wandb_save_dir = wandb_save_dir + def __init__(self, code_dir: str): + self.code_dir = code_dir def on_sanity_check_end(self, trainer, pl_module): - self.save_onnx_model(pl_module) - - def on_train_end(self, trainer, pl_module): - self.save_onnx_model(pl_module) - - def save_onnx_model(self, pl_module): - file_path = os.path.join(self.wandb_save_dir, "model.onnx") - pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device)) - wandb.save(file_path, base_path=self.wandb_save_dir) + """Upload files when all validation sanity checks end.""" + code = wandb.Artifact('project-source', type='code') + for path in glob.glob(os.path.join(self.code_dir, '**/*.py'), recursive=True): + code.add_file(path) + wandb.run.use_artifact(code) -class SaveImagePredictionsToWandb(Callback): - """ - Each epoch upload to wandb a couple of the same images with predicted labels. - """ - def __init__(self, datamodule, num_samples=8): - first_batch = next(iter(datamodule.train_dataloader())) - self.imgs, self.labels = first_batch - self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples] - self.ready = True - - def on_sanity_check_end(self, trainer, pl_module): - """Start executing this callback only after all validation sanity checks end.""" - self.ready = True - - def on_validation_epoch_end(self, trainer, pl_module): - if self.ready: - imgs = self.imgs.to(device=pl_module.device) - logits = pl_module(imgs) - preds = torch.argmax(logits, -1) - trainer.logger.experiment.log({f"img_examples": [ - wandb.Image( - x, - caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}" - ) for x, pred, y in zip(imgs, preds, self.labels) - ]}, commit=False) +# class SaveImagePredictionsToWandb(Callback): +# """ +# Each epoch upload to wandb a couple of the same images with predicted labels. +# """ +# def __init__(self, datamodule, num_samples=8): +# first_batch = next(iter(datamodule.train_dataloader())) +# self.imgs, self.labels = first_batch +# self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples] +# self.ready = True +# +# def on_sanity_check_end(self, trainer, pl_module): +# """Start executing this callback only after all validation sanity checks end.""" +# self.ready = True +# +# def on_validation_epoch_end(self, trainer, pl_module): +# if self.ready: +# imgs = self.imgs.to(device=pl_module.device) +# logits = pl_module(imgs) +# preds = torch.argmax(logits, -1) +# trainer.logger.experiment.log({f"img_examples": [ +# wandb.Image( +# x, +# caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}" +# ) for x, pred, y in zip(imgs, preds, self.labels) +# ]}, commit=False) class SaveMetricsHeatmapToWandb(Callback): """ - Generate f1, precision and recall heatmap from validation epoch outputs. - Expects validation step to return predictions and targets. - Works only for single label classification! + Generate f1, precision and recall heatmap from validation epoch outputs. + Expects validation step to return predictions and targets. + Works only for single label classification! """ def __init__(self, class_names): self.class_names = class_names @@ -77,7 +70,7 @@ class SaveMetricsHeatmapToWandb(Callback): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """Gather data from single batch.""" if self.ready: - preds, targets = outputs + preds, targets = outputs["preds"], outputs["y"] self.preds.append(preds) self.targets.append(targets) @@ -109,9 +102,9 @@ class SaveMetricsHeatmapToWandb(Callback): class SaveConfusionMatrixToWandb(Callback): """ - Generate Confusion Matrix. - Expects validation step to return predictions and targets. - Works only for single label classification! + Generate Confusion Matrix. + Expects validation step to return predictions and targets. + Works only for single label classification! """ def __init__(self, class_names): self.class_names = class_names @@ -126,7 +119,7 @@ class SaveConfusionMatrixToWandb(Callback): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """Gather data from single batch.""" if self.ready: - preds, targets = outputs + preds, targets = outputs["preds"], outputs["y"] self.preds.append(preds) self.targets.append(targets) @@ -142,7 +135,7 @@ class SaveConfusionMatrixToWandb(Callback): logger = some_logger logger.log({ - f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix( + f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix( self.preds, self.targets, class_names=self.class_names) @@ -152,31 +145,13 @@ class SaveConfusionMatrixToWandb(Callback): self.targets = [] -class SaveCodeToWandb(Callback): - """ - Upload specified code files to wandb at the beginning of the run. - """ - def __init__(self, base_dir, wandb_save_dir, run_config): - self.base_dir = base_dir - self.wandb_save_dir = wandb_save_dir - self.model_folder = run_config["model"]["load_from"]["model_path"] - self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"] - self.additional_files_to_be_saved = [ # paths should be relative to base_dir - "template_utils/custom_callbacks.py", - "template_utils/initializers.py", - "train.py", - "config.yaml", - "run_configs.yaml", - ] - - def on_sanity_check_end(self, trainer, pl_module): - """Upload files when all validation sanity checks end.""" - # upload additional files - pass - - class SaveBestMetricScoresToWandb(Callback): def __init__(self): + self.train_loss_list = [] + self.train_acc_list = [] + self.train_loss_best = None + self.train_acc_best = None + self.val_loss_list = [] self.val_acc_list = [] self.val_loss_best = None @@ -185,6 +160,8 @@ class SaveBestMetricScoresToWandb(Callback): self.ready = False def clear_lists(self): + self.train_loss_list.clear() + self.train_acc_list.clear() self.val_loss_list.clear() self.val_acc_list.clear() @@ -192,17 +169,31 @@ class SaveBestMetricScoresToWandb(Callback): """Start executing this callback only after all validation sanity checks end.""" self.ready = True + def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): + """Gather data from single batch.""" + # This is bugged :/ - lets wait for lightning 1.2 update + # if self.ready: + # self.train_loss_list.append(outputs["loss"]) + # self.train_acc_list.append(outputs["acc"]) + pass + def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """Gather data from single batch.""" if self.ready: - loss, acc, preds, targets = outputs - self.val_loss_list.append(loss) - self.val_acc_list.append(acc) + self.val_loss_list.append(outputs["loss"]) + self.val_acc_list.append(outputs["acc"]) def on_epoch_end(self, trainer, pl_module): if self.ready: for logger in trainer.logger.experiment: if isinstance(logger, wandb_run): + # loss = sum(self.train_loss_list) / len(self.train_loss_list) + # acc = sum(self.train_acc_list) / len(self.train_acc_list) + # self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best + # self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best + # logger.log({"train_loss_best": self.train_loss_best}, commit=False) + # logger.log({"train_acc_best": self.train_acc_best}, commit=False) + loss = sum(self.val_loss_list) / len(self.val_loss_list) acc = sum(self.val_acc_list) / len(self.val_acc_list) self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py index d7c2e79..0911e98 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/pytorch_modules/lightning_models/simple_mnist_classifier.py @@ -40,7 +40,8 @@ class LitModel(pl.LightningModule): self.log('train_loss', loss, on_step=False, on_epoch=True) self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - return loss + # we can return here anything and then read it in some callback + return {"loss": loss, "acc": acc, "preds": preds, "y": y} # logic for a single validation step def validation_step(self, batch, batch_idx): @@ -54,8 +55,7 @@ class LitModel(pl.LightningModule): self.log('val_loss', loss, on_step=False, on_epoch=True) self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - # we can return here anything and then read it in some callback - return loss, {"preds": preds, "acc": acc, "y": y} + return {"loss": loss, "acc": acc, "preds": preds, "y": y} # logic for a single testing step def test_step(self, batch, batch_idx): @@ -69,7 +69,7 @@ class LitModel(pl.LightningModule): self.log('test_loss', loss, on_step=False, on_epoch=True) self.log('test_acc', acc, on_step=False, on_epoch=True) - return loss + return {"loss": loss} def configure_optimizers(self): Optimizer = load_class(self.optimizer_config["class"]) diff --git a/project/pytorch_modules/transforms/mnist_transforms.py b/project/pytorch_modules/transforms/mnist_transforms.py index 7b22102..05e4d22 100644 --- a/project/pytorch_modules/transforms/mnist_transforms.py +++ b/project/pytorch_modules/transforms/mnist_transforms.py @@ -1,5 +1,5 @@ """ -Example file containing data transformations which can be used by datamodule. +Example file containing data transformations, which can be used by datamodule. """ from torchvision import transforms diff --git a/project/template_utils/execute_all_experiments.py b/project/template_utils/execute_all_experiments.py deleted file mode 100644 index ecec406..0000000 --- a/project/template_utils/execute_all_experiments.py +++ /dev/null @@ -1,33 +0,0 @@ -# THIS FILE WILL EXECUTE ALL EXPERIMENT CONFIGS LOCATED IN SPECIFIED FOLDER ONE AFTER THE OTHER - -from argparse import ArgumentParser -import train -import wandb -import yaml -import os - - -def main(project_config_path, run_configs_path): - - with open(project_config_path, "r") as ymlfile: - project_config = yaml.load(ymlfile, Loader=yaml.FullLoader) - - with open(run_configs_path, "r") as ymlfile: - run_configs = yaml.load(ymlfile, Loader=yaml.FullLoader) - - # EXECUTE ALL RUNS ONE AFTER THE OTHER - for conf_name in run_configs: - print(f"\nEXECUTING RUN: {conf_name}\n") - train.train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True) - wandb.finish() - - -if __name__ == "__main__": - parser = ArgumentParser() - parser.add_argument("-p", "--project_config_path", type=str, - default=os.path.join(train.BASE_DIR, "config.yaml")) - parser.add_argument("-r", "--run_configs_path", type=str, - default=os.path.join(train.BASE_DIR, "run_configs.yaml")) - args = parser.parse_args() - - main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path) diff --git a/project/template_utils/hydra_config_schema.py b/project/template_utils/hydra_config_schema.py index e69de29..55f1dc3 100644 --- a/project/template_utils/hydra_config_schema.py +++ b/project/template_utils/hydra_config_schema.py @@ -0,0 +1 @@ +import hydra diff --git a/project/template_utils/predict_example.py b/project/template_utils/inference_example.py similarity index 90% rename from project/template_utils/predict_example.py rename to project/template_utils/inference_example.py index 39965bb..755f349 100644 --- a/project/template_utils/predict_example.py +++ b/project/template_utils/inference_example.py @@ -1,4 +1,4 @@ -from pytorch_modules.lightning_datamodules.mnist_datamodule import transforms +from pytorch_modules.transforms import mnist_transforms from PIL import Image # the LitModel you import should be the same as the one you used for training! @@ -29,7 +29,7 @@ def predict(): # img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion # preprocess - img = transforms.mnist_test_transforms(img) + img = mnist_transforms.mnist_test_transforms(img) img = img.reshape((1, *img.size())) # reshape to form batch of size 1 # inference diff --git a/project/train.py b/project/train.py index 0d9c0ab..fa1a50b 100644 --- a/project/train.py +++ b/project/train.py @@ -9,6 +9,7 @@ import hydra # normal imports from typing import List +import wandb # template utils imports import template_utils.initializers as utils @@ -75,6 +76,7 @@ def train(config): def main(config: DictConfig) -> None: utils.show_config(config) # print content of config train(config) + wandb.finish() if __name__ == "__main__": From fbe24644263a02ac80caae8567b2c5a3d72d6cc5 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Sun, 10 Jan 2021 21:12:14 +0100 Subject: [PATCH 11/15] improve configs --- conda_env.yaml | 1 + .../configs/callbacks/default_callbacks.yaml | 4 +- .../configs/callbacks/wandb_callbacks.yaml | 20 ++--- project/configs/config.yaml | 4 - .../configs/datamodule/mnist_datamodule.yaml | 2 +- .../experiment/exp_example_advanced.yaml | 14 ++-- .../experiment/exp_example_simple.yaml | 4 +- .../model/simple_mnist_classifier.yaml | 2 +- project/configs/trainer/default_trainer.yaml | 4 +- .../datasets/img_test_dataset.py | 2 +- .../lightning_callbacks/custom_callbacks.py | 2 +- .../lightning_callbacks/wandb_callbacks.py | 73 ++++++++++++------- .../transforms/mnist_transforms.py | 2 +- project/train.py | 2 +- 14 files changed, 74 insertions(+), 62 deletions(-) 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 From 9a5a4eb1924a9375500400d573dc3ad04e5c91d6 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 12 Jan 2021 18:33:04 +0100 Subject: [PATCH 12/15] change folder structure --- README.md | 12 +-- conda_env.yaml | 2 + .../configs/callbacks/default_callbacks.yaml | 2 +- .../configs/callbacks/mnist_callbacks.yaml | 3 + .../configs/callbacks/wandb_callbacks.yaml | 33 +++++--- project/configs/config.yaml | 6 +- .../configs/datamodule/mnist_datamodule.yaml | 2 +- .../experiment/exp_example_advanced.yaml | 2 +- .../model/simple_mnist_classifier.yaml | 2 +- project/configs/trainer/default_trainer.yaml | 6 +- project/src/__init__.py | 1 + .../architectures/simple_mnist.py | 0 .../callbacks}/custom_callbacks.py | 0 .../callbacks}/wandb_callbacks.py | 77 ++++++------------- .../datamodules}/mnist_datamodule.py | 0 .../datasets/img_test_dataset.py | 0 .../models}/simple_mnist_classifier.py | 22 +++--- .../transforms/mnist_transforms.py | 0 project/template_utils/execute_sweep.py | 57 ++++++++------ project/template_utils/inference_example.py | 4 +- project/template_utils/initializers.py | 24 ++++-- project/test.py | 7 +- project/train.py | 6 ++ 23 files changed, 148 insertions(+), 120 deletions(-) create mode 100644 project/src/__init__.py rename project/{pytorch_modules => src}/architectures/simple_mnist.py (100%) rename project/{pytorch_modules/lightning_callbacks => src/callbacks}/custom_callbacks.py (100%) rename project/{pytorch_modules/lightning_callbacks => src/callbacks}/wandb_callbacks.py (70%) rename project/{pytorch_modules/lightning_datamodules => src/datamodules}/mnist_datamodule.py (100%) rename project/{pytorch_modules => src}/datasets/img_test_dataset.py (100%) rename project/{pytorch_modules/lightning_models => src/models}/simple_mnist_classifier.py (84%) rename project/{pytorch_modules => src}/transforms/mnist_transforms.py (100%) diff --git a/README.md b/README.md index 1da4dc5..89068c3 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Click on "Use this template" button above to initialize new repository. @@ -83,7 +83,7 @@ loggers: default_callbacks: ModelCheckpoint: 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) + 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: @@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: max_epochs: 10 model: load_from: - model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py" + model_path: "models/simple_mnist_classifier/simple_mnist_classifier.py" model_class: "LitModel" hparams: lr: 0.001 @@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: lin3_size: 128 datamodule: load_from: - datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py" + datamodule_path: "datamodules/mnist_datamodule/mnist_datamodule.py" datamodule_class: "MNISTDataModule" hparams: batch_size: 64 @@ -138,9 +138,9 @@ Each run configuration needs to contain sections `trainer`, `model` and `datamod Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)
-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/pytorch_modules/lightning_models/simple_mnist_classifier.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/src/models/simple_mnist_classifier.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/pytorch_modules/lightning_datamodules/mnist_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/src/datamodules/mnist_datamodule.py)).

diff --git a/conda_env.yaml b/conda_env.yaml index 7703647..7282075 100644 --- a/conda_env.yaml +++ b/conda_env.yaml @@ -1,8 +1,10 @@ #name: conda_env_name + channels: - pytorch - conda-forge - defaults + dependencies: - python=3.8 - pip diff --git a/project/configs/callbacks/default_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml index cc0ca4a..2d014b9 100644 --- a/project/configs/callbacks/default_callbacks.yaml +++ b/project/configs/callbacks/default_callbacks.yaml @@ -4,7 +4,7 @@ model_checkpoint: 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) + 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" filepath: "checkpoints/{epoch}" diff --git a/project/configs/callbacks/mnist_callbacks.yaml b/project/configs/callbacks/mnist_callbacks.yaml index dfa4e43..34e7b77 100644 --- a/project/configs/callbacks/mnist_callbacks.yaml +++ b/project/configs/callbacks/mnist_callbacks.yaml @@ -1,2 +1,5 @@ # @package _group_ +defaults: + - default_callbacks.yaml + - wandb_callbacks.yaml diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml index 70f8ea0..d9fbf88 100644 --- a/project/configs/callbacks/wandb_callbacks.yaml +++ b/project/configs/callbacks/wandb_callbacks.yaml @@ -1,18 +1,31 @@ # @package _group_ save_best_metric_scores_to_wandb: - class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb + class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb args: {} -save_code_to_wandb_as_artifact: - class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb - args: - code_dir: ${work_dir}/ +#save_confusion_matrix_to_wandb: +# class: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb +# args: +# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] +# +# +#save_f1_precision_recall_heatmap_to_wandb: +# class: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb +# args: +# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] -upload_ckpts_to_wandb_as_artifact: - class: pytorch_modules.lightning_callbacks.wandb_callbacks.UploadAllCheckpointsToWandb - args: - ckpt_dir: "checkpoints/" - upload_best_only: True +#upload_code_to_wandb_as_artifact: +# class: src.callbacks.wandb_callbacks.SaveCodeToWandb +# args: +# code_dir: ${work_dir}/ + + +#upload_ckpts_to_wandb_as_artifact: +# class: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb +# args: +# ckpt_dir: "checkpoints/" +# upload_best_only: True + diff --git a/project/configs/config.yaml b/project/configs/config.yaml index e450c51..dc7714a 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -23,7 +23,7 @@ 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 things that are logged by all loggers as hyperparameters extra_logs: log_seeds: True @@ -33,6 +33,6 @@ extra_logs: log_model_class: True log_optimizer_class: True log_datamodule_class: True + log_model_architecture_class: True - log_train_val_test_sizes: True - log_model_architecture_class_name: True + log_train_val_test_sizes: False diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml index f31d726..aa3240f 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: src.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 0d60efc..adab2d1 100644 --- a/project/configs/experiment/exp_example_advanced.yaml +++ b/project/configs/experiment/exp_example_advanced.yaml @@ -26,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: ${work_dir}/last.ckpt # use this to resume training from checkpoint + # resume_from_checkpoint: ${work_dir}/last.ckpt # path to checkpoint (this can be also url for download) model: args: # you can add here any params you want and then access them in lightning model diff --git a/project/configs/model/simple_mnist_classifier.yaml b/project/configs/model/simple_mnist_classifier.yaml index 10989d0..4d8f282 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: src.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 49c42d5..80a2f39 100644 --- a/project/configs/trainer/default_trainer.yaml +++ b/project/configs/trainer/default_trainer.yaml @@ -3,9 +3,11 @@ # 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 + gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only auto_select_gpus: True + max_epochs: 10 num_sanity_val_steps: 3 progress_bar_refresh_rate: 10 - weights_summary: null # null in yaml represents python None value + weights_summary: null # null in yaml represents python None value default_root_dir: "lightning_logs/" + auto_lr_find: False # "https://pytorch-lightning.readthedocs.io/en/stable/lr_finder.html" diff --git a/project/src/__init__.py b/project/src/__init__.py new file mode 100644 index 0000000..e24e3b1 --- /dev/null +++ b/project/src/__init__.py @@ -0,0 +1 @@ +# package file diff --git a/project/pytorch_modules/architectures/simple_mnist.py b/project/src/architectures/simple_mnist.py similarity index 100% rename from project/pytorch_modules/architectures/simple_mnist.py rename to project/src/architectures/simple_mnist.py diff --git a/project/pytorch_modules/lightning_callbacks/custom_callbacks.py b/project/src/callbacks/custom_callbacks.py similarity index 100% rename from project/pytorch_modules/lightning_callbacks/custom_callbacks.py rename to project/src/callbacks/custom_callbacks.py diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/src/callbacks/wandb_callbacks.py similarity index 70% rename from project/pytorch_modules/lightning_callbacks/wandb_callbacks.py rename to project/src/callbacks/wandb_callbacks.py index 10566e4..e7a867b 100644 --- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py +++ b/project/src/callbacks/wandb_callbacks.py @@ -47,7 +47,7 @@ class SaveMetricsHeatmapToWandb(Callback): Expects validation step to return predictions and targets. Works only for single label classification! """ - def __init__(self, class_names): + def __init__(self, class_names=None): self.class_names = class_names self.preds = [] self.targets = [] @@ -60,7 +60,7 @@ class SaveMetricsHeatmapToWandb(Callback): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """Gather data from single batch.""" if self.ready: - preds, targets = outputs["preds"], outputs["y"] + preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"] self.preds.append(preds) self.targets.append(targets) @@ -96,7 +96,7 @@ class SaveConfusionMatrixToWandb(Callback): Expects validation step to return predictions and targets. Works only for single label classification! """ - def __init__(self, class_names): + def __init__(self, class_names=None): self.class_names = class_names self.preds = [] self.targets = [] @@ -109,7 +109,7 @@ class SaveConfusionMatrixToWandb(Callback): def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): """Gather data from single batch.""" if self.ready: - preds, targets = outputs["preds"], outputs["y"] + preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"] self.preds.append(preds) self.targets.append(targets) @@ -119,17 +119,14 @@ class SaveConfusionMatrixToWandb(Callback): self.preds = torch.cat(self.preds).tolist() self.targets = torch.cat(self.targets).tolist() - 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}_{logger.id}": wandb.plot.confusion_matrix( - self.preds, - self.targets, - class_names=self.class_names) - }, commit=False) + for logger in trainer.logger.experiment: + if isinstance(logger, wandb_run): + logger.log({ + f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix( + preds=self.preds, + y_true=self.targets, + class_names=self.class_names) + }, commit=False) self.preds = [] self.targets = [] @@ -137,62 +134,34 @@ class SaveConfusionMatrixToWandb(Callback): class SaveBestMetricScoresToWandb(Callback): def __init__(self): - self.train_loss_list = [] - self.train_acc_list = [] self.train_loss_best = None self.train_acc_best = None - - self.val_loss_list = [] - self.val_acc_list = [] self.val_loss_best = None self.val_acc_best = None - self.ready = False - def clear_lists(self): - self.train_loss_list.clear() - self.train_acc_list.clear() - self.val_loss_list.clear() - self.val_acc_list.clear() - 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_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): - """Gather data from single batch.""" - # This is bugged :/ - lets wait for lightning 1.2 update - # if self.ready: - # self.train_loss_list.append(outputs["loss"]) - # self.train_acc_list.append(outputs["acc"]) - pass - - def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx): - """Gather data from single batch.""" - if self.ready: - self.val_loss_list.append(outputs["loss"]) - self.val_acc_list.append(outputs["acc"]) - def on_epoch_end(self, trainer, pl_module): if self.ready: for logger in trainer.logger.experiment: + metrics = trainer.callback_metrics if isinstance(logger, wandb_run): - # loss = sum(self.train_loss_list) / len(self.train_loss_list) - # acc = sum(self.train_acc_list) / len(self.train_acc_list) - # self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best - # self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best - # logger.log({"train_loss_best": self.train_loss_best}, commit=False) - # logger.log({"train_acc_best": self.train_acc_best}, commit=False) - - loss = sum(self.val_loss_list) / len(self.val_loss_list) - acc = sum(self.val_acc_list) / len(self.val_acc_list) - self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best - self.val_acc_best = acc if self.val_acc_best is None or acc > self.val_acc_best else self.val_acc_best + if self.train_loss_best is None or metrics["train_loss"] < self.train_loss_best: + self.train_loss_best = metrics["train_loss"] + if self.train_acc_best is None or metrics["train_acc"] > self.train_acc_best: + self.train_acc_best = metrics["train_acc"] + if self.val_loss_best is None or metrics["val_loss"] < self.val_loss_best: + self.val_loss_best = metrics["val_loss"] + if self.val_acc_best is None or metrics["val_acc"] > self.val_acc_best: + self.val_acc_best = metrics["val_acc"] + logger.log({"train_loss_best": self.train_loss_best}, commit=False) + logger.log({"train_acc_best": self.train_acc_best}, commit=False) logger.log({"val_loss_best": self.val_loss_best}, commit=False) logger.log({"val_acc_best": self.val_acc_best}, commit=False) - self.clear_lists() - # class SaveImagePredictionsToWandb(Callback): # """ diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/src/datamodules/mnist_datamodule.py similarity index 100% rename from project/pytorch_modules/lightning_datamodules/mnist_datamodule.py rename to project/src/datamodules/mnist_datamodule.py diff --git a/project/pytorch_modules/datasets/img_test_dataset.py b/project/src/datasets/img_test_dataset.py similarity index 100% rename from project/pytorch_modules/datasets/img_test_dataset.py rename to project/src/datasets/img_test_dataset.py diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/src/models/simple_mnist_classifier.py similarity index 84% rename from project/pytorch_modules/lightning_models/simple_mnist_classifier.py rename to project/src/models/simple_mnist_classifier.py index 0911e98..5b2ab93 100644 --- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py +++ b/project/src/models/simple_mnist_classifier.py @@ -1,11 +1,11 @@ -from sklearn.metrics import accuracy_score +from pytorch_lightning.metrics.classification import Accuracy +from template_utils.initializers import load_class import pytorch_lightning as pl import torch.nn.functional as F import torch -from template_utils.initializers import load_class # import custom architectures -from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier +from src.architectures.simple_mnist import SimpleMNISTClassifier class LitModel(pl.LightningModule): @@ -25,6 +25,8 @@ class LitModel(pl.LightningModule): self.model = SimpleMNISTClassifier(hparams=self.hparams) + self.accuracy = Accuracy() + def forward(self, x): return self.model(x) @@ -36,12 +38,11 @@ class LitModel(pl.LightningModule): # training metrics preds = torch.argmax(logits, dim=1) - acc = accuracy_score(preds.cpu(), y.cpu()) + acc = self.accuracy(preds, y) self.log('train_loss', loss, on_step=False, on_epoch=True) self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - # we can return here anything and then read it in some callback - return {"loss": loss, "acc": acc, "preds": preds, "y": y} + return loss # logic for a single validation step def validation_step(self, batch, batch_idx): @@ -51,11 +52,12 @@ class LitModel(pl.LightningModule): # validation metrics preds = torch.argmax(logits, dim=1) - acc = accuracy_score(preds.cpu(), y.cpu()) + acc = self.accuracy(preds, y) self.log('val_loss', loss, on_step=False, on_epoch=True) self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True) - return {"loss": loss, "acc": acc, "preds": preds, "y": y} + # we can return here anything and then read it in some callback + return {"batch_val_loss": loss, "batch_val_acc": acc, "batch_val_preds": preds, "batch_val_y": y} # logic for a single testing step def test_step(self, batch, batch_idx): @@ -65,11 +67,11 @@ class LitModel(pl.LightningModule): # test metrics preds = torch.argmax(logits, dim=1) - acc = accuracy_score(preds.cpu(), y.cpu()) + acc = self.accuracy(preds, y) self.log('test_loss', loss, on_step=False, on_epoch=True) self.log('test_acc', acc, on_step=False, on_epoch=True) - return {"loss": loss} + return loss def configure_optimizers(self): Optimizer = load_class(self.optimizer_config["class"]) diff --git a/project/pytorch_modules/transforms/mnist_transforms.py b/project/src/transforms/mnist_transforms.py similarity index 100% rename from project/pytorch_modules/transforms/mnist_transforms.py rename to project/src/transforms/mnist_transforms.py diff --git a/project/template_utils/execute_sweep.py b/project/template_utils/execute_sweep.py index c396584..505071f 100644 --- a/project/template_utils/execute_sweep.py +++ b/project/template_utils/execute_sweep.py @@ -1,31 +1,42 @@ # THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases # IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT! +# hydra imports +from omegaconf import DictConfig +import hydra + +# template utils imports +import template_utils.initializers as utils + import wandb -import train +from train import train -# Choose which run config to optimize -RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST" - -# Load configs -project_config = train.load_config("config.yaml") -run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME] - -# Initialize wandb -wandb.init() - # Replace run config hyperparameters with the ones loaded from wandb sweep server -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"]["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 +def replace_hparams(config, sweep_hparams): + for key, value in sweep_hparams.items(): + if key == "_wandb": + continue + elif key in config["trainer"]["args"]: + config["trainer"]["args"][key] = value + elif key in config["model"]["args"]: + config["model"]["args"][key] = value + elif key in config["optimizer"]["args"]: + config["optimizer"]["args"][key] = value + elif key in config["datamodule"]["args"]: + config["datamodule"]["args"][key] = value -# Execute run -train.train(project_config=project_config, run_config=run_config, use_wandb=True) + +@hydra.main(config_path="configs/", config_name="config.yaml") +def main(config: DictConfig) -> None: + wandb.init() + + sweep_hparams = wandb.Config._as_dict(wandb.config) + utils.show_config(config) # print content of config + + train(config) + wandb.finish() + + +if __name__ == "__main__": + main() diff --git a/project/template_utils/inference_example.py b/project/template_utils/inference_example.py index 755f349..fbee106 100644 --- a/project/template_utils/inference_example.py +++ b/project/template_utils/inference_example.py @@ -1,8 +1,8 @@ -from pytorch_modules.transforms import mnist_transforms +from src.transforms import mnist_transforms from PIL import Image # the LitModel you import should be the same as the one you used for training! -from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel +from src.models.simple_mnist_classifier import LitModel # ckpt can be a url! diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index d7bd4de..29288cd 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -138,11 +138,11 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase], log_hparams(loggers, config["datamodule"]["args"]) if "log_model_class" in extra_logs and extra_logs["log_model_class"]: - log_hparams(loggers, {"model_class": config["model"]["class"]}) + log_hparams(loggers, {"_class_model": config["model"]["class"]}) if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]: - log_hparams(loggers, {"optimizer_class": config["optimizer"]["class"]}) + log_hparams(loggers, {"_class_optimizer": config["optimizer"]["class"]}) if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]: - log_hparams(loggers, {"datamodule_class": config["datamodule"]["class"]}) + log_hparams(loggers, {"_class_datamodule": config["datamodule"]["class"]}) if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]: hparams = {} @@ -154,9 +154,10 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase], hparams["test_size"] = len(datamodule.data_test) log_hparams(loggers, hparams) - if "log_model_architecture_class_name" in extra_logs and extra_logs["log_model_architecture_class_name"]: + if "log_model_architecture_class" in extra_logs and extra_logs["log_model_architecture_class"]: if hasattr(model, "model"): - log_hparams(loggers, {"model_architecture_class_name": model.model.__class__.__name__}) + obj = model.model + log_hparams(loggers, {"_class_model_architecture": obj.__module__ + "." + obj.__class__.__name__}) def show_init_info(model, datamodule, callbacks, loggers): @@ -177,6 +178,19 @@ def show_init_info(model, datamodule, callbacks, loggers): log.info(message) +def auto_find_lr(trainer, model, datamodule, loggers): + lr_finder = trainer.tuner.lr_find(model=model, datamodule=datamodule) + new_lr = lr_finder.suggestion() + + # Save lr plot + fig = lr_finder.plot(suggest=True) + fig.savefig("lr_loss_curve.jpg") + + # Set new lr + model.hparams.lr = new_lr + log_hparams(loggers, {"lr": new_lr}) + + def show_config(config: DictConfig): log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") diff --git a/project/test.py b/project/test.py index 5c3af3c..b8e67e6 100644 --- a/project/test.py +++ b/project/test.py @@ -21,13 +21,18 @@ def my_app(cfg: DictConfig) -> None: def test_logger(): logger = WandbLogger() print(logger) + print(logger.__class__) + print(logger.__class__.__name__) + print(logger.__module__) + print(logger.__module__ + "." + logger.__class__.__name__) if __name__ == "__main__": my_app() + # with open("epoch=0.ckpt", "rb") as file: # data = torch.load(file) # print(data) - # test_logger() + test_logger() diff --git a/project/train.py b/project/train.py index 6cf1e1d..fb13b73 100644 --- a/project/train.py +++ b/project/train.py @@ -16,6 +16,7 @@ import template_utils.initializers as utils def train(config): + # Validate the correctness of loaded config utils.validate_config(config=config) # Set global PyTorch seed @@ -56,6 +57,7 @@ def train(config): callbacks=callbacks ) + # Log info in terminal about all initialized objects utils.show_init_info(model, datamodule, callbacks, loggers) # Init PyTorch Lightning trainer ⚡ @@ -65,6 +67,10 @@ def train(config): loggers=loggers ) + # Automatically find learning rate if specified in config + if "auto_lr_find" in config["trainer"]["args"] and config["trainer"]["args"]["auto_lr_find"]: + utils.auto_find_lr(trainer, model, datamodule, loggers) + # Train the model trainer.fit(model=model, datamodule=datamodule) From f90ceab6051cb53d98d1d0f40dbb9d69b9eeb3ce Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 12 Jan 2021 22:13:11 +0100 Subject: [PATCH 13/15] update readme --- README.md | 311 ++++++++++-------- .../configs/callbacks/default_callbacks.yaml | 2 +- project/configs/config.yaml | 5 +- project/configs/trainer/debug_trainer.yaml | 2 +- project/src/callbacks/wandb_callbacks.py | 15 +- 5 files changed, 200 insertions(+), 135 deletions(-) diff --git a/README.md b/README.md index 89068c3..282fa7c 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,26 @@ ## Deep learning project template -A convenient starting template for most deep learning projects. Built with PyTorch Lightning and Weights&Biases.
+A convenient starting template and pipeline for deep learning projects. Built with PyTorch Lightning, Hydra and Weights&Biases.
Click on "Use this template" button above to initialize new repository.
## Features - Predefined folder structure -- Storing project configuration in a convenient way ([project_config.yaml](project_config.yaml)) -- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml)) -- All advantages of PyTorch Lightning +- Automates loading of PyTorch Lightning modules - you only need to create model and datamodule and specify them in configuration files +- All advantages of Hydra: + - Main config file contains default configuration used when executing command `python train.py` ([config.yaml](project/configs/config.yaml)) + - Storing many experiment configurations in a convenient way - experiments override chosen parameters from default configuration ([configs/experiment](project/configs/experiment)) + - Composing configuration files out of other configuration files + - Scheduling execution of many experiments + - Overriding any config parameter from command line + - Command line tab completion + - Logging history of all executed runs - Weights&Biases integration: - - ~~Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud~~ (TODO) - - Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py)) -- Automates the whole training process, you only need to create model and datamodule and specify them in [run_configs.yaml](project/run_configs.yaml) -- Scheduling execution of many runs/experiments ([execute_all_runs.py](project/template_utils/execute_all_experiments.py)) + - Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud + - Useful callbacks ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py)) + - ~~Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))~~ (TODO) - Built in requirements ([requirements.txt](requirements.txt)) - Built in conda environment initialization ([conda_env.yaml](conda_env.yaml)) - Built in package setup ([setup.py](setup.py)) - Example with MNIST digits classification -- Useful example callbacks ([callbacks.py](project/src/callbacks/custom_callbacks.py))
@@ -24,137 +28,180 @@ Click on "Use this template" button above to initialize new repository. + + +## Main project configuration file ([config.yaml](project/configs/config.yaml)) +```yaml +# specify here default training configuration +defaults: + - trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder + - model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder + - datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder + - optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder + - seeds: default_seeds.yaml # set this to null if you don't want to use seeds + - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks + - logger: null # set this to null if you don't want to use loggers + +# 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: + dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} + sweep: + dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S} + subdir: ${hydra.job.num} + +# extra things that are logged by all loggers as hyperparameters +extra_logs: + log_seeds: True + + log_trainer_args: False + log_datamodule_args: True + + log_model_class: True + log_optimizer_class: True + log_datamodule_class: True + log_model_architecture_class: True + + log_train_val_test_sizes: False +``` +
+ + +## Experiment configuration ([configs/experiment](project/configs/experiment)) +You can store many experiment configurations in this folder.
+Example experiment configuration: +```yaml +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 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 + +# all parameters below will be merged with parameters from default configurations set above +# this allows you to overwrite only specified parameters + +seeds: + pytorch_seed: 12345 + +trainer: + args: + max_epochs: 10 + +model: + args: + input_size: 784 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + +datamodule: + args: + batch_size: 32 + train_val_test_split: [55_000, 5_000, 10_000] + +optimizer: + args: + lr: 0.001 + weight_decay: 0.00001 +``` +To execute this experiment run: +```bash +python train.py +experiment=exp_example_simple +``` +
+ + +## Logs +Logs are created automatically with the following structure: +``` +├── logs +│ ├── runs # Folder for logs generated from single runs +│ │ ├── 2021-02-15 # Date of executing run +│ │ │ ├── 16-50-49 # Hour of executing run +│ │ │ │ ├── .hydra # Hydra logs +│ │ │ │ ├── wandb # Weights&Biases logs +│ │ │ │ └── checkpoints # Training checkpoints +│ │ │ │ +│ │ │ ├── ... │ │ │ └── ... │ │ ├── ... │ │ └── ... │ │ -│ ├── models <- All your models should be located here! -│ │ ├── 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' +│ ├── multiruns # Folder for logs generated from sweeps +│ │ ├── 2021-02-15_16-50-49 # Date and hour of executing run +│ │ │ ├── 0 # Job number +│ │ │ │ ├── .hydra # Hydra logs +│ │ │ │ ├── wandb # Weights&Biases logs +│ │ │ │ └── checkpoints # Training checkpoints +│ │ │ ├── 1 +│ │ │ ├── 2 +│ │ │ └── ... │ │ ├── ... │ │ └── ... │ │ -│ ├── project_config.yaml <- Project configuration -│ ├── run_configs.yaml <- Configurations of different runs/experiments -│ └── train.py <- Train model with chosen run configuration -│ -├── .gitignore -├── LICENSE -├── README.md -├── conda_env.yaml -├── requirements.txt -└── setup.py ```
-## Project config parameters ([project_config.yaml](project_config.yaml)) -Example project configuration: -```yaml -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 - -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" - 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" - -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 -``` -
- - -## Run config parameters ([run_configs.yaml](project/run_configs.yaml)) -You can store many run configurations in this file.
-Example run configuration: -```yaml -SIMPLE_CONFIG_EXAMPLE_MNIST: - seed: 1234 - trainer: - args: - max_epochs: 10 - model: - load_from: - model_path: "models/simple_mnist_classifier/simple_mnist_classifier.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/mnist_datamodule.py" - datamodule_class: "MNISTDataModule" - hparams: - 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` - -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)
- - -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/src/models/simple_mnist_classifier.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/src/datamodules/mnist_datamodule.py)).
-
- - ## Workflow 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 any hyperparameters you want! -3. Configure your project in [project_config.yaml](project_config.yaml) +3. Create new experiment config in [configs/experiment](project/configs/experiment) 4. Run training with chosen run config
```bash - python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST + python train.py +experiment=experiment_name.yaml ```

@@ -191,29 +238,32 @@ conda activate your_env_name # install requirements pip install -r requirements.txt + +pip install hydra-core --upgrade --pre ``` -Next, you can train model without logging +Next, you can train model with default configuration without logging ```bash -# train model without Weights&Biases -# choose run config name from project/run_configs.yaml cd project -python train.py --no_wandb --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST +python train.py ``` -Or you can train model with Weights&Biases logging +Or you can train model with chosen logger like Weights&Biases ```yaml -# set project and entity names in project/config.yaml -loggers: - wandb: +# set project and entity names in project/configs/logger/wandb.yaml +wandb: + args: project: "your_project_name" - entity: "your_wandb_username_or_team" + entity: "your_wandb_team_name" ``` ```bash # train model with Weights&Biases -# choose run config name from project/run_configs.yaml -cd project -python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST +python train.py logger=wandb.yaml +``` + +Or you can train model with chosen experiment config +```bash +python train.py +experiment=exp_example_simple.yaml ``` Optionally you can install project as a package with [setup.py](setup.py) @@ -234,5 +284,6 @@ pip install -e . - run training:
`right click on train.py file -> "Run 'train'"` + #### VS Code setup - TODO diff --git a/project/configs/callbacks/default_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml index 2d014b9..daffe78 100644 --- a/project/configs/callbacks/default_callbacks.yaml +++ b/project/configs/callbacks/default_callbacks.yaml @@ -4,7 +4,7 @@ model_checkpoint: 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 models (determined by above metric) + save_top_k: 2 # 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" filepath: "checkpoints/{epoch}" diff --git a/project/configs/config.yaml b/project/configs/config.yaml index dc7714a..ef1deac 100644 --- a/project/configs/config.yaml +++ b/project/configs/config.yaml @@ -6,9 +6,12 @@ defaults: - datamodule: mnist_datamodule.yaml - optimizer: adam.yaml - seeds: default_seeds.yaml # set this to null if you don't want to use seeds - - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks + - 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`) + - override hydra/job_logging: colorlog + - override hydra/hydra_logging: colorlog + # path to working directory (the directory that `train.py` was executed from in command line) work_dir: ${hydra:runtime.cwd} diff --git a/project/configs/trainer/debug_trainer.yaml b/project/configs/trainer/debug_trainer.yaml index 3a8f840..8cfe1ed 100644 --- a/project/configs/trainer/debug_trainer.yaml +++ b/project/configs/trainer/debug_trainer.yaml @@ -5,7 +5,7 @@ args: gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only auto_select_gpus: True - fast_dev_run: True +# fast_dev_run: True # bugged :( limit_train_batches: 1.0 limit_val_batches: 1.0 limit_test_batches: 1.0 diff --git a/project/src/callbacks/wandb_callbacks.py b/project/src/callbacks/wandb_callbacks.py index e7a867b..0018ed3 100644 --- a/project/src/callbacks/wandb_callbacks.py +++ b/project/src/callbacks/wandb_callbacks.py @@ -10,7 +10,7 @@ import os class SaveCodeToWandb(Callback): """ - Upload all *.py files to wandb at the beginning of the run. + Upload all *.py files to wandb as an artifact at the beginning of the run. """ def __init__(self, code_dir: str): self.code_dir = code_dir @@ -24,6 +24,9 @@ class SaveCodeToWandb(Callback): class UploadAllCheckpointsToWandb(Callback): + """ + Upload experiment checkpoints to wandb as an artifact at the end of training. + """ def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False): self.ckpt_dir = ckpt_dir self.upload_best_only = upload_best_only @@ -43,7 +46,7 @@ class UploadAllCheckpointsToWandb(Callback): class SaveMetricsHeatmapToWandb(Callback): """ - Generate f1, precision and recall heatmap from validation epoch outputs. + Generate f1, precision and recall heatmap from validation step outputs. Expects validation step to return predictions and targets. Works only for single label classification! """ @@ -133,6 +136,14 @@ class SaveConfusionMatrixToWandb(Callback): class SaveBestMetricScoresToWandb(Callback): + """ + Store in wandb: + - max train acc + - min train loss + - max val acc + - min val loss + Useful for comparing runs in table views, as wandb doesn't currently supports column aggregation. + """ def __init__(self): self.train_loss_best = None self.train_acc_best = None From f8dd90ec7dd437c2cf20bb0fe6cb0f877783e200 Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 12 Jan 2021 22:18:03 +0100 Subject: [PATCH 14/15] fix structure --- project/logs/.gitkeep | 0 project/test.py | 38 -------------------------------------- 2 files changed, 38 deletions(-) create mode 100644 project/logs/.gitkeep delete mode 100644 project/test.py diff --git a/project/logs/.gitkeep b/project/logs/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/project/test.py b/project/test.py deleted file mode 100644 index b8e67e6..0000000 --- a/project/test.py +++ /dev/null @@ -1,38 +0,0 @@ -import torch -import yaml -from omegaconf import DictConfig, OmegaConf -import hydra.conf.hydra.output -from hydra.experimental import initialize, compose -import comet_ml -from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger -import logging - - -log = logging.getLogger(__name__) - - -@hydra.main(config_path="configs/", config_name="config.yaml") -def my_app(cfg: DictConfig) -> None: - # pass - # print(cfg) - log.info(OmegaConf.to_yaml(cfg, resolve=True)) - - -def test_logger(): - logger = WandbLogger() - print(logger) - print(logger.__class__) - print(logger.__class__.__name__) - print(logger.__module__) - print(logger.__module__ + "." + logger.__class__.__name__) - - -if __name__ == "__main__": - my_app() - - - # with open("epoch=0.ckpt", "rb") as file: - # data = torch.load(file) - # print(data) - - test_logger() From 85688007b943a93208102b315996de8b0daec802 Mon Sep 17 00:00:00 2001 From: Lucas Date: Tue, 12 Jan 2021 22:35:20 +0100 Subject: [PATCH 15/15] Update README.md --- README.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 282fa7c..9ee536e 100644 --- a/README.md +++ b/README.md @@ -4,17 +4,17 @@ Click on "Use this template" button above to initialize new repository. Example experiment configuration: ```yaml 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 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 + - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' + - override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' + - override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' + - override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' + - override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' + - override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' + - override /logger: null # choose logger from 'configs/logger/' # all parameters below will be merged with parameters from default configurations set above # this allows you to overwrite only specified parameters