From fa8b9ecc16403dc89e485e82077cf1db2064298b Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Tue, 29 Dec 2020 01:48:44 +0100 Subject: [PATCH] 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,