develop more generic version of template, switch to using hydra initializers
This commit is contained in:
1 parent
e93283d890
commit
7fe01e22d3
26 files changed
+329
-512
No files matched your search
@@ -1,12 +1,14 @@
|
|||||||
## Deep learning project template
|
## Deep learning project template
|
||||||
This is my starting template and pipeline for most deep learning projects.<br>
|
This is my starting template and pipeline for most deep learning projects.<br>
|
||||||
Built with <b>PyTorch Lightning</b>, <b>Hydra</b> and <b>Weights&Biases</b>.<br>
|
I'm trying to make this as generic as possible.<br>
|
||||||
|
Built with <b>PyTorch Lightning</b> and <b>Hydra</b>.<br>
|
||||||
|
Also contains special <b>Weights&Biases</b> integration, but can be used with any other logger.<br>
|
||||||
It's supposed to be enchancement/expansion on original [deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template) repository.<br>
|
It's supposed to be enchancement/expansion on original [deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template) repository.<br>
|
||||||
|
|
||||||
The goal is to:
|
The goal is to:
|
||||||
- structure ML code the same so that work can easily be extended and replicated
|
- structure ML code the same so that work can easily be extended and replicated
|
||||||
- allow for quick and efficient experimentation process thanks to automating pipeline with config files
|
- allow for quick and efficient experimentation process thanks to automating pipeline with config files
|
||||||
- extend functionality of popular experiment loggers like Weights&Biases
|
- extend functionality of popular experiment loggers like Weights&Biases, mostly with dedicated callbacks
|
||||||
|
|
||||||
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>
|
||||||
|
|
||||||
@@ -22,14 +24,18 @@ Click on <b>`Use this template`</b> button above to initialize new repository.<b
|
|||||||
- Storing many experiment configurations in a convenient way ([configs/experiment](project/configs/experiment))
|
- Storing many experiment configurations in a convenient way ([configs/experiment](project/configs/experiment))
|
||||||
- Composing configuration files out of other configuration files
|
- Composing configuration files out of other configuration files
|
||||||
- Scheduling execution of many experiments
|
- Scheduling execution of many experiments
|
||||||
|
- Searching over hyperparameters from command line
|
||||||
- Overriding any config parameter from command line
|
- Overriding any config parameter from command line
|
||||||
- Command line tab completion
|
- Command line tab completion
|
||||||
- Logging history of all executed runs/experiments
|
- Logging history of all executed runs/experiments
|
||||||
|
- ~~Automatically validate config structure with config schemas~~ (TODO)
|
||||||
- Weights&Biases integration
|
- Weights&Biases integration
|
||||||
- Available callbacks that store all code files and model checkpoints as artifacts in Weights&Biases cloud ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py))
|
- Available callbacks that store all code files and model checkpoints as artifacts in Weights&Biases cloud ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py))
|
||||||
- Other examples of useful wandb callbacks ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py))
|
- Other examples of useful wandb callbacks ([wandb_callbacks.py](project/src/callbacks/wandb_callbacks.py))
|
||||||
- Configuring which hyperparameters are saved by loggers through main config file ([config.yaml](project/configs/config.yaml))
|
- Automatically watch the model
|
||||||
- ~~Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))~~ (TODO)
|
- ~~Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))~~ (TODO)
|
||||||
|
- Automatically logs config parts to all initialized lightning loggers
|
||||||
|
- Example of inference with trained model ([inference_example.py](project/src/utils/inference_example.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 python package setup ([setup.py](setup.py))
|
- Built in python package setup ([setup.py](setup.py))
|
||||||
@@ -47,7 +53,6 @@ The directory structure of new project looks like this:
|
|||||||
│ │ ├── datamodule <- Configurations of lightning datamodules
|
│ │ ├── datamodule <- Configurations of lightning datamodules
|
||||||
│ │ ├── callbacks <- Configurations of lightning callbacks
|
│ │ ├── callbacks <- Configurations of lightning callbacks
|
||||||
│ │ ├── logger <- Configurations of lightning loggers
|
│ │ ├── logger <- Configurations of lightning loggers
|
||||||
│ │ ├── optimizer <- Configurations of optimizers
|
|
||||||
│ │ ├── seeds <- Configurations of seeds
|
│ │ ├── seeds <- Configurations of seeds
|
||||||
│ │ ├── experiment <- Configurations of experiments
|
│ │ ├── experiment <- Configurations of experiments
|
||||||
│ │ │
|
│ │ │
|
||||||
@@ -68,13 +73,13 @@ The directory structure of new project looks like this:
|
|||||||
│ │ ├── transforms <- Data transformations
|
│ │ ├── transforms <- Data transformations
|
||||||
│ │ └── utils <- Utility scripts
|
│ │ └── utils <- Utility scripts
|
||||||
│ │ ├── inference_example.py <- Example of inference with trained model
|
│ │ ├── inference_example.py <- Example of inference with trained model
|
||||||
│ │ └── initializers.py <- Initializers for different modules
|
│ │ └── template_utils.py <- Some extra template utilities
|
||||||
│ │
|
│ │
|
||||||
│ └── train.py <- Train model with chosen experiment configuration
|
│ └── train.py <- Train model with chosen experiment configuration
|
||||||
│
|
│
|
||||||
├── .gitignore <- Ignored files
|
├── .gitignore
|
||||||
├── LICENSE <- Project license
|
├── LICENSE
|
||||||
├── README.md <- Readme
|
├── README.md
|
||||||
├── conda_env.yaml <- File for installing conda environment
|
├── conda_env.yaml <- File for installing conda environment
|
||||||
├── requirements.txt <- File for installing python dependencies
|
├── requirements.txt <- File for installing python dependencies
|
||||||
└── setup.py <- File for installing project as a package
|
└── setup.py <- File for installing project as a package
|
||||||
@@ -83,17 +88,26 @@ The directory structure of new project looks like this:
|
|||||||
|
|
||||||
|
|
||||||
## Main project configuration file ([config.yaml](project/configs/config.yaml))
|
## Main project configuration file ([config.yaml](project/configs/config.yaml))
|
||||||
|
Main config contains default training configuration.<br>
|
||||||
|
It determines how config is composed when simply executing command: `python train.py`
|
||||||
```yaml
|
```yaml
|
||||||
|
# to execute run with default training configuration simply run:
|
||||||
|
# `python train.py`
|
||||||
|
|
||||||
|
|
||||||
# specify here default training configuration
|
# specify here default training configuration
|
||||||
defaults:
|
defaults:
|
||||||
- trainer: default_trainer.yaml
|
- trainer: default_trainer.yaml
|
||||||
- model: mnist_model.yaml
|
- model: mnist_model.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
- optimizer: adam.yaml
|
|
||||||
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
|
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
|
||||||
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
|
|
||||||
|
# we add this just to enable color logging
|
||||||
|
- hydra/job_logging: colorlog
|
||||||
|
- hydra/hydra_logging: colorlog
|
||||||
|
|
||||||
|
|
||||||
# path to original working directory (the directory that `train.py` was executed from in command line)
|
# path to original working directory (the directory that `train.py` was executed from in command line)
|
||||||
# hydra hijacks working directory by changing it to the current log directory,
|
# hydra hijacks working directory by changing it to the current log directory,
|
||||||
@@ -106,20 +120,6 @@ original_work_dir: ${hydra:runtime.cwd}
|
|||||||
data_dir: ${original_work_dir}/data/
|
data_dir: ${original_work_dir}/data/
|
||||||
|
|
||||||
|
|
||||||
# define which things will be saved as hyperparameters by lightning loggers
|
|
||||||
extra_logs:
|
|
||||||
save_model_class_path: True
|
|
||||||
save_optimizer_class_path: True
|
|
||||||
save_datamodule_class_path: True
|
|
||||||
save_model_architecture_class_path: True
|
|
||||||
save_model_args: True
|
|
||||||
save_datamodule_args: True
|
|
||||||
save_optimizer_args: True
|
|
||||||
save_trainer_args: False
|
|
||||||
save_seeds: True
|
|
||||||
save_data_train_val_test_sizes: False
|
|
||||||
|
|
||||||
|
|
||||||
# output paths for hydra logs
|
# output paths for hydra logs
|
||||||
hydra:
|
hydra:
|
||||||
run:
|
run:
|
||||||
@@ -135,14 +135,18 @@ hydra:
|
|||||||
You can store many experiment configurations in this folder.<br>
|
You can store many experiment configurations in this folder.<br>
|
||||||
Example experiment configuration:
|
Example experiment configuration:
|
||||||
```yaml
|
```yaml
|
||||||
|
# to execute this experiment run:
|
||||||
|
# python train.py +experiment=exp_example_simple
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/'
|
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
|
||||||
- override /model: mnist_model.yaml # choose model from 'configs/model/'
|
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder or set to null
|
||||||
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/'
|
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder or set to null
|
||||||
- override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/'
|
- override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder or set to null
|
||||||
- override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/'
|
- override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder or set to null
|
||||||
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/'
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder or set to null
|
||||||
- override /logger: null # choose logger from 'configs/logger/'
|
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
||||||
|
# `python train.py +experiment=exp_example_simple logger=wandb`
|
||||||
|
|
||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
@@ -151,30 +155,18 @@ seeds:
|
|||||||
pytorch_seed: 12345
|
pytorch_seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
args:
|
max_epochs: 10
|
||||||
max_epochs: 10
|
gradient_clip_val: 0.5
|
||||||
|
|
||||||
model:
|
model:
|
||||||
args:
|
lr: 0.001
|
||||||
input_size: 784
|
lin1_size: 128
|
||||||
output_size: 10
|
lin2_size: 256
|
||||||
lin1_size: 256
|
lin3_size: 64
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
args:
|
batch_size: 64
|
||||||
batch_size: 32
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
|
||||||
|
|
||||||
optimizer:
|
|
||||||
args:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
```
|
|
||||||
To execute this experiment run:
|
|
||||||
```bash
|
|
||||||
python train.py +experiment=exp_example_simple
|
|
||||||
```
|
```
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
@@ -265,9 +257,8 @@ Or you can train model with chosen logger like Weights&Biases:
|
|||||||
```yaml
|
```yaml
|
||||||
# set project and entity names in project/configs/logger/wandb.yaml
|
# set project and entity names in project/configs/logger/wandb.yaml
|
||||||
wandb:
|
wandb:
|
||||||
args:
|
project: "your_project_name"
|
||||||
project: "your_project_name"
|
entity: "your_wandb_team_name"
|
||||||
entity: "your_wandb_team_name"
|
|
||||||
```
|
```
|
||||||
```bash
|
```bash
|
||||||
# train model with Weights&Biases
|
# train model with Weights&Biases
|
||||||
@@ -286,15 +277,31 @@ python train.py --multirun '+experiment=glob(*)'
|
|||||||
|
|
||||||
You can override any parameter from command line like this:
|
You can override any parameter from command line like this:
|
||||||
```bash
|
```bash
|
||||||
python train.py trainer.args.max_epochs=20 optimizer.args.lr=0.0005
|
python train.py trainer.max_epochs=20 model.lr=0.0005
|
||||||
|
```
|
||||||
|
|
||||||
|
Attach some callback set to run:
|
||||||
|
```bash
|
||||||
|
python train.py callbacks=wandb_callbacks
|
||||||
```
|
```
|
||||||
|
|
||||||
Combaining it all:
|
Combaining it all:
|
||||||
```bash
|
```bash
|
||||||
python train.py --multirun '+experiment=glob(*)' trainer.args.max_epochs=20 logger=wandb
|
python train.py --multirun '+experiment=glob(*)' trainer.max_epochs=20 logger=wandb callbacks=wandb_callbacks
|
||||||
|
```
|
||||||
|
|
||||||
|
To create a sweep over some hyperparameters run:
|
||||||
|
```bash
|
||||||
|
# this will run 6 experiments one after the other, each with different combination of batch_size and learning rate
|
||||||
|
python train.py --multirun datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
|
||||||
```
|
```
|
||||||
|
|
||||||
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):
|
||||||
```bash
|
```bash
|
||||||
pip install -e .
|
pip install -e .
|
||||||
```
|
```
|
||||||
|
|
||||||
|
To update the conda environment run:
|
||||||
|
```bash
|
||||||
|
conda env update --file conda_env.yml
|
||||||
|
```
|
||||||
@@ -1,17 +1,15 @@
|
|||||||
model_checkpoint:
|
model_checkpoint:
|
||||||
class: pytorch_lightning.callbacks.ModelCheckpoint
|
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
||||||
args:
|
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
||||||
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
save_top_k: 2 # save k best models (determined by above metric)
|
||||||
save_top_k: 2 # save k best models (determined by above metric)
|
save_last: True # additionaly always save model from last epoch
|
||||||
save_last: True # additionaly always save model from last epoch
|
mode: "max" # can be "max" or "min"
|
||||||
mode: "max" # can be "max" or "min"
|
filepath: "checkpoints/{epoch}"
|
||||||
filepath: "checkpoints/{epoch}"
|
|
||||||
|
|
||||||
|
|
||||||
early_stopping:
|
early_stopping:
|
||||||
class: pytorch_lightning.callbacks.EarlyStopping
|
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||||
args:
|
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
||||||
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
patience: 100 # how many epochs of not improving until training stops
|
||||||
patience: 100 # how many epochs of not improving until training stops
|
mode: "max" # can be "max" or "min"
|
||||||
mode: "max" # can be "max" or "min"
|
min_delta: 0.0 # minimum change in the monitored metric needed to qualify as an improvement
|
||||||
min_delta: 0.0 # minimum change in the monitored metric needed to qualify as an improvement
|
|
||||||
@@ -4,12 +4,10 @@ defaults:
|
|||||||
|
|
||||||
|
|
||||||
save_confusion_matrix_to_wandb:
|
save_confusion_matrix_to_wandb:
|
||||||
class: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
|
_target_: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
|
||||||
args:
|
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
|
||||||
|
|
||||||
|
|
||||||
save_f1_precision_recall_heatmap_to_wandb:
|
save_f1_precision_recall_heatmap_to_wandb:
|
||||||
class: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb
|
_target_: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb
|
||||||
args:
|
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
|
||||||
@@ -3,30 +3,15 @@ defaults:
|
|||||||
|
|
||||||
|
|
||||||
save_best_metric_scores_to_wandb:
|
save_best_metric_scores_to_wandb:
|
||||||
class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
_target_: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
||||||
args: {}
|
|
||||||
|
|
||||||
|
|
||||||
upload_code_to_wandb_as_artifact:
|
upload_code_to_wandb_as_artifact:
|
||||||
class: src.callbacks.wandb_callbacks.SaveCodeToWandb
|
_target_: src.callbacks.wandb_callbacks.SaveCodeToWandb
|
||||||
args:
|
code_dir: ${original_work_dir}/
|
||||||
code_dir: ${work_dir}/
|
|
||||||
|
|
||||||
|
|
||||||
upload_ckpts_to_wandb_as_artifact:
|
upload_ckpts_to_wandb_as_artifact:
|
||||||
class: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
_target_: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
||||||
args:
|
ckpt_dir: "checkpoints/"
|
||||||
ckpt_dir: "checkpoints/"
|
upload_best_only: False
|
||||||
upload_best_only: False
|
|
||||||
|
|
||||||
|
|
||||||
#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']
|
|
||||||
@@ -5,11 +5,14 @@ defaults:
|
|||||||
- trainer: default_trainer.yaml
|
- trainer: default_trainer.yaml
|
||||||
- model: mnist_model.yaml
|
- model: mnist_model.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
- optimizer: adam.yaml
|
|
||||||
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
|
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
|
||||||
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
|
|
||||||
|
# we add this just to enable color logging
|
||||||
|
# - hydra/hydra_logging: colorlog
|
||||||
|
# - hydra/job_logging: colorlog
|
||||||
|
|
||||||
|
|
||||||
# path to original working directory (the directory that `train.py` was executed from in command line)
|
# path to original working directory (the directory that `train.py` was executed from in command line)
|
||||||
# hydra hijacks working directory by changing it to the current log directory,
|
# hydra hijacks working directory by changing it to the current log directory,
|
||||||
@@ -22,20 +25,6 @@ original_work_dir: ${hydra:runtime.cwd}
|
|||||||
data_dir: ${original_work_dir}/data/
|
data_dir: ${original_work_dir}/data/
|
||||||
|
|
||||||
|
|
||||||
# define which things will be saved as hyperparameters by lightning loggers
|
|
||||||
extra_logs:
|
|
||||||
save_model_class_path: True
|
|
||||||
save_optimizer_class_path: True
|
|
||||||
save_datamodule_class_path: True
|
|
||||||
save_model_architecture_class_path: True
|
|
||||||
save_model_args: True
|
|
||||||
save_datamodule_args: True
|
|
||||||
save_optimizer_args: True
|
|
||||||
save_trainer_args: False
|
|
||||||
save_seeds: True
|
|
||||||
save_data_train_val_test_sizes: False
|
|
||||||
|
|
||||||
|
|
||||||
# output paths for hydra logs
|
# output paths for hydra logs
|
||||||
hydra:
|
hydra:
|
||||||
run:
|
run:
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
class: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
args:
|
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
||||||
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
batch_size: 64
|
||||||
batch_size: 64
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
num_workers: 1
|
||||||
num_workers: 1
|
pin_memory: False
|
||||||
pin_memory: False
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
# @package _global_
|
||||||
|
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=exp_example_advanced
|
# python train.py +experiment=exp_example_advanced
|
||||||
|
|
||||||
@@ -5,7 +7,6 @@ defaults:
|
|||||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
|
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
|
||||||
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder
|
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder
|
||||||
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' 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 /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder
|
||||||
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
|
||||||
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
||||||
@@ -15,51 +16,41 @@ defaults:
|
|||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
|
|
||||||
seeds:
|
seeds:
|
||||||
pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule)
|
pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule)
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
args:
|
min_epochs: 1 # train for at least this many epochs (denies early stopping)
|
||||||
min_epochs: 1 # train for at least this many epochs (denies early stopping)
|
max_epochs: 10 # train for maximum this many epochs
|
||||||
max_epochs: 10 # train for maximum this many epochs
|
gradient_clip_val: 0.5 # gradient clipping (helps with exploding gradient issues)
|
||||||
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
|
||||||
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
|
||||||
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_train_batches: 0.6 # train on 60% of training data
|
limit_val_batches: 0.9 # validate on 90% of validation data
|
||||||
limit_val_batches: 0.9 # validate on 90% of validation data
|
limit_test_batches: 1.0 # test on 100% of test data
|
||||||
limit_test_batches: 1.0 # test on 100% of test data
|
val_check_interval: 0.5 # perform validation twice per epoch
|
||||||
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)
|
||||||
# resume_from_checkpoint: ${work_dir}/last.ckpt # path to checkpoint (this can be also url for download)
|
|
||||||
|
|
||||||
model:
|
model: # you can add here any params you want and then access them in lightning model
|
||||||
args: # you can add here any params you want and then access them in lightning model
|
lr: 0.001
|
||||||
input_size: 784 # img size is 1*28*28
|
weight_decay: 0.00001
|
||||||
output_size: 10 # there are 10 digit classes
|
input_size: 784 # img size is 1*28*28
|
||||||
lin1_size: 256
|
output_size: 10 # there are 10 digit classes
|
||||||
lin2_size: 256
|
lin1_size: 256
|
||||||
lin3_size: 128
|
lin2_size: 256
|
||||||
|
lin3_size: 128
|
||||||
|
|
||||||
datamodule:
|
datamodule: # you can add here any params you want and then access them in lightning datamodule
|
||||||
args: # you can add here any params you want and then access them in lightning datamodule
|
batch_size: 64
|
||||||
batch_size: 64
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
num_workers: 1 # num of processes used for loading data in parallel
|
||||||
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
|
||||||
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
|
|
||||||
|
|
||||||
optimizer:
|
logger: # you can add here additional logger arguments specific for this experiment
|
||||||
args:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
|
|
||||||
logger:
|
|
||||||
# you can add here additional logger arguments specific for this experiment
|
|
||||||
wandb:
|
wandb:
|
||||||
args:
|
tags: ["best_model", "uwu"]
|
||||||
tags: ["best_model", "uwu"]
|
notes: "Description of this model."
|
||||||
notes: "Description of this model."
|
group: "mnist"
|
||||||
group: "mnist"
|
|
||||||
comet:
|
comet:
|
||||||
args:
|
tags: ["best_model"]
|
||||||
tags: ["best_model"]
|
|
||||||
csv_logger:
|
csv_logger:
|
||||||
args:
|
save_dir: "."
|
||||||
save_dir: "."
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
# @package _global_
|
||||||
|
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=exp_example_simple
|
# python train.py +experiment=exp_example_simple
|
||||||
|
|
||||||
@@ -5,11 +7,10 @@ defaults:
|
|||||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
|
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
|
||||||
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder or set to null
|
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder or set to null
|
||||||
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder or set to null
|
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder or set to null
|
||||||
- override /optimizer: adam.yaml # choose optimizer from 'configs/optimizer/' folder or set to null
|
|
||||||
- override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder or set to null
|
- override /seeds: default_seeds.yaml # choose seeds from 'configs/seeds/' folder or set to null
|
||||||
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder or set to null
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder or set to null
|
||||||
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
||||||
# `python train.py +experiment=exp_example_with_paths logger=wandb`
|
# `python train.py +experiment=exp_example_simple logger=wandb`
|
||||||
|
|
||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
@@ -18,21 +19,14 @@ seeds:
|
|||||||
pytorch_seed: 12345
|
pytorch_seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
args:
|
max_epochs: 10
|
||||||
max_epochs: 10
|
|
||||||
|
|
||||||
model:
|
model:
|
||||||
args:
|
lr: 0.001
|
||||||
lin1_size: 128
|
lin1_size: 128
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 64
|
lin3_size: 64
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
args:
|
batch_size: 64
|
||||||
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
|
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
# @package _global_
|
||||||
|
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=exp_example_with_paths
|
# python train.py +experiment=exp_example_with_paths
|
||||||
|
|
||||||
@@ -5,7 +7,6 @@ defaults:
|
|||||||
- override /trainer: null # override trainer to null so it's not loaded from main config defaults
|
- override /trainer: null # override trainer to null so it's not loaded from main config defaults
|
||||||
- override /model: null # override model to null so it's not loaded from main config defaults
|
- override /model: null # override model to null so it's not loaded from main config defaults
|
||||||
- override /datamodule: null # override datamodel to null so it's not loaded from main config defaults
|
- override /datamodule: null # override datamodel to null so it's not loaded from main config defaults
|
||||||
- override /optimizer: null # override datamodel to null so it's not loaded from main config defaults
|
|
||||||
- override /seeds: null # override seeds to null so it's not loaded from main config defaults
|
- override /seeds: null # override seeds to null so it's not loaded from main config defaults
|
||||||
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
|
||||||
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
- override /logger: null # choose logger from 'configs/logger/' folder or set it from console when running experiment:
|
||||||
@@ -18,37 +19,32 @@ seeds:
|
|||||||
pytorch_seed: 12345
|
pytorch_seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
# trainer is always the same class so we don't need to specify class path
|
_target_: pytorch_lightning.Trainer
|
||||||
args:
|
min_epochs: 1
|
||||||
min_epochs: 1
|
max_epochs: 10
|
||||||
max_epochs: 10
|
gradient_clip_val: 0.5
|
||||||
gradient_clip_val: 0.5
|
weights_summary: null
|
||||||
gpus: 0
|
gpus: 0
|
||||||
|
|
||||||
model:
|
model:
|
||||||
class: src.models.simple_mnist_classifier.LitModel
|
_target_: src.models.mnist_model.LitModelMNIST
|
||||||
args:
|
optimizer_config: adam
|
||||||
optimizer_config: ${optimizer}
|
lr: 0.001
|
||||||
architecture: SimpleDenseNet
|
weight_decay: 0.00001
|
||||||
input_size: 784
|
architecture: SimpleDenseNet
|
||||||
lin1_size: 256
|
input_size: 784
|
||||||
dropout1: 0.25
|
lin1_size: 256
|
||||||
lin2_size: 256
|
dropout1: 0.25
|
||||||
dropout2: 0.25
|
lin2_size: 256
|
||||||
lin3_size: 128
|
dropout2: 0.25
|
||||||
dropout3: 0.20
|
lin3_size: 128
|
||||||
output_size: 10
|
dropout3: 0.20
|
||||||
|
output_size: 10
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
class: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
args:
|
data_dir: ${data_dir}
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
num_workers: 1
|
num_workers: 1
|
||||||
pin_memory: False
|
pin_memory: False
|
||||||
|
|
||||||
optimizer:
|
|
||||||
class: torch.optim.Adam
|
|
||||||
args:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
@@ -2,6 +2,6 @@
|
|||||||
defaults:
|
defaults:
|
||||||
- csv_logger.yaml
|
- csv_logger.yaml
|
||||||
- wandb.yaml
|
- wandb.yaml
|
||||||
# - comet.yaml
|
- comet.yaml
|
||||||
# - neptune.yaml
|
- neptune.yaml
|
||||||
# - tensorboard.yaml
|
- tensorboard.yaml
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
# Comet logger config
|
# Comet logger config
|
||||||
comet:
|
comet:
|
||||||
class: pytorch_lightning.logger.CometLogger
|
_target_: pytorch_lightning.logger.CometLogger
|
||||||
args:
|
api_key: ???
|
||||||
api_key: ???
|
project_name: "project_template_test"
|
||||||
project_name: "project_template_test"
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
# Csv logger config
|
# Csv logger config
|
||||||
csv_logger:
|
csv_logger:
|
||||||
class: pytorch_lightning.loggers.CSVLogger
|
_target_: pytorch_lightning.loggers.CSVLogger
|
||||||
args:
|
save_dir: "."
|
||||||
save_dir: "."
|
name: "csv_logger/"
|
||||||
name: "csv_logger/"
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
# Neptune logger config
|
# Neptune logger config
|
||||||
comet:
|
neptune:
|
||||||
class: pytorch_lightning.logger.NeptuneLogger
|
_target_: pytorch_lightning.logger.NeptuneLogger
|
||||||
args: {}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
# Tensorboard logger config
|
# Tensorboard logger config
|
||||||
tensorboard:
|
tensorboard:
|
||||||
class: pytorch_lightning.logger.TensorboardLogger
|
_target_: pytorch_lightning.logger.TensorboardLogger
|
||||||
args: {}
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
# Weights&Biases logger config
|
# Weights&Biases logger config
|
||||||
wandb:
|
wandb:
|
||||||
class: pytorch_lightning.loggers.wandb.WandbLogger
|
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||||
args:
|
project: "env_tests"
|
||||||
project: "env_tests"
|
entity: "" # set to name of your wandb team or just remove it
|
||||||
# entity: "team_name" # set to name of your wandb team or just remove it
|
offline: False # set True to store all logs only locally
|
||||||
offline: False # set True to store all logs only locally
|
job_type: "train"
|
||||||
job_type: "train"
|
save_dir: "."
|
||||||
save_dir: "."
|
|
||||||
@@ -1,12 +1,13 @@
|
|||||||
class: src.models.mnist_model.LitModelMNIST
|
_target_: src.models.mnist_model.LitModelMNIST
|
||||||
args:
|
optimizer: adam
|
||||||
optimizer_config: ${optimizer}
|
lr: 0.001
|
||||||
architecture: SimpleDenseNet
|
weight_decay: 0.000001
|
||||||
input_size: 784
|
architecture: SimpleDenseNet
|
||||||
lin1_size: 256
|
input_size: 784
|
||||||
dropout1: 0.30
|
lin1_size: 256
|
||||||
lin2_size: 256
|
dropout1: 0.30
|
||||||
dropout2: 0.25
|
lin2_size: 256
|
||||||
lin3_size: 128
|
dropout2: 0.25
|
||||||
dropout3: 0.20
|
lin3_size: 128
|
||||||
output_size: 10
|
dropout3: 0.20
|
||||||
|
output_size: 10
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
class: torch.optim.Adam
|
|
||||||
args:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.000001
|
|
||||||
@@ -1,17 +1,16 @@
|
|||||||
# trainer args for debugging model
|
# trainer args for debugging model
|
||||||
args:
|
gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||||
gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
# auto_select_gpus: True
|
||||||
# auto_select_gpus: True
|
|
||||||
|
|
||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
|
|
||||||
# fast_dev_run: True # bugged :( (probably wee need to wait for lightning patch)
|
# fast_dev_run: True # bugged :( (probably wee need to wait for lightning patch)
|
||||||
limit_train_batches: 1.0
|
limit_train_batches: 1.0
|
||||||
limit_val_batches: 1.0
|
limit_val_batches: 1.0
|
||||||
limit_test_batches: 1.0
|
limit_test_batches: 1.0
|
||||||
val_check_interval: 1.0
|
val_check_interval: 1.0
|
||||||
profiler: "simple" # use profiler to print execution time profiling after training ends
|
profiler: "simple" # use profiler to print execution time profiling after training ends
|
||||||
|
|
||||||
progress_bar_refresh_rate: 10
|
progress_bar_refresh_rate: 10
|
||||||
weights_summary: "full"
|
weights_summary: "full"
|
||||||
default_root_dir: "lightning_logs/"
|
default_root_dir: "lightning_logs/"
|
||||||
@@ -1,12 +1,8 @@
|
|||||||
# default args passed to Lightning Trainer on every experiment
|
_target_: pytorch_lightning.Trainer
|
||||||
# they can be combined or overwritten with args set in experiment config
|
gpus: 0 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||||
args:
|
max_epochs: 10
|
||||||
gpus: 0 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
gradient_clip_val: 0.5
|
||||||
# auto_select_gpus: True
|
num_sanity_val_steps: 3
|
||||||
|
progress_bar_refresh_rate: 10
|
||||||
max_epochs: 10
|
weights_summary: null # null in yaml represents python None value
|
||||||
gradient_clip_val: 0.5
|
default_root_dir: "lightning_logs/"
|
||||||
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/"
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
from pytorch_lightning.metrics.classification import Accuracy
|
from pytorch_lightning.metrics.classification import Accuracy
|
||||||
from src.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
|
||||||
@@ -21,7 +20,7 @@ class LitModelMNIST(pl.LightningModule):
|
|||||||
self.accuracy = Accuracy()
|
self.accuracy = Accuracy()
|
||||||
|
|
||||||
# Initialize model architecture
|
# Initialize model architecture
|
||||||
if self.hparams["architecture"] == "SimpleDenseNet":
|
if self.hparams.architecture == "SimpleDenseNet":
|
||||||
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||||
else:
|
else:
|
||||||
raise Exception("Invalid architecture name")
|
raise Exception("Invalid architecture name")
|
||||||
@@ -73,6 +72,4 @@ class LitModelMNIST(pl.LightningModule):
|
|||||||
return loss
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
def configure_optimizers(self):
|
||||||
Optimizer = load_class(self.hparams["optimizer_config"]["class"])
|
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
|
||||||
return Optimizer(self.parameters(), **self.hparams["optimizer_config"]["args"])
|
|
||||||
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
# # THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
|
|
||||||
# # IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
|
|
||||||
#
|
|
||||||
# # hydra imports
|
|
||||||
# from omegaconf import DictConfig
|
|
||||||
# import hydra
|
|
||||||
#
|
|
||||||
# # template utils imports
|
|
||||||
# import src.utils.initializers as utils
|
|
||||||
#
|
|
||||||
# import wandb
|
|
||||||
# from train import train
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# # Replace run config hyperparameters with the ones loaded from wandb sweep server
|
|
||||||
# def replace_hparams(config, sweep_hparams):
|
|
||||||
# for key, value in sweep_hparams.items():
|
|
||||||
# if key == "_wandb":
|
|
||||||
# continue
|
|
||||||
# elif key in config["trainer"]["args"]:
|
|
||||||
# config["trainer"]["args"][key] = value
|
|
||||||
# elif key in config["model"]["args"]:
|
|
||||||
# config["model"]["args"][key] = value
|
|
||||||
# elif key in config["optimizer"]["args"]:
|
|
||||||
# config["optimizer"]["args"][key] = value
|
|
||||||
# elif key in config["datamodule"]["args"]:
|
|
||||||
# config["datamodule"]["args"][key] = value
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# @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.print_config(config) # print content of config
|
|
||||||
#
|
|
||||||
# train(config)
|
|
||||||
# wandb.finish()
|
|
||||||
#
|
|
||||||
#
|
|
||||||
# if __name__ == "__main__":
|
|
||||||
# main()
|
|
||||||
@@ -2,7 +2,7 @@ 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 src.models.mnist_model import LitModel
|
from src.models.mnist_model import LitModelMNIST
|
||||||
|
|
||||||
# ckpt can be a url!
|
# ckpt can be a url!
|
||||||
|
|
||||||
@@ -18,7 +18,7 @@ def predict():
|
|||||||
CKPT_PATH = "epoch=0.ckpt"
|
CKPT_PATH = "epoch=0.ckpt"
|
||||||
|
|
||||||
# load model from checkpoint
|
# load model from checkpoint
|
||||||
trained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
trained_model = LitModelMNIST.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||||
|
|
||||||
# switch to evaluation mode
|
# switch to evaluation mode
|
||||||
trained_model.eval()
|
trained_model.eval()
|
||||||
|
|||||||
@@ -1,171 +0,0 @@
|
|||||||
# pytorch lightning imports
|
|
||||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
|
||||||
import pytorch_lightning as pl
|
|
||||||
|
|
||||||
# hydra imports
|
|
||||||
from omegaconf import DictConfig, OmegaConf
|
|
||||||
|
|
||||||
# normal imports
|
|
||||||
from typing import List
|
|
||||||
import importlib
|
|
||||||
import logging
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def load_class(class_path) -> type:
|
|
||||||
"""Load class from a given path."""
|
|
||||||
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:
|
|
||||||
"""Initialize an object from a given class path and args."""
|
|
||||||
return load_class(class_path)(**args)
|
|
||||||
|
|
||||||
|
|
||||||
def init_model(model_config: dict) -> pl.LightningModule:
|
|
||||||
"""Initialize LightningModule from a given model config."""
|
|
||||||
model_class = model_config["class"]
|
|
||||||
model_args = model_config["args"]
|
|
||||||
LitModelClass = load_class(model_class)
|
|
||||||
return LitModelClass(**model_args)
|
|
||||||
|
|
||||||
|
|
||||||
def init_datamodule(datamodule_config: dict) -> pl.LightningDataModule:
|
|
||||||
"""Initialize LightningDataModule from a given datamodule config."""
|
|
||||||
datamodule_class = datamodule_config["class"]
|
|
||||||
datamodule_args = datamodule_config["args"]
|
|
||||||
DataModuleClass = load_class(datamodule_class)
|
|
||||||
datamodule = DataModuleClass(**datamodule_args)
|
|
||||||
datamodule.prepare_data()
|
|
||||||
datamodule.setup()
|
|
||||||
return datamodule
|
|
||||||
|
|
||||||
|
|
||||||
def init_trainer(trainer_config: dict,
|
|
||||||
callbacks: List[pl.Callback],
|
|
||||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
|
||||||
"""Initialize PyTorch Lightning Trainer from a given trainer config."""
|
|
||||||
trainer = pl.Trainer(
|
|
||||||
callbacks=callbacks,
|
|
||||||
logger=loggers,
|
|
||||||
**trainer_config["args"]
|
|
||||||
)
|
|
||||||
return trainer
|
|
||||||
|
|
||||||
|
|
||||||
def init_callbacks(callbacks_config: dict) -> List[pl.Callback]:
|
|
||||||
"""Initialize callbacks from a given callbacks config."""
|
|
||||||
callbacks = []
|
|
||||||
for callback_name, callback_conf in callbacks_config.items():
|
|
||||||
class_path = callback_conf.get("class", None)
|
|
||||||
if class_path:
|
|
||||||
callback_obj = init_object(class_path=class_path, args=callback_conf.get("args", {}))
|
|
||||||
assert issubclass(callback_obj.__class__, pl.Callback), \
|
|
||||||
f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`."
|
|
||||||
callbacks.append(callback_obj)
|
|
||||||
return callbacks
|
|
||||||
|
|
||||||
|
|
||||||
def init_loggers(loggers_config: dict) -> List[pl.loggers.LightningLoggerBase]:
|
|
||||||
"""Initialize loggers from a given loggers config."""
|
|
||||||
loggers = []
|
|
||||||
for logger_name, logger_conf in loggers_config.items():
|
|
||||||
class_path = logger_conf.get("class", None)
|
|
||||||
if class_path:
|
|
||||||
logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {}))
|
|
||||||
assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \
|
|
||||||
f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`."
|
|
||||||
loggers.append(logger_obj)
|
|
||||||
return loggers
|
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(loggers: List[pl.loggers.LightningLoggerBase]) -> WandbLogger:
|
|
||||||
for logger in loggers:
|
|
||||||
if isinstance(logger, WandbLogger):
|
|
||||||
return logger
|
|
||||||
|
|
||||||
|
|
||||||
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, 'architecture'):
|
|
||||||
wandb_logger.watch(model.architecture, log=None)
|
|
||||||
else:
|
|
||||||
wandb_logger.watch(model, log=None)
|
|
||||||
|
|
||||||
|
|
||||||
def send_hparams_to_loggers(loggers: List[pl.loggers.LightningLoggerBase], hparams: dict):
|
|
||||||
for logger in loggers:
|
|
||||||
logger.log_hyperparams(hparams)
|
|
||||||
|
|
||||||
|
|
||||||
def log_hparams(loggers: List[pl.loggers.LightningLoggerBase],
|
|
||||||
config: dict,
|
|
||||||
model: pl.LightningModule,
|
|
||||||
datamodule: pl.LightningDataModule,
|
|
||||||
callbacks: List[pl.callbacks.Callback]):
|
|
||||||
extra_logs = config.get("extra_logs", {})
|
|
||||||
|
|
||||||
if extra_logs.get("save_model_class_path", None):
|
|
||||||
hparams = {"_class_model": config["model"]["class"]}
|
|
||||||
send_hparams_to_loggers(loggers, hparams)
|
|
||||||
if extra_logs.get("save_optimizer_class_path", None):
|
|
||||||
hparams = {"_class_optimizer": config["optimizer"]["class"]}
|
|
||||||
send_hparams_to_loggers(loggers, hparams)
|
|
||||||
if extra_logs.get("save_datamodule_class_path", None):
|
|
||||||
hparams = {"_class_datamodule": config["datamodule"]["class"]}
|
|
||||||
send_hparams_to_loggers(loggers, hparams)
|
|
||||||
if extra_logs.get("save_model_architecture_class_path", None):
|
|
||||||
if hasattr(model, "architecture"):
|
|
||||||
obj = model.architecture
|
|
||||||
hparams = {"_class_model_architecture": obj.__module__ + "." + obj.__class__.__name__}
|
|
||||||
send_hparams_to_loggers(loggers, hparams)
|
|
||||||
|
|
||||||
if extra_logs.get("save_seeds", None):
|
|
||||||
send_hparams_to_loggers(loggers, config["seeds"])
|
|
||||||
|
|
||||||
if extra_logs.get("save_model_args", None):
|
|
||||||
send_hparams_to_loggers(loggers, config["model"]["args"])
|
|
||||||
if extra_logs.get("save_datamodule_args", None):
|
|
||||||
send_hparams_to_loggers(loggers, config["datamodule"]["args"])
|
|
||||||
if extra_logs.get("save_optimizer_args", None):
|
|
||||||
send_hparams_to_loggers(loggers, config["optimizer"]["args"])
|
|
||||||
if extra_logs.get("save_trainer_args", None):
|
|
||||||
send_hparams_to_loggers(loggers, config["trainer"]["args"])
|
|
||||||
|
|
||||||
if extra_logs.get("save_data_train_val_test_sizes", None):
|
|
||||||
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)
|
|
||||||
send_hparams_to_loggers(loggers, hparams)
|
|
||||||
|
|
||||||
|
|
||||||
def print_module_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 print_config(config: DictConfig):
|
|
||||||
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
|
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# pytorch lightning imports
|
||||||
|
import wandb
|
||||||
|
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||||
|
import pytorch_lightning as pl
|
||||||
|
|
||||||
|
# hydra imports
|
||||||
|
from omegaconf import DictConfig, OmegaConf
|
||||||
|
|
||||||
|
# normal imports
|
||||||
|
from typing import List
|
||||||
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
def print_config(config: DictConfig):
|
||||||
|
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
|
||||||
|
|
||||||
|
|
||||||
|
def print_module_init_info(model, datamodule, callbacks, loggers, trainer):
|
||||||
|
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)
|
||||||
|
|
||||||
|
message = "Trainer initialised:" + "\n" + trainer.__module__ + "." + trainer.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
|
||||||
|
def make_wandb_watch_model(loggers: List[pl.loggers.LightningLoggerBase], model: pl.LightningModule):
|
||||||
|
for logger in loggers:
|
||||||
|
if isinstance(logger, WandbLogger):
|
||||||
|
if hasattr(model, 'architecture'):
|
||||||
|
logger.watch(model.architecture, log=None)
|
||||||
|
else:
|
||||||
|
logger.watch(model, log=None)
|
||||||
|
|
||||||
|
|
||||||
|
def send_hparams_to_loggers(loggers: List[pl.loggers.LightningLoggerBase], hparams: dict):
|
||||||
|
for logger in loggers:
|
||||||
|
logger.log_hyperparams(hparams)
|
||||||
|
|
||||||
|
|
||||||
|
def log_hparams(config, model, datamodule, callbacks, loggers, trainer):
|
||||||
|
hparams = {
|
||||||
|
"_class_model": config["model"]["_target_"],
|
||||||
|
"_class_datamodule": config["datamodule"]["_target_"]
|
||||||
|
}
|
||||||
|
|
||||||
|
if hasattr(model, "architecture"):
|
||||||
|
obj = model.architecture
|
||||||
|
hparams["_class_model_architecture"] = obj.__module__ + "." + obj.__class__.__name__
|
||||||
|
|
||||||
|
hparams.update(config["seeds"])
|
||||||
|
hparams.update(config["model"])
|
||||||
|
hparams.update(config["datamodule"])
|
||||||
|
hparams.update(config["trainer"])
|
||||||
|
hparams.pop("_target_")
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
|
send_hparams_to_loggers(loggers=loggers, hparams=hparams)
|
||||||
|
|
||||||
|
|
||||||
|
def extras(config, model, datamodule, callbacks, loggers, trainer):
|
||||||
|
# Print info about which modules were initialized
|
||||||
|
print_module_init_info(model, datamodule, callbacks, loggers, trainer)
|
||||||
|
|
||||||
|
# Log extra hyperparameters to loggers
|
||||||
|
log_hparams(config, model, datamodule, callbacks, loggers, trainer)
|
||||||
|
|
||||||
|
# If WandbLogger was initialized, make it watch the model
|
||||||
|
make_wandb_watch_model(loggers=loggers, model=model)
|
||||||
|
|
||||||
|
|
||||||
|
def finish():
|
||||||
|
wandb.finish()
|
||||||
+18
-22
@@ -1,6 +1,6 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
from pytorch_lightning.loggers import LightningLoggerBase
|
from pytorch_lightning.loggers import LightningLoggerBase
|
||||||
import pytorch_lightning as pl
|
from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
# hydra imports
|
# hydra imports
|
||||||
@@ -9,10 +9,9 @@ import hydra
|
|||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List
|
from typing import List
|
||||||
import wandb
|
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
import src.utils.initializers as utils
|
from src.utils import template_utils as utils
|
||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train(config):
|
||||||
@@ -21,32 +20,29 @@ def train(config):
|
|||||||
torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
|
torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
model: pl.LightningModule = utils.init_model(model_config=config["model"])
|
model: LightningModule = hydra.utils.instantiate(config["model"])
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: pl.LightningDataModule = utils.init_datamodule(datamodule_config=config["datamodule"])
|
datamodule: LightningDataModule = hydra.utils.instantiate(config["datamodule"])
|
||||||
|
|
||||||
# Init PyTorch Lightning callbacks ⚡
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
callbacks = []
|
callbacks: List[Callback] = [
|
||||||
if "callbacks" in config:
|
hydra.utils.instantiate(callback_conf)
|
||||||
callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"])
|
for callback_name, callback_conf in config["callbacks"].items()
|
||||||
|
] if "callbacks" in config else []
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers ⚡
|
# Init PyTorch Lightning loggers ⚡
|
||||||
loggers = []
|
loggers: List[LightningLoggerBase] = [
|
||||||
if "logger" in config:
|
hydra.utils.instantiate(logger_conf)
|
||||||
loggers: List[pl.loggers.LightningLoggerBase] = utils.init_loggers(loggers_config=config["logger"])
|
for logger_name, logger_conf in config["logger"].items()
|
||||||
|
if "_target_" in logger_conf # ignore logger conf if there's no target
|
||||||
|
] if "logger" in config else []
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: pl.Trainer = utils.init_trainer(trainer_config=config["trainer"], callbacks=callbacks, loggers=loggers)
|
trainer: Trainer = hydra.utils.instantiate(config["trainer"], callbacks=callbacks, logger=loggers)
|
||||||
|
|
||||||
# Print info in terminal about all succesfully initialized objects
|
# Magic
|
||||||
utils.print_module_init_info(model=model, datamodule=datamodule, callbacks=callbacks, loggers=loggers)
|
utils.extras(config, model, datamodule, callbacks, loggers, trainer)
|
||||||
|
|
||||||
# If WandbLogger was initialized, make it watch the model
|
|
||||||
utils.make_wandb_watch_model(loggers=loggers, model=model)
|
|
||||||
|
|
||||||
# Make loggers save hyperparameters specified in 'extra_logs' section of config
|
|
||||||
utils.log_hparams(loggers=loggers, config=config, model=model, datamodule=datamodule, callbacks=callbacks)
|
|
||||||
|
|
||||||
# Train the model
|
# Train the model
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
@@ -54,8 +50,8 @@ def train(config):
|
|||||||
# Evaluate model on test set after training
|
# Evaluate model on test set after training
|
||||||
trainer.test()
|
trainer.test()
|
||||||
|
|
||||||
# Finish wandb run if WandbLogger was initialized (otherwise next run in hydra multirun would crash)
|
# Finish run
|
||||||
wandb.finish()
|
utils.finish()
|
||||||
|
|
||||||
|
|
||||||
@hydra.main(config_path="configs/", config_name="config.yaml")
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
|
|||||||
+1
-1
@@ -7,4 +7,4 @@ hydra-core>=1.1.0.dev2
|
|||||||
wandb>=0.10.14
|
wandb>=0.10.14
|
||||||
scikit-learn>=0.24.0
|
scikit-learn>=0.24.0
|
||||||
pandas>=1.2.0
|
pandas>=1.2.0
|
||||||
# hydra_colorlog>=1.0.0
|
hydra_colorlog>=1.0.0
|
||||||
Reference in new issue
Block a user