40 files changed
+934
-840
No files matched your search
@@ -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/project_config.yaml))
|
- Automates training with PyTorch Lightning - 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 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:
|
- Weights&Biases integration:
|
||||||
- ~~Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud~~ (TODO)
|
- Automatically stores all code files, 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_runs.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/template_utils/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/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/'
|
||||||
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:
|
args:
|
||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
model:
|
|
||||||
load_from:
|
model:
|
||||||
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
args:
|
||||||
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:
|
|
||||||
load_from:
|
datamodule:
|
||||||
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
args:
|
||||||
datamodule_class: "MNISTDataModule"
|
batch_size: 32
|
||||||
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/models/simple_mnist_classifier/lightning_module.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/datamodules/mnist_datamodule/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/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/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
|
||||||
@@ -1,11 +1,14 @@
|
|||||||
#name: conda_env_name
|
#name: conda_env_name
|
||||||
|
|
||||||
channels:
|
channels:
|
||||||
- pytorch
|
- pytorch
|
||||||
- conda-forge
|
- conda-forge
|
||||||
- defaults
|
- defaults
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
- python=3.8
|
- python=3.8
|
||||||
- pip
|
- pip
|
||||||
|
- notebook
|
||||||
- cudatoolkit
|
- cudatoolkit
|
||||||
- pytorch
|
- pytorch
|
||||||
- torchvision
|
- torchvision
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
- default_callbacks.yaml
|
||||||
|
- 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
|
||||||
|
|
||||||
@@ -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
|
||||||
@@ -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
|
||||||
@@ -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"]
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# Train with all logger at once
|
||||||
|
defaults:
|
||||||
|
- csv_logger.yaml
|
||||||
|
- wandb.yaml
|
||||||
|
# - comet.yaml
|
||||||
|
# - tensorboard.yaml
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# Comet logger config
|
||||||
|
comet:
|
||||||
|
class: pytorch_lightning.logger.CometLogger
|
||||||
|
args:
|
||||||
|
api_key: ???
|
||||||
|
project_name: "project_template_test"
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# Csv logger config
|
||||||
|
csv_logger:
|
||||||
|
class: pytorch_lightning.loggers.CSVLogger
|
||||||
|
args:
|
||||||
|
save_dir: "."
|
||||||
|
name: "csv_logger/"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# Tensorboard logger config
|
||||||
|
tensorboard:
|
||||||
|
class: pytorch_lightning.logger.TensorboardLogger
|
||||||
|
args: {}
|
||||||
@@ -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: "."
|
||||||
@@ -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
|
||||||
|
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
class: torch.optim.Adam
|
||||||
|
args:
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.000001
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
pytorch_seed: 12345
|
||||||
@@ -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/"
|
||||||
@@ -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"
|
||||||
Whitespace-only changes.
Whitespace-only changes.
@@ -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/"
|
|
||||||
@@ -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
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# package file
|
||||||
File renamed without changes.
File renamed without changes.
@@ -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)
|
||||||
+8
-9
@@ -7,20 +7,19 @@ from torchvision.datasets import MNIST
|
|||||||
class MNISTDataModule(LightningDataModule):
|
class MNISTDataModule(LightningDataModule):
|
||||||
"""
|
"""
|
||||||
This is example of datamodule for MNIST dataset.
|
This is example of datamodule for MNIST dataset.
|
||||||
|
To learn how to create datamodules visit:
|
||||||
The path to datamodule should be specified in your run config. (run_configs.yaml)
|
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
||||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, data_dir: str, hparams: dict):
|
def __init__(self, data_dir, **args):
|
||||||
super().__init__()
|
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.batch_size = args["batch_size"]
|
||||||
self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
self.train_val_test_split = args["train_val_test_split"]
|
||||||
self.num_workers = hparams.get("num_workers") or 1
|
self.num_workers = args["num_workers"]
|
||||||
self.pin_memory = hparams.get("pin_memory") or False
|
self.pin_memory = args["pin_memory"]
|
||||||
|
|
||||||
self.transforms = transforms.ToTensor()
|
self.transforms = transforms.ToTensor()
|
||||||
|
|
||||||
File renamed without changes.
+24
-25
@@ -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 pytorch_lightning as pl
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
# import custom models
|
# import custom architectures
|
||||||
from models.simple_mnist_classifier.models import *
|
from src.architectures.simple_mnist import SimpleMNISTClassifier
|
||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
"""
|
"""
|
||||||
This is example of lightning model for MNIST digits classification.
|
This is example of lightning model for MNIST classification.
|
||||||
|
|
||||||
The path to model should be specified in your run config. (run_configs.yaml)
|
|
||||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
|
||||||
|
|
||||||
This class enables you to specify what happens during training, validation and test step.
|
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.
|
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__()
|
super().__init__()
|
||||||
|
hparams = {**model_config["args"], **optimizer_config["args"]}
|
||||||
if hparams:
|
|
||||||
self.save_hyperparameters(hparams)
|
self.save_hyperparameters(hparams)
|
||||||
|
self.optimizer_config = optimizer_config
|
||||||
|
|
||||||
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
||||||
|
|
||||||
|
self.accuracy = Accuracy()
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
|
|
||||||
@@ -37,10 +38,9 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# training metrics
|
# training metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = self.accuracy(preds, y)
|
||||||
acc = accuracy_score(preds, y)
|
self.log('train_loss', loss, on_step=False, on_epoch=True)
|
||||||
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, prog_bar=True)
|
||||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
@@ -52,13 +52,12 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# validation metrics
|
# validation metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = self.accuracy(preds, y)
|
||||||
acc = accuracy_score(preds, y)
|
self.log('val_loss', loss, on_step=False, on_epoch=True)
|
||||||
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, prog_bar=True)
|
||||||
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback
|
# 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
|
# logic for a single testing step
|
||||||
def test_step(self, batch, batch_idx):
|
def test_step(self, batch, batch_idx):
|
||||||
@@ -68,12 +67,12 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# test metrics
|
# test metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
preds, y = preds.cpu(), y.cpu()
|
acc = self.accuracy(preds, y)
|
||||||
acc = accuracy_score(preds, y)
|
self.log('test_loss', loss, on_step=False, on_epoch=True)
|
||||||
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)
|
||||||
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
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"])
|
||||||
+2
-2
@@ -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
|
from torchvision import transforms
|
||||||
|
|
||||||
@@ -9,5 +9,5 @@ mnist_train_transforms = transforms.Compose([
|
|||||||
])
|
])
|
||||||
|
|
||||||
mnist_test_transforms = transforms.Compose([
|
mnist_test_transforms = transforms.Compose([
|
||||||
transforms.ToTensor()
|
transforms.ToTensor(),
|
||||||
])
|
])
|
||||||
@@ -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)
|
|
||||||
@@ -1,31 +1,42 @@
|
|||||||
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
|
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
|
||||||
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
|
# 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 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
|
# Replace run config hyperparameters with the ones loaded from wandb sweep server
|
||||||
sweep_hparams = wandb.Config._as_dict(wandb.config)
|
def replace_hparams(config, sweep_hparams):
|
||||||
for key, value in sweep_hparams.items():
|
for key, value in sweep_hparams.items():
|
||||||
if key == "_wandb":
|
if key == "_wandb":
|
||||||
continue
|
continue
|
||||||
elif key in run_config["trainer"]["args"]:
|
elif key in config["trainer"]["args"]:
|
||||||
run_config["trainer"]["args"][key] = value
|
config["trainer"]["args"][key] = value
|
||||||
elif key in run_config["model"]["hparams"]:
|
elif key in config["model"]["args"]:
|
||||||
run_config["model"]["hparams"][key] = value
|
config["model"]["args"][key] = value
|
||||||
elif key in run_config["datamodule"]["hparams"]:
|
elif key in config["optimizer"]["args"]:
|
||||||
run_config["datamodule"]["hparams"][key] = value
|
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()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
import hydra
|
||||||
+6
-4
@@ -1,8 +1,10 @@
|
|||||||
from datamodules.mnist_datamodule import transforms
|
from src.transforms import mnist_transforms
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
# the LitModel you import should be the same as the one you used for training!
|
# 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():
|
def predict():
|
||||||
@@ -10,7 +12,7 @@ def predict():
|
|||||||
This method is example of inference with a trained model.
|
This method is example of inference with a trained model.
|
||||||
It Loads trained image classification model from checkpoint.
|
It Loads trained image classification model from checkpoint.
|
||||||
Then it loads example image and predicts its label.
|
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"
|
CKPT_PATH = "epoch=0.ckpt"
|
||||||
@@ -27,7 +29,7 @@ def predict():
|
|||||||
# img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion
|
# img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion
|
||||||
|
|
||||||
# preprocess
|
# 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
|
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||||
|
|
||||||
# inference
|
# inference
|
||||||
@@ -1,290 +1,205 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
|
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||||
from pytorch_lightning.profiler import SimpleProfiler
|
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
|
|
||||||
|
# hydra imports
|
||||||
|
from omegaconf import DictConfig, OmegaConf
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List, Tuple
|
from typing import List
|
||||||
import importlib.util
|
import importlib
|
||||||
import os
|
import logging
|
||||||
|
|
||||||
# template utils imports
|
log = logging.getLogger(__name__)
|
||||||
from pytorch_lightning import callbacks as lightning_callbacks
|
|
||||||
from template_utils import callbacks as custom_callbacks
|
|
||||||
from template_utils import wandb_callbacks
|
|
||||||
|
|
||||||
|
|
||||||
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.
|
||||||
"""
|
"""
|
||||||
|
model_class = model_config["class"]
|
||||||
if not os.path.isabs(project_config["data_dir"]):
|
LitModel = load_class(model_class)
|
||||||
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)
|
|
||||||
|
|
||||||
assert issubclass(LitModel, pl.LightningModule), \
|
assert issubclass(LitModel, pl.LightningModule), \
|
||||||
f"specified model class '{model_class}' is not a 'LightningModule' type"
|
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
||||||
|
return LitModel(model_config=model_config, optimizer_config=optimizer_config)
|
||||||
model = LitModel(hparams=model_config["hparams"])
|
|
||||||
|
|
||||||
return model
|
|
||||||
|
|
||||||
|
|
||||||
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||||
"""
|
"""
|
||||||
Load LightningDataModule from path specified in run config.
|
Load LightningDataModule from path specified config.
|
||||||
"""
|
"""
|
||||||
|
datamodule_class = datamodule_config["class"]
|
||||||
datamodule_path = datamodule_config["load_from"]["datamodule_path"]
|
datamodule_args = datamodule_config["args"]
|
||||||
datamodule_class = datamodule_config["load_from"]["datamodule_class"]
|
DataModule = load_class(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)
|
|
||||||
|
|
||||||
assert issubclass(DataModule, pl.LightningDataModule), \
|
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||||
f"specified datamodule class '{datamodule_class}' is not a 'LightningDataModule' type"
|
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
||||||
|
datamodule = DataModule(data_dir=data_dir, **datamodule_args)
|
||||||
datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"])
|
|
||||||
datamodule.prepare_data()
|
datamodule.prepare_data()
|
||||||
datamodule.setup()
|
datamodule.setup()
|
||||||
|
|
||||||
return datamodule
|
return datamodule
|
||||||
|
|
||||||
|
|
||||||
def init_trainer(project_config: dict,
|
def init_trainer(trainer_config: dict,
|
||||||
run_config: dict,
|
|
||||||
callbacks: List[pl.Callback],
|
callbacks: List[pl.Callback],
|
||||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||||
"""
|
"""
|
||||||
Initialize PyTorch Lightning 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(
|
trainer = pl.Trainer(
|
||||||
# whether to use gpu and how many
|
|
||||||
gpus=project_config["num_of_gpus"],
|
|
||||||
|
|
||||||
# experiment logging
|
|
||||||
logger=loggers,
|
|
||||||
|
|
||||||
# useful callbacks
|
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
|
logger=loggers,
|
||||||
# resume training from checkpoint if it was set in the run config
|
**trainer_config["args"]
|
||||||
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"]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return trainer
|
return trainer
|
||||||
|
|
||||||
|
|
||||||
def init_callbacks(project_config: dict,
|
def init_callbacks(callbacks_config: dict) -> List[pl.Callback]:
|
||||||
run_config: dict,
|
|
||||||
use_wandb: bool,
|
|
||||||
base_dir: str) -> 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 = []
|
callbacks = []
|
||||||
|
for callback_name, callback_conf in callbacks_config.items():
|
||||||
all_callback_configs = {}
|
class_path = callback_conf.get("class", None)
|
||||||
for callback_config in default_callbacks:
|
if class_path:
|
||||||
all_callback_configs[callback_config] = default_callbacks[callback_config]
|
callback_obj = init_object(class_path=class_path, args=callback_conf.get("args", {}))
|
||||||
for callback_config in run_callbacks:
|
assert issubclass(callback_obj.__class__, pl.Callback), \
|
||||||
all_callback_configs[callback_config] = run_callbacks[callback_config]
|
f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`."
|
||||||
|
callbacks.append(callback_obj)
|
||||||
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
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
|
|
||||||
def init_loggers(project_config: dict,
|
def init_loggers(loggers_config: dict) -> List[pl.loggers.LightningLoggerBase]:
|
||||||
run_config: dict,
|
|
||||||
model: pl.LightningModule,
|
|
||||||
datamodule: pl.LightningDataModule,
|
|
||||||
use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
|
|
||||||
"""
|
"""
|
||||||
Initialize loggers.
|
Initialize loggers specified in config.
|
||||||
"""
|
"""
|
||||||
loggers = []
|
loggers = []
|
||||||
if use_wandb:
|
for logger_name, logger_conf in loggers_config.items():
|
||||||
wandb_logger = init_wandb_logger(
|
class_path = logger_conf.get("class", None)
|
||||||
project_config=project_config,
|
if class_path:
|
||||||
run_config=run_config,
|
logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {}))
|
||||||
model=model,
|
assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \
|
||||||
datamodule=datamodule
|
f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`."
|
||||||
)
|
loggers.append(logger_obj)
|
||||||
if wandb_logger:
|
|
||||||
loggers.append(wandb_logger)
|
|
||||||
|
|
||||||
return loggers
|
return loggers
|
||||||
|
|
||||||
|
|
||||||
def init_wandb_logger(project_config: dict,
|
def get_wandb_logger(loggers: List[pl.loggers.LightningLoggerBase]) -> WandbLogger:
|
||||||
run_config: dict,
|
for logger in loggers:
|
||||||
model: pl.LightningModule,
|
if isinstance(logger, WandbLogger):
|
||||||
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
return logger
|
||||||
"""
|
|
||||||
Initialize Weights&Biases logger.
|
|
||||||
"""
|
|
||||||
|
|
||||||
if "loggers" not in project_config or "wandb" not in project_config["loggers"]:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
|
||||||
# instead of auto-creating a new run
|
|
||||||
os.environ["WANDB_RESUME"] = "must"
|
|
||||||
|
|
||||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
|
|
||||||
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
|
||||||
|
|
||||||
wandb_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"])
|
|
||||||
|
|
||||||
|
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'):
|
if hasattr(model, 'model'):
|
||||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
|
||||||
wandb_logger.watch(model.model, log='gradients')
|
|
||||||
else:
|
|
||||||
wandb_logger.watch(model.model, log=None)
|
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:
|
else:
|
||||||
wandb_logger.watch(model, log=None)
|
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:
|
def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
|
||||||
"""Initialize tensorboard logger"""
|
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
|
# TODO
|
||||||
return None
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def validate_obj_config(obj_config: dict):
|
||||||
|
# TODO
|
||||||
|
pass
|
||||||
@@ -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
|
|
||||||
+47
-90
@@ -1,81 +1,75 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
|
||||||
from pytorch_lightning.loggers import LightningLoggerBase
|
from pytorch_lightning.loggers import LightningLoggerBase
|
||||||
|
import pytorch_lightning as pl
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
# hydra imports
|
||||||
|
from omegaconf import DictConfig
|
||||||
|
import hydra
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from argparse import ArgumentParser
|
|
||||||
from typing import List
|
from typing import List
|
||||||
import pprint
|
import wandb
|
||||||
import yaml
|
|
||||||
import os
|
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
from template_utils.initializers import (
|
import template_utils.initializers as utils
|
||||||
normalize_config_paths,
|
|
||||||
init_model,
|
|
||||||
init_datamodule,
|
|
||||||
init_callbacks,
|
|
||||||
init_loggers,
|
|
||||||
init_trainer
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# Everything will be loaded relatively to placement of 'train.py' file!
|
def train(config):
|
||||||
BASE_DIR: str = os.path.dirname(__file__)
|
# Validate the correctness of loaded config
|
||||||
|
utils.validate_config(config=config)
|
||||||
|
|
||||||
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
|
||||||
|
|
||||||
# Set global PyTorch seed
|
# Set global PyTorch seed
|
||||||
if "seed" in run_config:
|
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||||
torch.manual_seed(run_config["seed"])
|
torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
|
||||||
|
|
||||||
# Covert paths to absolute and normalize them
|
|
||||||
project_config, run_config = normalize_config_paths(
|
|
||||||
project_config=project_config,
|
|
||||||
run_config=run_config,
|
|
||||||
base_dir=BASE_DIR
|
|
||||||
)
|
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
model: LightningModule = init_model(
|
model: pl.LightningModule = utils.init_model(
|
||||||
model_config=run_config["model"]
|
model_config=config["model"],
|
||||||
|
optimizer_config=config["optimizer"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: LightningDataModule = init_datamodule(
|
datamodule: pl.LightningDataModule = utils.init_datamodule(
|
||||||
datamodule_config=run_config["datamodule"],
|
datamodule_config=config["datamodule"],
|
||||||
data_dir=project_config["data_dir"]
|
data_dir=config["data_dir"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning callbacks ⚡
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
callbacks: List[Callback] = init_callbacks(
|
callbacks = []
|
||||||
project_config=project_config,
|
if "callbacks" in config:
|
||||||
run_config=run_config,
|
callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"])
|
||||||
use_wandb=use_wandb,
|
|
||||||
base_dir=BASE_DIR
|
|
||||||
)
|
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers ⚡
|
# Init PyTorch Lightning loggers ⚡
|
||||||
loggers: List[LightningLoggerBase] = init_loggers(
|
loggers = []
|
||||||
project_config=project_config,
|
if "logger" in config:
|
||||||
run_config=run_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,
|
model=model,
|
||||||
datamodule=datamodule,
|
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 ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: Trainer = init_trainer(
|
trainer: pl.Trainer = utils.init_trainer(
|
||||||
project_config=project_config,
|
trainer_config=config["trainer"],
|
||||||
run_config=run_config,
|
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
loggers=loggers
|
loggers=loggers
|
||||||
)
|
)
|
||||||
|
|
||||||
# Evaluate model on test set before training
|
# Automatically find learning rate if specified in config
|
||||||
# trainer.test(model=model, datamodule=datamodule)
|
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
|
# Train the model
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
@@ -84,49 +78,12 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
|||||||
trainer.test()
|
trainer.test()
|
||||||
|
|
||||||
|
|
||||||
def load_config(path):
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path
|
def main(config: DictConfig) -> None:
|
||||||
with open(abs_path, "r") as ymlfile:
|
utils.show_config(config) # print content of config
|
||||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
train(config)
|
||||||
return config
|
wandb.finish()
|
||||||
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
main()
|
||||||
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)
|
|
||||||
+3
-2
@@ -1,8 +1,9 @@
|
|||||||
torch>=1.7.0
|
torch>=1.7.0
|
||||||
torchvision>=0.8.1
|
torchvision>=0.8.1
|
||||||
torchaudio>=0.7.0
|
torchaudio>=0.7.0
|
||||||
pytorch-lightning>=1.0.8
|
pytorch-lightning>=1.1.3
|
||||||
|
hydra-core
|
||||||
wandb>=0.10.12
|
wandb>=0.10.12
|
||||||
PyYAML>=5.3.1
|
|
||||||
scikit-learn>=0.23.2
|
scikit-learn>=0.23.2
|
||||||
pandas>=1.1.5
|
pandas>=1.1.5
|
||||||
|
hydra_colorlog
|
||||||
@@ -8,7 +8,7 @@ setup(
|
|||||||
description='Describe Your Cool Project',
|
description='Describe Your Cool Project',
|
||||||
author='',
|
author='',
|
||||||
author_email='',
|
author_email='',
|
||||||
url='https://github.com/kinoai/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
|
url='https://github.com/hobogalaxy/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
|
||||||
install_requires=['pytorch-lightning', 'PyYAML'],
|
install_requires=['pytorch-lightning', 'hydra-core'],
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
)
|
)
|
||||||
Reference in new issue
Block a user