diff --git a/README.md b/README.md
index 62f2d01..9ee536e 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/project_config.yaml))
-- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml))
-- All advantages of PyTorch Lightning
+- Automates training with PyTorch Lightning - you only need to create model and datamodule and specify them in configuration files
+- All advantages of Hydra:
+ - Main config file contains default training configuration ([config.yaml](project/configs/config.yaml))
+ - Storing many experiment configurations in a convenient way - experiments override chosen parameters from default training 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_runs.py))
+ - Automatically stores all code files, 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/template_utils/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/'
+ - 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
+
+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/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/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 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/models/simple_mnist_classifier/lightning_module.py)).
-
-Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).
-
-
-
## 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/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/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/conda_env.yaml b/conda_env.yaml
index e5f8012..7282075 100644
--- a/conda_env.yaml
+++ b/conda_env.yaml
@@ -1,11 +1,14 @@
#name: conda_env_name
+
channels:
- pytorch
- conda-forge
- defaults
+
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
new file mode 100644
index 0000000..daffe78
--- /dev/null
+++ b/project/configs/callbacks/default_callbacks.yaml
@@ -0,0 +1,19 @@
+# @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: 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}"
+
+
+early_stopping:
+ 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
+ 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
new file mode 100644
index 0000000..34e7b77
--- /dev/null
+++ b/project/configs/callbacks/mnist_callbacks.yaml
@@ -0,0 +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
new file mode 100644
index 0000000..d9fbf88
--- /dev/null
+++ b/project/configs/callbacks/wandb_callbacks.yaml
@@ -0,0 +1,31 @@
+# @package _group_
+
+save_best_metric_scores_to_wandb:
+ class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
+ args: {}
+
+
+#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_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
new file mode 100644
index 0000000..ef1deac
--- /dev/null
+++ b/project/configs/config.yaml
@@ -0,0 +1,41 @@
+# @package _global_
+
+defaults:
+ - trainer: default_trainer.yaml
+ - model: simple_mnist_classifier.yaml
+ - 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
+ - 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}
+
+# 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
diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml
new file mode 100644
index 0000000..aa3240f
--- /dev/null
+++ b/project/configs/datamodule/mnist_datamodule.yaml
@@ -0,0 +1,8 @@
+# @package _group_
+
+class: src.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/experiment/exp_example_advanced.yaml b/project/configs/experiment/exp_example_advanced.yaml
new file mode 100644
index 0000000..adab2d1
--- /dev/null
+++ b/project/configs/experiment/exp_example_advanced.yaml
@@ -0,0 +1,59 @@
+# @package _global_
+
+# to execute this experiment run:
+# python train.py +experiment=exp_example_advanced
+
+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
+
+seeds:
+ pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule)
+
+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.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: ${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
+ 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:
+ 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
+
+logger:
+ wandb:
+ args: # you can add here additional logger arguments specific for this experiment
+ tags: ["best_model", "uwu"]
+ notes: "Description of this model."
+ group: ""
+ comet:
+ args:
+ tags: ["best_model"]
diff --git a/project/configs/experiment/exp_example_simple.yaml b/project/configs/experiment/exp_example_simple.yaml
new file mode 100644
index 0000000..9f3d6ea
--- /dev/null
+++ b/project/configs/experiment/exp_example_simple.yaml
@@ -0,0 +1,38 @@
+# @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 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
+
+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/logger/all_loggers.yaml b/project/configs/logger/all_loggers.yaml
new file mode 100644
index 0000000..76af7ec
--- /dev/null
+++ b/project/configs/logger/all_loggers.yaml
@@ -0,0 +1,8 @@
+# @package _group_
+
+# Train with all logger at once
+defaults:
+ - csv_logger.yaml
+ - wandb.yaml
+ # - comet.yaml
+# - tensorboard.yaml
diff --git a/project/configs/logger/comet.yaml b/project/configs/logger/comet.yaml
new file mode 100644
index 0000000..39a12dc
--- /dev/null
+++ b/project/configs/logger/comet.yaml
@@ -0,0 +1,8 @@
+# @package _group_
+
+# Comet logger config
+comet:
+ class: pytorch_lightning.logger.CometLogger
+ args:
+ api_key: ???
+ project_name: "project_template_test"
diff --git a/project/configs/logger/csv_logger.yaml b/project/configs/logger/csv_logger.yaml
new file mode 100644
index 0000000..88d2dea
--- /dev/null
+++ b/project/configs/logger/csv_logger.yaml
@@ -0,0 +1,8 @@
+# @package _group_
+
+# Csv logger config
+csv_logger:
+ class: pytorch_lightning.loggers.CSVLogger
+ args:
+ save_dir: "."
+ name: "csv_logger/"
diff --git a/project/configs/logger/tensorboard.yaml b/project/configs/logger/tensorboard.yaml
new file mode 100644
index 0000000..543d590
--- /dev/null
+++ b/project/configs/logger/tensorboard.yaml
@@ -0,0 +1,6 @@
+# @package _group_
+
+# Tensorboard logger config
+tensorboard:
+ class: pytorch_lightning.logger.TensorboardLogger
+ args: {}
diff --git a/project/configs/logger/wandb.yaml b/project/configs/logger/wandb.yaml
new file mode 100644
index 0000000..a9fa46f
--- /dev/null
+++ b/project/configs/logger/wandb.yaml
@@ -0,0 +1,11 @@
+# @package _group_
+
+# Weights&Biases logger config
+wandb:
+ class: pytorch_lightning.loggers.wandb.WandbLogger
+ args:
+ project: "env_tests"
+# 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/model/simple_mnist_classifier.yaml b/project/configs/model/simple_mnist_classifier.yaml
new file mode 100644
index 0000000..4d8f282
--- /dev/null
+++ b/project/configs/model/simple_mnist_classifier.yaml
@@ -0,0 +1,12 @@
+# @package _group_
+
+class: src.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
+
diff --git a/project/configs/optimizer/adam.yaml b/project/configs/optimizer/adam.yaml
new file mode 100644
index 0000000..f325327
--- /dev/null
+++ b/project/configs/optimizer/adam.yaml
@@ -0,0 +1,6 @@
+# @package _group_
+
+class: torch.optim.Adam
+args:
+ lr: 0.001
+ weight_decay: 0.000001
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
new file mode 100644
index 0000000..8cfe1ed
--- /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 # bugged :(
+ 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: "full"
+ default_root_dir: "lightning_logs/"
diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml
new file mode 100644
index 0000000..80a2f39
--- /dev/null
+++ b/project/configs/trainer/default_trainer.yaml
@@ -0,0 +1,13 @@
+# @package _group_
+
+# 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
+ max_epochs: 10
+ num_sanity_val_steps: 3
+ progress_bar_refresh_rate: 10
+ 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/datamodules/.gitkeep b/project/datamodules/.gitkeep
deleted file mode 100644
index e69de29..0000000
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
deleted file mode 100644
index ff29583..0000000
--- a/project/project_config.yaml
+++ /dev/null
@@ -1,44 +0,0 @@
-# set -1 to train on all GPUs abailable, set 0 to train on CPU only
-num_of_gpus: -1
-
-
-# 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 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
-# 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_last: True # additionaly always save model from last epoch
- mode: "max" # can be "max" or "min"
- EarlyStopping: # name of PyTorch Lightning class for early stopping callback
- monitor: "val_acc" # name of the logged metric which determines when model is improving
- patience: 5 # how many epochs of not improving until training stops
- mode: "max" # can be "max" or "min"
-
-
-# configure things which are printed in terminal
-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
-
-
-# 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/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/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/models/simple_mnist_classifier/models.py b/project/src/architectures/simple_mnist.py
similarity index 100%
rename from project/models/simple_mnist_classifier/models.py
rename to project/src/architectures/simple_mnist.py
diff --git a/project/template_utils/callbacks.py b/project/src/callbacks/custom_callbacks.py
similarity index 94%
rename from project/template_utils/callbacks.py
rename to project/src/callbacks/custom_callbacks.py
index 31785a2..4a94532 100644
--- a/project/template_utils/callbacks.py
+++ b/project/src/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/src/callbacks/wandb_callbacks.py b/project/src/callbacks/wandb_callbacks.py
new file mode 100644
index 0000000..0018ed3
--- /dev/null
+++ b/project/src/callbacks/wandb_callbacks.py
@@ -0,0 +1,201 @@
+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 torch
+import wandb
+import glob
+import os
+
+
+class SaveCodeToWandb(Callback):
+ """
+ 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
+
+ def on_sanity_check_end(self, trainer, pl_module):
+ """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 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
+
+ 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):
+ """
+ Generate f1, precision and recall heatmap from validation step outputs.
+ Expects validation step to return predictions and targets.
+ Works only for single label classification!
+ """
+ def __init__(self, class_names=None):
+ self.class_names = class_names
+ self.preds = []
+ self.targets = []
+ self.ready = False
+
+ def on_sanity_check_end(self, trainer, pl_module):
+ """Start executing this callback only after all validation sanity checks end."""
+ self.ready = True
+
+ def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
+ """Gather data from single batch."""
+ if self.ready:
+ preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
+ self.preds.append(preds)
+ self.targets.append(targets)
+
+ def on_validation_epoch_end(self, trainer, pl_module):
+ """Generate f1, precision and recall heatmap."""
+ if self.ready:
+ self.preds = torch.cat(self.preds).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)
+
+ logger = None
+ for some_logger in trainer.logger.experiment:
+ if isinstance(some_logger, wandb_run):
+ logger = some_logger
+
+ logger.log({
+ f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap(
+ x_labels=self.class_names,
+ y_labels=["f1", "precision", "recall"],
+ matrix_values=[f1, p, r],
+ show_text=True,
+ )}, commit=False)
+
+ self.preds = []
+ self.targets = []
+
+
+class SaveConfusionMatrixToWandb(Callback):
+ """
+ Generate Confusion Matrix.
+ Expects validation step to return predictions and targets.
+ Works only for single label classification!
+ """
+ def __init__(self, class_names=None):
+ self.class_names = class_names
+ self.preds = []
+ self.targets = []
+ self.ready = False
+
+ def on_sanity_check_end(self, trainer, pl_module):
+ """Start executing this callback only after all validation sanity checks end."""
+ self.ready = True
+
+ def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
+ """Gather data from single batch."""
+ if self.ready:
+ preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
+ self.preds.append(preds)
+ self.targets.append(targets)
+
+ def on_validation_epoch_end(self, trainer, pl_module):
+ """Generate f1, precision and recall heatmap."""
+ if self.ready:
+ self.preds = torch.cat(self.preds).tolist()
+ self.targets = torch.cat(self.targets).tolist()
+
+ 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 = []
+
+
+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
+ self.val_loss_best = None
+ self.val_acc_best = None
+ self.ready = False
+
+ def on_sanity_check_end(self, trainer, pl_module):
+ """Start executing this callback only after all validation sanity checks end."""
+ self.ready = True
+
+ def on_epoch_end(self, trainer, pl_module):
+ if self.ready:
+ for logger in trainer.logger.experiment:
+ metrics = trainer.callback_metrics
+ if isinstance(logger, wandb_run):
+ 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)
+
+
+# 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/datamodules/mnist_datamodule/datamodule.py b/project/src/datamodules/mnist_datamodule.py
similarity index 74%
rename from project/datamodules/mnist_datamodule/datamodule.py
rename to project/src/datamodules/mnist_datamodule.py
index 3470394..113b280 100644
--- a/project/datamodules/mnist_datamodule/datamodule.py
+++ b/project/src/datamodules/mnist_datamodule.py
@@ -7,20 +7,19 @@ 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. (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):
+ 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 # 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["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/datamodules/mnist_datamodule/datasets.py b/project/src/datasets/img_test_dataset.py
similarity index 100%
rename from project/datamodules/mnist_datamodule/datasets.py
rename to project/src/datasets/img_test_dataset.py
diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/src/models/simple_mnist_classifier.py
similarity index 55%
rename from project/models/simple_mnist_classifier/lightning_module.py
rename to project/src/models/simple_mnist_classifier.py
index 7a981b2..5b2ab93 100644
--- a/project/models/simple_mnist_classifier/lightning_module.py
+++ b/project/src/models/simple_mnist_classifier.py
@@ -1,31 +1,32 @@
-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
-# import custom models
-from models.simple_mnist_classifier.models import *
+# import custom architectures
+from src.architectures.simple_mnist import SimpleMNISTClassifier
class LitModel(pl.LightningModule):
"""
- This is example of lightning model for MNIST digits classification.
-
- The path to model should be specified in your run config. (run_configs.yaml)
- The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
-
+ This is example of lightning model for MNIST classification.
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):
+ def __init__(self, model_config, optimizer_config):
super().__init__()
-
- if hparams:
- self.save_hyperparameters(hparams)
+ hparams = {**model_config["args"], **optimizer_config["args"]}
+ self.save_hyperparameters(hparams)
+ self.optimizer_config = optimizer_config
self.model = SimpleMNISTClassifier(hparams=self.hparams)
+ self.accuracy = Accuracy()
+
def forward(self, x):
return self.model(x)
@@ -37,10 +38,9 @@ class LitModel(pl.LightningModule):
# training metrics
preds = torch.argmax(logits, dim=1)
- preds, y = preds.cpu(), y.cpu()
- acc = accuracy_score(preds, y)
- 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)
+ 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)
return loss
@@ -52,13 +52,12 @@ class LitModel(pl.LightningModule):
# validation metrics
preds = torch.argmax(logits, dim=1)
- preds, y = preds.cpu(), y.cpu()
- acc = accuracy_score(preds, y)
- 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)
+ 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)
# we can return here anything and then read it in some callback
- return preds, y
+ 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):
@@ -68,12 +67,12 @@ class LitModel(pl.LightningModule):
# test metrics
preds = torch.argmax(logits, dim=1)
- preds, y = preds.cpu(), y.cpu()
- acc = accuracy_score(preds, y)
- 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)
+ 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
def configure_optimizers(self):
- return torch.optim.Adam(self.parameters(), lr=self.hparams["lr"], weight_decay=self.hparams["weight_decay"])
+ Optimizer = load_class(self.optimizer_config["class"])
+ return Optimizer(self.parameters(), **self.optimizer_config["args"])
diff --git a/project/datamodules/mnist_datamodule/transforms.py b/project/src/transforms/mnist_transforms.py
similarity index 61%
rename from project/datamodules/mnist_datamodule/transforms.py
rename to project/src/transforms/mnist_transforms.py
index 7b22102..7ab835b 100644
--- a/project/datamodules/mnist_datamodule/transforms.py
+++ b/project/src/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
@@ -9,5 +9,5 @@ mnist_train_transforms = transforms.Compose([
])
mnist_test_transforms = transforms.Compose([
- transforms.ToTensor()
+ transforms.ToTensor(),
])
diff --git a/project/template_utils/execute_all_runs.py b/project/template_utils/execute_all_runs.py
deleted file mode 100644
index 193f9e6..0000000
--- a/project/template_utils/execute_all_runs.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# 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
-
-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, "project_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/execute_sweep.py b/project/template_utils/execute_sweep.py
index 7a205ab..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("project_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/hydra_config_schema.py b/project/template_utils/hydra_config_schema.py
new file mode 100644
index 0000000..55f1dc3
--- /dev/null
+++ 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 78%
rename from project/template_utils/predict_example.py
rename to project/template_utils/inference_example.py
index 8f31156..fbee106 100644
--- a/project/template_utils/predict_example.py
+++ b/project/template_utils/inference_example.py
@@ -1,8 +1,10 @@
-from datamodules.mnist_datamodule import 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 models.simple_mnist_classifier.lightning_module import LitModel
+from src.models.simple_mnist_classifier import LitModel
+
+# ckpt can be a url!
def predict():
@@ -10,7 +12,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"
@@ -27,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/template_utils/initializers.py b/project/template_utils/initializers.py
index cd493d2..29288cd 100644
--- a/project/template_utils/initializers.py
+++ b/project/template_utils/initializers.py
@@ -1,290 +1,205 @@
# pytorch lightning imports
-from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
-from pytorch_lightning.profiler import SimpleProfiler
+from pytorch_lightning.loggers.wandb import WandbLogger
import pytorch_lightning as pl
+# hydra imports
+from omegaconf import DictConfig, OmegaConf
+
# normal imports
-from typing import List, Tuple
-import importlib.util
-import os
+from typing import List
+import importlib
+import logging
-# 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
+log = logging.getLogger(__name__)
-def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]:
+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 `{class_path}`.'
+ return getattr(module, obj_name)
+
+
+def init_object(class_path, args) -> object:
+ return load_class(class_path)(**args)
+
+
+def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule:
"""
- Convert all config paths to absolute paths relatively to base_dir and normalize them.
+ Load LightningModule from path specified in config.
"""
-
- if not os.path.isabs(project_config["data_dir"]):
- project_config["data_dir"] = \
- os.path.normpath(os.path.join(base_dir, project_config["data_dir"]))
-
- if not os.path.isabs(project_config["logs_dir"]):
- project_config["logs_dir"] =\
- os.path.normpath(os.path.join(base_dir, project_config["logs_dir"]))
-
- if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
- run_config["model"]["load_from"]["model_path"] = \
- os.path.normpath(os.path.join(base_dir, run_config["model"]["load_from"]["model_path"]))
-
- if not os.path.isabs(run_config["datamodule"]["load_from"]["datamodule_path"]):
- run_config["datamodule"]["load_from"]["datamodule_path"] = \
- os.path.normpath(os.path.join(base_dir, run_config["datamodule"]["load_from"]["datamodule_path"]))
-
- return project_config, run_config
-
-
-def init_model(model_config: dict) -> pl.LightningModule:
- """
- Load LightningModule from path specified in run config.
- """
-
- 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)
-
+ model_class = model_config["class"]
+ LitModel = load_class(model_class)
assert issubclass(LitModel, pl.LightningModule), \
- f"specified model class '{model_class}' is not a 'LightningModule' type"
-
- model = LitModel(hparams=model_config["hparams"])
-
- return model
+ f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
+ return LitModel(model_config=model_config, optimizer_config=optimizer_config)
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_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_class = datamodule_config["class"]
+ datamodule_args = datamodule_config["args"]
+ DataModule = load_class(datamodule_class)
assert issubclass(DataModule, pl.LightningDataModule), \
- f"specified datamodule class '{datamodule_class}' is not a 'LightningDataModule' type"
-
- datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"])
+ f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
+ 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_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 callbacks
callbacks=callbacks,
-
- # resume training from checkpoint if it was set in the run config
- resume_from_checkpoint=resume_from_checkpoint
- if resume_from_checkpoint != "None"
- and resume_from_checkpoint != "False"
- and resume_from_checkpoint is not False
- else None,
-
- # print related
- progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
- profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
- weights_summary=project_config["printing"]["weights_summary"],
-
- # number of validation sanity checks
- num_sanity_val_steps=3,
-
- # default log dir if no logger is found
- default_root_dir=os.path.join(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(callbacks_config: dict) -> List[pl.Callback]:
"""
- Initialize default callbacks and callbacks specified in run config.
+ Initialize callbacks specified in config.
"""
-
- default_callbacks = project_config.get("default_callbacks", {})
- run_callbacks = run_config.get("callbacks", {})
-
- # namespaces in which callbacks will be searched for
- namespaces = [
- lightning_callbacks,
- custom_callbacks,
- wandb_callbacks,
- ]
-
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]
-
- 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():
+ 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
-def init_loggers(project_config: dict,
- run_config: dict,
- model: pl.LightningModule,
- datamodule: pl.LightningDataModule,
- use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
+def init_loggers(loggers_config: dict) -> List[pl.loggers.LightningLoggerBase]:
"""
- Initialize loggers.
+ Initialize loggers specified in config.
"""
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)
-
+ for logger_name, logger_conf in loggers_config.items():
+ class_path = logger_conf.get("class", None)
+ if class_path:
+ 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_logger(project_config: dict,
- run_config: dict,
- model: pl.LightningModule,
- datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
- """
- Initialize Weights&Biases logger.
- """
+def get_wandb_logger(loggers: List[pl.loggers.LightningLoggerBase]) -> WandbLogger:
+ for logger in loggers:
+ if isinstance(logger, WandbLogger):
+ return 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_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"])
-
- if hasattr(model, 'model'):
- if project_config["loggers"]["wandb"]["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 project_config["loggers"]["wandb"]["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"])
- return wandb_logger
+def log_hparams(loggers: List[pl.loggers.LightningLoggerBase], hparams: dict):
+ for logger in loggers:
+ logger.log_hyperparams(hparams)
-def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
- """Initialize tensorboard logger"""
+def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
+ config: dict,
+ model: pl.LightningModule,
+ datamodule: pl.LightningDataModule,
+ callbacks: List[pl.callbacks.Callback]):
+ 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, {"_class_model": config["model"]["class"]})
+ if "log_optimizer_class" in extra_logs and extra_logs["log_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, {"_class_datamodule": 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" in extra_logs and extra_logs["log_model_architecture_class"]:
+ if hasattr(model, "model"):
+ obj = model.model
+ log_hparams(loggers, {"_class_model_architecture": obj.__module__ + "." + obj.__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 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)}")
+
+
+def validate_config(config: dict):
# TODO
- return None
+ pass
+
+
+def validate_obj_config(obj_config: dict):
+ # TODO
+ pass
diff --git a/project/template_utils/wandb_callbacks.py b/project/template_utils/wandb_callbacks.py
deleted file mode 100644
index 3a4b94a..0000000
--- a/project/template_utils/wandb_callbacks.py
+++ /dev/null
@@ -1,175 +0,0 @@
-from sklearn.metrics import precision_score, recall_score, f1_score
-from pytorch_lightning.loggers import WandbLogger
-from wandb.sdk.wandb_run import Run as wandb_run
-from pytorch_lightning import Callback
-from shutil import copy
-import torch
-import wandb
-import os
-
-
-class SaveOnnxModelToWandbCallback(Callback):
- """
- Save model in .onnx format and upload to wandb.
- Might crash since not all models are compatible with onnx.
- """
- def __init__(self, datamodule, wandb_save_dir):
- first_batch = next(iter(datamodule.train_dataloader()))
- x, y = first_batch
- self.dummy_input = x
- self.wandb_save_dir = wandb_save_dir
-
- def on_sanity_check_end(self, trainer, pl_module):
- self.save_onnx_model(pl_module)
-
- def on_train_end(self, trainer, pl_module):
- self.save_onnx_model(pl_module)
-
- def save_onnx_model(self, pl_module):
- file_path = os.path.join(self.wandb_save_dir, "model.onnx")
- pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
- wandb.save(file_path, base_path=self.wandb_save_dir)
-
-
-class ImagePredictionWandbLoggerCallback(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 MetricsHeatmapWandbLoggerCallback(Callback):
- """
- Generate f1, precision and recall heatmap from validation epoch outputs.
- Expects validation step to return predictions and targets.
- Works only for single label classification!
- """
- def __init__(self, class_names):
- self.class_names = class_names
- self.preds = []
- self.targets = []
- self.ready = False
-
- def on_sanity_check_end(self, trainer, pl_module):
- """Start executing this callback only after all validation sanity checks end."""
- self.ready = True
-
- def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
- """Gather data from single batch."""
- if self.ready:
- preds, targets = outputs
- self.preds.append(preds)
- self.targets.append(targets)
-
- def on_validation_epoch_end(self, trainer, pl_module):
- """Generate f1, precision and recall heatmap."""
- if self.ready:
- self.preds = torch.cat(self.preds)
- self.targets = torch.cat(self.targets)
- f1 = f1_score(self.preds, self.targets, average=None)
- r = recall_score(self.preds, self.targets, average=None)
- p = precision_score(self.preds, self.targets, average=None)
-
- logger = None
- for some_logger in trainer.logger.experiment:
- if isinstance(some_logger, wandb_run):
- logger = some_logger
-
- logger.log({
- f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap(
- x_labels=self.class_names,
- y_labels=["f1", "precision", "recall"],
- matrix_values=[f1, p, r],
- show_text=True,
- )}, commit=False)
-
- self.preds = []
- self.targets = []
-
-
-class ConfusionMatrixWandbLoggerCallback(Callback):
- """
- Generate Confusion Matrix.
- Expects validation step to return predictions and targets.
- Works only for single label classification!
- """
- def __init__(self, class_names):
- self.class_names = class_names
- self.preds = []
- self.targets = []
- self.ready = False
-
- def on_sanity_check_end(self, trainer, pl_module):
- """Start executing this callback only after all validation sanity checks end."""
- self.ready = True
-
- def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
- """Gather data from single batch."""
- if self.ready:
- preds, targets = outputs
- self.preds.append(preds)
- self.targets.append(targets)
-
- def on_validation_epoch_end(self, trainer, pl_module):
- """Generate f1, precision and recall heatmap."""
- if self.ready:
- self.preds = torch.cat(self.preds).tolist()
- self.targets = torch.cat(self.targets).tolist()
-
- logger = None
- for some_logger in trainer.logger.experiment:
- if isinstance(some_logger, wandb_run):
- logger = some_logger
-
- logger.log({
- f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
- self.preds,
- self.targets,
- class_names=self.class_names)
- }, commit=False)
-
- self.preds = []
- self.targets = []
-
-
-class SaveCodeToWandbCallback(Callback):
- """
- Upload specified code files to wandb at the beginning of the run.
- """
- def __init__(self, base_dir, wandb_save_dir, run_config):
- self.base_dir = base_dir
- self.wandb_save_dir = wandb_save_dir
- self.model_folder = run_config["model"]["load_from"]["model_path"]
- self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
- self.additional_files_to_be_saved = [ # paths should be relative to base_dir
- "template_utils/callbacks.py",
- "template_utils/initializers.py",
- "train.py",
- "project_config.yaml",
- "run_configs.yaml",
- ]
-
- def on_sanity_check_end(self, trainer, pl_module):
- """Upload files when all validation sanity checks end."""
- # upload additional files
- pass
diff --git a/project/train.py b/project/train.py
index 514493c..fb13b73 100644
--- a/project/train.py
+++ b/project/train.py
@@ -1,81 +1,75 @@
# 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
+import hydra
+
# normal imports
-from argparse import ArgumentParser
from typing import List
-import pprint
-import yaml
-import os
+import wandb
# template utils imports
-from template_utils.initializers import (
- normalize_config_paths,
- init_model,
- init_datamodule,
- init_callbacks,
- init_loggers,
- init_trainer
-)
+import template_utils.initializers as utils
-# Everything will be loaded relatively to placement of 'train.py' file!
-BASE_DIR: str = os.path.dirname(__file__)
-
-
-def train(project_config: dict, run_config: dict, use_wandb: bool):
+def train(config):
+ # Validate the correctness of loaded config
+ utils.validate_config(config=config)
# Set global PyTorch seed
- if "seed" in run_config:
- torch.manual_seed(run_config["seed"])
-
- # Covert paths to absolute and normalize them
- project_config, run_config = normalize_config_paths(
- project_config=project_config,
- run_config=run_config,
- base_dir=BASE_DIR
- )
+ if "seeds" in config and "pytorch_seed" in config["seeds"]:
+ torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
# Init PyTorch Lightning model ⚡
- model: LightningModule = init_model(
- model_config=run_config["model"]
+ model: pl.LightningModule = utils.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 = utils.init_datamodule(
+ datamodule_config=config["datamodule"],
+ data_dir=config["data_dir"]
)
# Init PyTorch Lightning callbacks ⚡
- callbacks: List[Callback] = init_callbacks(
- project_config=project_config,
- run_config=run_config,
- use_wandb=use_wandb,
- base_dir=BASE_DIR
- )
+ callbacks = []
+ if "callbacks" in config:
+ callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"])
# Init PyTorch Lightning loggers ⚡
- loggers: List[LightningLoggerBase] = init_loggers(
- project_config=project_config,
- run_config=run_config,
+ 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,
- use_wandb=use_wandb
+ callbacks=callbacks
)
+ # Log info in terminal about all initialized objects
+ utils.show_init_info(model, datamodule, callbacks, loggers)
+
# Init PyTorch Lightning trainer ⚡
- trainer: Trainer = init_trainer(
- project_config=project_config,
- run_config=run_config,
+ 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)
+ # 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)
@@ -84,49 +78,12 @@ 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:
+ utils.show_config(config) # print content of config
+ train(config)
+ wandb.finish()
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 aa3d615..fe195b6 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,8 +1,9 @@
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
-PyYAML>=5.3.1
scikit-learn>=0.23.2
pandas>=1.1.5
+hydra_colorlog
diff --git a/setup.py b/setup.py
index 9fa9614..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', 'PyYAML'],
+ 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(),
)