update readme

This commit is contained in:
hobogalaxy committed 2021-01-12 22:13:11 +01:00
1 parent 9a5a4eb192
commit f90ceab605
5 files changed
+175 -110

No files matched your search

+157 -106
View File
@@ -1,22 +1,26 @@
## Deep learning project template ## Deep learning project template
A convenient starting template for most deep learning projects. Built with <b>PyTorch Lightning</b> and <b>Weights&Biases</b>.<br> A convenient starting template and pipeline for deep learning projects. Built with <b>PyTorch Lightning</b>, <b>Hydra</b> and <b>Weights&Biases</b>.<br>
Click on <b>"Use this template"</b> button above to initialize new repository.<br> Click on <b>"Use this template"</b> button above to initialize new repository.<br>
## Features ## Features
- Predefined folder structure - Predefined folder structure
- Storing project configuration in a convenient way ([project_config.yaml](project_config.yaml)) - Automates loading of PyTorch Lightning modules - you only need to create model and datamodule and specify them in configuration files
- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml)) - All advantages of Hydra:
- All advantages of PyTorch Lightning - Main config file contains default configuration used when executing command `python train.py` ([config.yaml](project/configs/config.yaml))
- Storing many experiment configurations in a convenient way - experiments override chosen parameters from default configuration ([configs/experiment](project/configs/experiment))
- Composing configuration files out of other configuration files
- Scheduling execution of many experiments
- Overriding any config parameter from command line
- Command line tab completion
- Logging history of all executed runs
- Weights&Biases integration: - Weights&Biases integration:
- ~~Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud~~ (TODO) - Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py)) - Useful callbacks ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.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) - ~~Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))~~ (TODO)
- Scheduling execution of many runs/experiments ([execute_all_runs.py](project/template_utils/execute_all_experiments.py))
- Built in requirements ([requirements.txt](requirements.txt)) - Built in requirements ([requirements.txt](requirements.txt))
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml)) - Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
- Built in package setup ([setup.py](setup.py)) - Built in package setup ([setup.py](setup.py))
- Example with MNIST digits classification - Example with MNIST digits classification
- Useful example callbacks ([callbacks.py](project/src/callbacks/custom_callbacks.py))
<br> <br>
@@ -24,137 +28,180 @@ Click on <b>"Use this template"</b> button above to initialize new repository.<b
The directory structure of new project looks like this: The directory structure of new project looks like this:
``` ```
├── project ├── project
│ ├── data <- Data from third party sources │ ├── configs <- Hydra configuration files
│ │ ├── trainer <- Configurations of lightning trainers
│ │ ├── model <- Configurations of lightning models
│ │ ├── datamodule <- Configurations of lightning datamodules
│ │ ├── callbacks <- Configurations of lightning callbacks
│ │ ├── logger <- Configurations of lightning loggers
│ │ ├── optimizer <- Configurations of optimizers
│ │ ├── seeds <- Configurations of seeds
│ │ ├── experiment <- Configurations of experiments
│ │ │
│ │ └── config.yaml <- Main project configuration file
│ │ │ │
│ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning │ ├── data <- Project data
│ │
│ ├── logs <- Logs generated by hydra and pytorch lightning loggers
│ │ │ │
│ ├── notebooks <- Jupyter notebooks │ ├── notebooks <- Jupyter notebooks
│ │ │ │
│ ├── template_utils <- Different utilities │ ├── template_utils <- Different project utilities
│ │ ├── callbacks.py <- Custom callbacks
│ │ ├── wandb_callbacks.py <- Custom Weights&Biases related callbacks
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps │ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
│ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other │ │ ├── inference_example.py <- Example of inference with trained model
│ │ ├── initializers.py <- Initializers for different modules │ │ └── initializers.py <- Initializers for different modules
│ │ └── predict_example.py <- Example of inference with trained model
│ │ │ │
│ ├── datamodules <- All your datamodules should be located here! │ ├── src
│ │ ├── example_datamodule <- It's best to locate each datamodule in separate folder! │ │ ├── architectures <- PyTorch model architectures
│ │ │ ├── datamodule.py <- Contains class of type 'LightningDataModule' │ │ ├── callbacks <- PyTorch Lightning callbacks
│ │ │ ├── transforms.py <- Some optional file │ │ ├── datamodules <- PyTorch Lightning datamodules
│ │ │ └── ... │ │ ├── datasets <- PyTorch datasets
│ │ ├── ... │ │ ├── models <- PyTorch Lightning models
│ │ └── ... │ │ ├── transforms <- Data transformations
│ │ └── utils <- Utility scripts
│ │ │ │
│ ├── 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'
│ │ ├── ...
│ │ └── ...
│ │
│ ├── project_config.yaml <- Project configuration
│ ├── run_configs.yaml <- Configurations of different runs/experiments
│ └── train.py <- Train model with chosen run configuration │ └── train.py <- Train model with chosen run configuration
│ │
├── .gitignore ├── .gitignore <- Ignored files
├── LICENSE ├── LICENSE <- Project license
├── README.md ├── README.md <- Readme
├── conda_env.yaml ├── conda_env.yaml <- File for installing conda environment
├── requirements.txt ├── requirements.txt <- List of python dependencies
└── setup.py └── setup.py <- File for installing project as a package
``` ```
<br> <br>
## Project config parameters ([project_config.yaml](project_config.yaml)) ## Main project configuration file ([config.yaml](project/configs/config.yaml))
Example project configuration:
```yaml ```yaml
num_of_gpus: -1 <- '-1' to train on all GPUs available, '0' to train on CPU # 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
loggers: # path to working directory (the directory that `train.py` was executed from in command line)
wandb: work_dir: ${hydra:runtime.cwd}
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: # path to folder with data
ModelCheckpoint: data_dir: ${work_dir}/data/
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: # hydra output paths
progress_bar_refresh_rate: 5 <- refresh rate of training bar in terminal hydra:
weights_summary: "top" <- print summary of model (alternatively "full") run:
profiler: False <- set True if you want to see execution time profiling 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}
data_dir: "data/" <- path to data folder # extra things that are logged by all loggers as hyperparameters
logs_dir: "logs/" <- path to logs folder 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
``` ```
<br> <br>
## Run config parameters ([run_configs.yaml](project/run_configs.yaml)) ## Experiment configuration ([configs/experiment](project/configs/experiment))
You can store many run configurations in this file.<br> You can store many experiment configurations in this folder.<br>
Example run configuration: Example experiment configuration:
```yaml ```yaml
SIMPLE_CONFIG_EXAMPLE_MNIST: defaults:
seed: 1234 - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
- override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder
- override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder
- override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
- override /logger: null # choose logger from 'configs/logger/' folder
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
seeds:
pytorch_seed: 12345
trainer: trainer:
args: args:
max_epochs: 10 max_epochs: 10
model: model:
load_from: args:
model_path: "models/simple_mnist_classifier/simple_mnist_classifier.py"
model_class: "LitModel"
hparams:
lr: 0.001
weight_decay: 0.00001
input_size: 784 input_size: 784
output_size: 10 output_size: 10
lin1_size: 256 lin1_size: 256
lin2_size: 256 lin2_size: 256
lin3_size: 128 lin3_size: 128
datamodule: datamodule:
load_from: args:
datamodule_path: "datamodules/mnist_datamodule/mnist_datamodule.py" batch_size: 32
datamodule_class: "MNISTDataModule"
hparams:
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000] train_val_test_split: [55_000, 5_000, 10_000]
optimizer:
args:
lr: 0.001
weight_decay: 0.00001
``` ```
To start training with this configuration run:<br> To execute this experiment run:
`python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` ```bash
python train.py +experiment=exp_example_simple
Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.<br> ```
Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<br> <br>
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/src/models/simple_mnist_classifier.py)).<br> ## Logs
Logs are created automatically with the following structure:
Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/src/datamodules/mnist_datamodule.py)).<br> ```
├── 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
│ │ │ │
│ │ │ ├── ...
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
│ ├── 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
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
```
<br> <br>
## Workflow ## Workflow
1. Create PyTorch Lightning model 1. Create PyTorch Lightning model
2. Create PyTorch Lightning datamodule 2. Create PyTorch Lightning datamodule
3. Create new run config in [run_configs.yaml](project/run_configs.yaml) 3. Create new experiment config in [configs/experiment](project/configs/experiment)
- specify path to your model class
- specify path to your datamodule class
- you can add there any hyperparameters you want!
3. Configure your project in [project_config.yaml](project_config.yaml)
4. Run training with chosen run config<br> 4. Run training with chosen run config<br>
```bash ```bash
python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST python train.py +experiment=experiment_name.yaml
``` ```
<br><br> <br><br>
@@ -191,29 +238,32 @@ conda activate your_env_name
# install requirements # install requirements
pip install -r requirements.txt 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 ```bash
# train model without Weights&Biases
# choose run config name from project/run_configs.yaml
cd project 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 ```yaml
# set project and entity names in project/config.yaml # set project and entity names in project/configs/logger/wandb.yaml
loggers:
wandb: wandb:
args:
project: "your_project_name" project: "your_project_name"
entity: "your_wandb_username_or_team" entity: "your_wandb_team_name"
``` ```
```bash ```bash
# train model with Weights&Biases # train model with Weights&Biases
# choose run config name from project/run_configs.yaml python train.py logger=wandb.yaml
cd project ```
python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
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) Optionally you can install project as a package with [setup.py](setup.py)
@@ -234,5 +284,6 @@ pip install -e .
- run training:<br> - run training:<br>
`right click on train.py file -> "Run 'train'"` `right click on train.py file -> "Run 'train'"`
#### VS Code setup #### VS Code setup
- TODO - TODO
@@ -4,7 +4,7 @@ model_checkpoint:
class: pytorch_lightning.callbacks.ModelCheckpoint class: pytorch_lightning.callbacks.ModelCheckpoint
args: args:
monitor: "val_acc" # name of the logged metric which determines when model is improving monitor: "val_acc" # name of the logged metric which determines when model is improving
save_top_k: 1 # save k best models (determined by above metric) save_top_k: 2 # save k best models (determined by above metric)
save_last: True # additionaly always save model from last epoch save_last: True # additionaly always save model from last epoch
mode: "max" # can be "max" or "min" mode: "max" # can be "max" or "min"
filepath: "checkpoints/{epoch}" filepath: "checkpoints/{epoch}"
+3
View File
@@ -9,6 +9,9 @@ defaults:
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`) - 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) # path to working directory (the directory that `train.py` was executed from in command line)
work_dir: ${hydra:runtime.cwd} work_dir: ${hydra:runtime.cwd}
+1 -1
View File
@@ -5,7 +5,7 @@ args:
gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
auto_select_gpus: True auto_select_gpus: True
fast_dev_run: True # fast_dev_run: True # bugged :(
limit_train_batches: 1.0 limit_train_batches: 1.0
limit_val_batches: 1.0 limit_val_batches: 1.0
limit_test_batches: 1.0 limit_test_batches: 1.0
+13 -2
View File
@@ -10,7 +10,7 @@ import os
class SaveCodeToWandb(Callback): class SaveCodeToWandb(Callback):
""" """
Upload all *.py files to wandb at the beginning of the run. Upload all *.py files to wandb as an artifact at the beginning of the run.
""" """
def __init__(self, code_dir: str): def __init__(self, code_dir: str):
self.code_dir = code_dir self.code_dir = code_dir
@@ -24,6 +24,9 @@ class SaveCodeToWandb(Callback):
class UploadAllCheckpointsToWandb(Callback): class UploadAllCheckpointsToWandb(Callback):
"""
Upload experiment checkpoints to wandb as an artifact at the end of training.
"""
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False): def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
self.ckpt_dir = ckpt_dir self.ckpt_dir = ckpt_dir
self.upload_best_only = upload_best_only self.upload_best_only = upload_best_only
@@ -43,7 +46,7 @@ class UploadAllCheckpointsToWandb(Callback):
class SaveMetricsHeatmapToWandb(Callback): class SaveMetricsHeatmapToWandb(Callback):
""" """
Generate f1, precision and recall heatmap from validation epoch outputs. Generate f1, precision and recall heatmap from validation step outputs.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
Works only for single label classification! Works only for single label classification!
""" """
@@ -133,6 +136,14 @@ class SaveConfusionMatrixToWandb(Callback):
class SaveBestMetricScoresToWandb(Callback): class SaveBestMetricScoresToWandb(Callback):
"""
Store in wandb:
- max train acc
- min train loss
- max val acc
- min val loss
Useful for comparing runs in table views, as wandb doesn't currently supports column aggregation.
"""
def __init__(self): def __init__(self):
self.train_loss_best = None self.train_loss_best = None
self.train_acc_best = None self.train_acc_best = None