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
|
||||
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>
|
||||
|
||||
The goal is to:
|
||||
- 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
|
||||
- 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>
|
||||
|
||||
@@ -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))
|
||||
- Composing configuration files out of other configuration files
|
||||
- Scheduling execution of many experiments
|
||||
- Searching over hyperparameters from command line
|
||||
- Overriding any config parameter from command line
|
||||
- Command line tab completion
|
||||
- Logging history of all executed runs/experiments
|
||||
- ~~Automatically validate config structure with config schemas~~ (TODO)
|
||||
- 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))
|
||||
- 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)
|
||||
- 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 conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
||||
- 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
|
||||
│ │ ├── callbacks <- Configurations of lightning callbacks
|
||||
│ │ ├── logger <- Configurations of lightning loggers
|
||||
│ │ ├── optimizer <- Configurations of optimizers
|
||||
│ │ ├── seeds <- Configurations of seeds
|
||||
│ │ ├── experiment <- Configurations of experiments
|
||||
│ │ │
|
||||
@@ -68,13 +73,13 @@ The directory structure of new project looks like this:
|
||||
│ │ ├── transforms <- Data transformations
|
||||
│ │ └── utils <- Utility scripts
|
||||
│ │ ├── 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
|
||||
│
|
||||
├── .gitignore <- Ignored files
|
||||
├── LICENSE <- Project license
|
||||
├── README.md <- Readme
|
||||
├── .gitignore
|
||||
├── LICENSE
|
||||
├── README.md
|
||||
├── conda_env.yaml <- File for installing conda environment
|
||||
├── requirements.txt <- File for installing python dependencies
|
||||
└── 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 config contains default training configuration.<br>
|
||||
It determines how config is composed when simply executing command: `python train.py`
|
||||
```yaml
|
||||
# to execute run with default training configuration simply run:
|
||||
# `python train.py`
|
||||
|
||||
|
||||
# specify here default training configuration
|
||||
defaults:
|
||||
- trainer: default_trainer.yaml
|
||||
- model: mnist_model.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`)
|
||||
|
||||
# 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)
|
||||
# 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/
|
||||
|
||||
|
||||
# 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
|
||||
hydra:
|
||||
run:
|
||||
@@ -135,14 +135,18 @@ hydra:
|
||||
You can store many experiment configurations in this folder.<br>
|
||||
Example experiment configuration:
|
||||
```yaml
|
||||
# to execute this experiment run:
|
||||
# python train.py +experiment=exp_example_simple
|
||||
|
||||
defaults:
|
||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/'
|
||||
- override /model: mnist_model.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/'
|
||||
- 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 /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 /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:
|
||||
# `python train.py +experiment=exp_example_simple logger=wandb`
|
||||
|
||||
# all parameters below will be merged with parameters from default configurations set above
|
||||
# this allows you to overwrite only specified parameters
|
||||
@@ -151,30 +155,18 @@ seeds:
|
||||
pytorch_seed: 12345
|
||||
|
||||
trainer:
|
||||
args:
|
||||
max_epochs: 10
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
|
||||
model:
|
||||
args:
|
||||
input_size: 784
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
lin2_size: 256
|
||||
lin3_size: 128
|
||||
lr: 0.001
|
||||
lin1_size: 128
|
||||
lin2_size: 256
|
||||
lin3_size: 64
|
||||
|
||||
datamodule:
|
||||
args:
|
||||
batch_size: 32
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
|
||||
optimizer:
|
||||
args:
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
```
|
||||
To execute this experiment run:
|
||||
```bash
|
||||
python train.py +experiment=exp_example_simple
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
```
|
||||
<br>
|
||||
|
||||
@@ -265,9 +257,8 @@ Or you can train model with chosen logger like Weights&Biases:
|
||||
```yaml
|
||||
# set project and entity names in project/configs/logger/wandb.yaml
|
||||
wandb:
|
||||
args:
|
||||
project: "your_project_name"
|
||||
entity: "your_wandb_team_name"
|
||||
project: "your_project_name"
|
||||
entity: "your_wandb_team_name"
|
||||
```
|
||||
```bash
|
||||
# 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:
|
||||
```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:
|
||||
```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):
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
To update the conda environment run:
|
||||
```bash
|
||||
conda env update --file conda_env.yml
|
||||
```
|
||||
@@ -1,17 +1,15 @@
|
||||
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}"
|
||||
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
||||
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
|
||||
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||
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
|
||||
@@ -4,12 +4,10 @@ defaults:
|
||||
|
||||
|
||||
save_confusion_matrix_to_wandb:
|
||||
class: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
|
||||
args:
|
||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||
_target_: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
|
||||
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']
|
||||
_target_: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb
|
||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||
@@ -3,30 +3,15 @@ defaults:
|
||||
|
||||
|
||||
save_best_metric_scores_to_wandb:
|
||||
class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
||||
args: {}
|
||||
_target_: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
||||
|
||||
|
||||
upload_code_to_wandb_as_artifact:
|
||||
class: src.callbacks.wandb_callbacks.SaveCodeToWandb
|
||||
args:
|
||||
code_dir: ${work_dir}/
|
||||
_target_: src.callbacks.wandb_callbacks.SaveCodeToWandb
|
||||
code_dir: ${original_work_dir}/
|
||||
|
||||
|
||||
upload_ckpts_to_wandb_as_artifact:
|
||||
class: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
||||
args:
|
||||
ckpt_dir: "checkpoints/"
|
||||
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']
|
||||
_target_: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
||||
ckpt_dir: "checkpoints/"
|
||||
upload_best_only: False
|
||||
@@ -5,11 +5,14 @@ defaults:
|
||||
- trainer: default_trainer.yaml
|
||||
- model: mnist_model.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`)
|
||||
|
||||
# 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)
|
||||
# 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/
|
||||
|
||||
|
||||
# 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
|
||||
hydra:
|
||||
run:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
class: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||
args:
|
||||
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
@@ -1,3 +1,5 @@
|
||||
# @package _global_
|
||||
|
||||
# to execute this experiment run:
|
||||
# python train.py +experiment=exp_example_advanced
|
||||
|
||||
@@ -5,7 +7,6 @@ defaults:
|
||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
|
||||
- override /model: mnist_model.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 or set it from console when running experiment:
|
||||
@@ -15,51 +16,41 @@ defaults:
|
||||
# this allows you to overwrite only specified parameters
|
||||
|
||||
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:
|
||||
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)
|
||||
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
|
||||
model: # you can add here any params you want and then access them in lightning 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:
|
||||
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
|
||||
datamodule: # 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:
|
||||
# you can add here additional logger arguments specific for this experiment
|
||||
logger: # you can add here additional logger arguments specific for this experiment
|
||||
wandb:
|
||||
args:
|
||||
tags: ["best_model", "uwu"]
|
||||
notes: "Description of this model."
|
||||
group: "mnist"
|
||||
tags: ["best_model", "uwu"]
|
||||
notes: "Description of this model."
|
||||
group: "mnist"
|
||||
comet:
|
||||
args:
|
||||
tags: ["best_model"]
|
||||
tags: ["best_model"]
|
||||
csv_logger:
|
||||
args:
|
||||
save_dir: "."
|
||||
save_dir: "."
|
||||
@@ -1,3 +1,5 @@
|
||||
# @package _global_
|
||||
|
||||
# to execute this experiment run:
|
||||
# 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 /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 /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 /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:
|
||||
# `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
|
||||
# this allows you to overwrite only specified parameters
|
||||
@@ -18,21 +19,14 @@ seeds:
|
||||
pytorch_seed: 12345
|
||||
|
||||
trainer:
|
||||
args:
|
||||
max_epochs: 10
|
||||
max_epochs: 10
|
||||
|
||||
model:
|
||||
args:
|
||||
lin1_size: 128
|
||||
lin2_size: 256
|
||||
lin3_size: 64
|
||||
lr: 0.001
|
||||
lin1_size: 128
|
||||
lin2_size: 256
|
||||
lin3_size: 64
|
||||
|
||||
datamodule:
|
||||
args:
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
|
||||
optimizer:
|
||||
args:
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
@@ -1,3 +1,5 @@
|
||||
# @package _global_
|
||||
|
||||
# to execute this experiment run:
|
||||
# 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 /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 /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 /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:
|
||||
@@ -18,37 +19,32 @@ seeds:
|
||||
pytorch_seed: 12345
|
||||
|
||||
trainer:
|
||||
# trainer is always the same class so we don't need to specify class path
|
||||
args:
|
||||
min_epochs: 1
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
gpus: 0
|
||||
_target_: pytorch_lightning.Trainer
|
||||
min_epochs: 1
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
weights_summary: null
|
||||
gpus: 0
|
||||
|
||||
model:
|
||||
class: src.models.simple_mnist_classifier.LitModel
|
||||
args:
|
||||
optimizer_config: ${optimizer}
|
||||
architecture: SimpleDenseNet
|
||||
input_size: 784
|
||||
lin1_size: 256
|
||||
dropout1: 0.25
|
||||
lin2_size: 256
|
||||
dropout2: 0.25
|
||||
lin3_size: 128
|
||||
dropout3: 0.20
|
||||
output_size: 10
|
||||
_target_: src.models.mnist_model.LitModelMNIST
|
||||
optimizer_config: adam
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
architecture: SimpleDenseNet
|
||||
input_size: 784
|
||||
lin1_size: 256
|
||||
dropout1: 0.25
|
||||
lin2_size: 256
|
||||
dropout2: 0.25
|
||||
lin3_size: 128
|
||||
dropout3: 0.20
|
||||
output_size: 10
|
||||
|
||||
datamodule:
|
||||
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
|
||||
|
||||
optimizer:
|
||||
class: torch.optim.Adam
|
||||
args:
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||
data_dir: ${data_dir}
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
@@ -2,6 +2,6 @@
|
||||
defaults:
|
||||
- csv_logger.yaml
|
||||
- wandb.yaml
|
||||
# - comet.yaml
|
||||
# - neptune.yaml
|
||||
# - tensorboard.yaml
|
||||
- comet.yaml
|
||||
- neptune.yaml
|
||||
- tensorboard.yaml
|
||||
@@ -1,6 +1,5 @@
|
||||
# Comet logger config
|
||||
comet:
|
||||
class: pytorch_lightning.logger.CometLogger
|
||||
args:
|
||||
api_key: ???
|
||||
project_name: "project_template_test"
|
||||
_target_: pytorch_lightning.logger.CometLogger
|
||||
api_key: ???
|
||||
project_name: "project_template_test"
|
||||
@@ -1,6 +1,5 @@
|
||||
# Csv logger config
|
||||
csv_logger:
|
||||
class: pytorch_lightning.loggers.CSVLogger
|
||||
args:
|
||||
save_dir: "."
|
||||
name: "csv_logger/"
|
||||
_target_: pytorch_lightning.loggers.CSVLogger
|
||||
save_dir: "."
|
||||
name: "csv_logger/"
|
||||
@@ -1,4 +1,3 @@
|
||||
# Neptune logger config
|
||||
comet:
|
||||
class: pytorch_lightning.logger.NeptuneLogger
|
||||
args: {}
|
||||
neptune:
|
||||
_target_: pytorch_lightning.logger.NeptuneLogger
|
||||
@@ -1,4 +1,3 @@
|
||||
# Tensorboard logger config
|
||||
tensorboard:
|
||||
class: pytorch_lightning.logger.TensorboardLogger
|
||||
args: {}
|
||||
_target_: pytorch_lightning.logger.TensorboardLogger
|
||||
@@ -1,9 +1,8 @@
|
||||
# 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: "."
|
||||
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||
project: "env_tests"
|
||||
entity: "" # 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: "."
|
||||
@@ -1,12 +1,13 @@
|
||||
class: src.models.mnist_model.LitModelMNIST
|
||||
args:
|
||||
optimizer_config: ${optimizer}
|
||||
architecture: SimpleDenseNet
|
||||
input_size: 784
|
||||
lin1_size: 256
|
||||
dropout1: 0.30
|
||||
lin2_size: 256
|
||||
dropout2: 0.25
|
||||
lin3_size: 128
|
||||
dropout3: 0.20
|
||||
output_size: 10
|
||||
_target_: src.models.mnist_model.LitModelMNIST
|
||||
optimizer: adam
|
||||
lr: 0.001
|
||||
weight_decay: 0.000001
|
||||
architecture: SimpleDenseNet
|
||||
input_size: 784
|
||||
lin1_size: 256
|
||||
dropout1: 0.30
|
||||
lin2_size: 256
|
||||
dropout2: 0.25
|
||||
lin3_size: 128
|
||||
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
|
||||
args:
|
||||
gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||
# auto_select_gpus: True
|
||||
gpus: 0 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||
# 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)
|
||||
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
|
||||
# fast_dev_run: True # bugged :( (probably wee need to wait for lightning patch)
|
||||
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/"
|
||||
progress_bar_refresh_rate: 10
|
||||
weights_summary: "full"
|
||||
default_root_dir: "lightning_logs/"
|
||||
@@ -1,12 +1,8 @@
|
||||
# default args passed to Lightning Trainer on every experiment
|
||||
# they can be combined or overwritten with args set in experiment config
|
||||
args:
|
||||
gpus: 0 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||
# auto_select_gpus: True
|
||||
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
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/"
|
||||
_target_: pytorch_lightning.Trainer
|
||||
gpus: 0 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
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 src.utils.initializers import load_class
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
@@ -21,7 +20,7 @@ class LitModelMNIST(pl.LightningModule):
|
||||
self.accuracy = Accuracy()
|
||||
|
||||
# Initialize model architecture
|
||||
if self.hparams["architecture"] == "SimpleDenseNet":
|
||||
if self.hparams.architecture == "SimpleDenseNet":
|
||||
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||
else:
|
||||
raise Exception("Invalid architecture name")
|
||||
@@ -73,6 +72,4 @@ class LitModelMNIST(pl.LightningModule):
|
||||
return loss
|
||||
|
||||
def configure_optimizers(self):
|
||||
Optimizer = load_class(self.hparams["optimizer_config"]["class"])
|
||||
return Optimizer(self.parameters(), **self.hparams["optimizer_config"]["args"])
|
||||
|
||||
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
|
||||
@@ -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
|
||||
|
||||
# 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!
|
||||
|
||||
@@ -18,7 +18,7 @@ def predict():
|
||||
CKPT_PATH = "epoch=0.ckpt"
|
||||
|
||||
# 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
|
||||
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
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
import pytorch_lightning as pl
|
||||
from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer
|
||||
import torch
|
||||
|
||||
# hydra imports
|
||||
@@ -9,10 +9,9 @@ import hydra
|
||||
|
||||
# normal imports
|
||||
from typing import List
|
||||
import wandb
|
||||
|
||||
# template utils imports
|
||||
import src.utils.initializers as utils
|
||||
from src.utils import template_utils as utils
|
||||
|
||||
|
||||
def train(config):
|
||||
@@ -21,32 +20,29 @@ def train(config):
|
||||
torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
|
||||
|
||||
# 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 ⚡
|
||||
datamodule: pl.LightningDataModule = utils.init_datamodule(datamodule_config=config["datamodule"])
|
||||
datamodule: LightningDataModule = hydra.utils.instantiate(config["datamodule"])
|
||||
|
||||
# Init PyTorch Lightning callbacks ⚡
|
||||
callbacks = []
|
||||
if "callbacks" in config:
|
||||
callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"])
|
||||
callbacks: List[Callback] = [
|
||||
hydra.utils.instantiate(callback_conf)
|
||||
for callback_name, callback_conf in config["callbacks"].items()
|
||||
] if "callbacks" in config else []
|
||||
|
||||
# Init PyTorch Lightning loggers ⚡
|
||||
loggers = []
|
||||
if "logger" in config:
|
||||
loggers: List[pl.loggers.LightningLoggerBase] = utils.init_loggers(loggers_config=config["logger"])
|
||||
loggers: List[LightningLoggerBase] = [
|
||||
hydra.utils.instantiate(logger_conf)
|
||||
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 ⚡
|
||||
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
|
||||
utils.print_module_init_info(model=model, datamodule=datamodule, callbacks=callbacks, loggers=loggers)
|
||||
|
||||
# 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)
|
||||
# Magic
|
||||
utils.extras(config, model, datamodule, callbacks, loggers, trainer)
|
||||
|
||||
# Train the model
|
||||
trainer.fit(model=model, datamodule=datamodule)
|
||||
@@ -54,8 +50,8 @@ def train(config):
|
||||
# Evaluate model on test set after training
|
||||
trainer.test()
|
||||
|
||||
# Finish wandb run if WandbLogger was initialized (otherwise next run in hydra multirun would crash)
|
||||
wandb.finish()
|
||||
# Finish run
|
||||
utils.finish()
|
||||
|
||||
|
||||
@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
|
||||
scikit-learn>=0.24.0
|
||||
pandas>=1.2.0
|
||||
# hydra_colorlog>=1.0.0
|
||||
hydra_colorlog>=1.0.0
|
||||
Reference in new issue
Block a user