training with hydra works
This commit is contained in:
1 parent
9cffc61c20
commit
610117f161
27 files changed
+247
-430
No files matched your search
@@ -203,7 +203,7 @@ python train.py --no_wandb --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
|
|||||||
|
|
||||||
Or you can train model with Weights&Biases logging
|
Or you can train model with Weights&Biases logging
|
||||||
```yaml
|
```yaml
|
||||||
# set project and entity names in project/project_config.yaml
|
# set project and entity names in project/config.yaml
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
project: "your_project_name"
|
project: "your_project_name"
|
||||||
|
|||||||
@@ -4,14 +4,16 @@ defaults:
|
|||||||
- trainer: default_trainer.yaml
|
- trainer: default_trainer.yaml
|
||||||
- model: simple_mnist_classifier.yaml
|
- model: simple_mnist_classifier.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
|
- optimizer: adam.yaml
|
||||||
- callbacks: default_callbacks.yaml
|
- callbacks: default_callbacks.yaml
|
||||||
- loggers: null
|
- loggers: null
|
||||||
|
|
||||||
|
seeds:
|
||||||
|
pytorch_seed: 12345
|
||||||
|
|
||||||
paths:
|
paths:
|
||||||
data_dir: "data/" # path to data folder (either absolute or relative to placement of 'train.py' file)
|
data_dir: "data" # path to data folder (either absolute or relative to placement of 'train.py' file)
|
||||||
logs_dir: "logs/" # path to logs folder (either absolute or relative to placement of 'train.py' file)
|
logs_dir: "logs" # path to logs folder (either absolute or relative to placement of 'train.py' file)
|
||||||
|
|
||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
run:
|
run:
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule"
|
class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule"
|
||||||
|
args:
|
||||||
hparams:
|
|
||||||
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]
|
||||||
+17
-15
@@ -1,15 +1,17 @@
|
|||||||
# @package _global_
|
# @package _global_
|
||||||
|
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=xxx2
|
# python train.py +experiment=exp_example_advanced
|
||||||
|
|
||||||
defaults:
|
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: null # choose model from 'configs/model/' folder
|
- override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder
|
||||||
- override /datamodule: null # choose datamodule from 'configs/datamodule/' folder
|
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder
|
||||||
|
- override /optimizer: adam.yaml # choose datamodule from 'configs/datamodule/' 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
|
||||||
|
|
||||||
pytorch_seed: 12345 # pytorch seed for this experiment (also affects lightning random_split() method)
|
seeds:
|
||||||
|
pytorch_seed: 12345 # pytorch seed for this experiment (affects torch.utils.data.random_split() method used in mnist_datamodule)
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
args:
|
args:
|
||||||
@@ -18,16 +20,14 @@ trainer:
|
|||||||
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.8 # train only on 80% of training data
|
limit_train_batches: 0.6 # train on 60% of training data
|
||||||
limit_val_batches: 1.0 # validate on 100% 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: "last.ckpt" # use this to resume training from checkpoint
|
||||||
|
|
||||||
model:
|
model:
|
||||||
class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
|
args: # 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
|
|
||||||
weight_decay: 0.00001
|
|
||||||
input_size: 784 # img size is 1*28*28
|
input_size: 784 # img size is 1*28*28
|
||||||
output_size: 10 # there are 10 digit classes
|
output_size: 10 # there are 10 digit classes
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
@@ -35,21 +35,23 @@ model:
|
|||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
|
|
||||||
args: # 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:
|
||||||
|
args:
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.00001
|
||||||
|
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
args: # you can add here additional loggers arguments specific for this experiment
|
args: # you can add here additional loggers arguments specific for this experiment
|
||||||
tags: ["uwu", "best_model"]
|
tags: ["uwu", "best_model"]
|
||||||
|
notes: ""
|
||||||
|
group: ""
|
||||||
comet:
|
comet:
|
||||||
args:
|
args:
|
||||||
tags: ["uwu", "best_model"]
|
tags: ["uwu", "best_model"]
|
||||||
|
|
||||||
resume_training: # use this if you want to resume training from checkpoint
|
|
||||||
checkpoint_path: False # path to your checkpoint
|
|
||||||
logger_run_id: False # loggers experiment id that you want to resume (optional)
|
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# @package _global_
|
||||||
|
|
||||||
|
# to execute this experiment run:
|
||||||
|
# python train.py +experiment=exp_example_simple
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
|
||||||
|
- override /model: simple_mnist_classifier.yaml # choose model from 'configs/model/' folder
|
||||||
|
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder
|
||||||
|
- override /optimizer: adam.yaml # choose datamodule from 'configs/datamodule/' folder
|
||||||
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder
|
||||||
|
|
||||||
|
seeds:
|
||||||
|
pytorch_seed: 12345
|
||||||
|
|
||||||
|
trainer:
|
||||||
|
args:
|
||||||
|
max_epochs: 10
|
||||||
|
|
||||||
|
model:
|
||||||
|
args:
|
||||||
|
input_size: 784
|
||||||
|
output_size: 10
|
||||||
|
lin1_size: 256
|
||||||
|
lin2_size: 256
|
||||||
|
lin3_size: 128
|
||||||
|
|
||||||
|
datamodule:
|
||||||
|
args:
|
||||||
|
batch_size: 32
|
||||||
|
train_val_test_split: (55_000, 5_000, 10_000)
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
args:
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.00001
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
# @package _global_
|
|
||||||
|
|
||||||
# to execute this experiment run:
|
|
||||||
# python train.py +experiment=xxx
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
- override /trainer: default_trainer.yaml
|
|
||||||
- override /model: null
|
|
||||||
- override /datamodule: null
|
|
||||||
- override /callbacks: default_callbacks.yaml
|
|
||||||
|
|
||||||
pytorch_seed: 12345
|
|
||||||
|
|
||||||
trainer:
|
|
||||||
args:
|
|
||||||
max_epochs: 10
|
|
||||||
|
|
||||||
model:
|
|
||||||
class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
|
|
||||||
args:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
input_size: 784
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 256
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
datamodule:
|
|
||||||
class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
|
|
||||||
args:
|
|
||||||
batch_size: 32
|
|
||||||
train_val_test_split: (55_000, 5_000, 10_000)
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
# @package _global_
|
|
||||||
|
|
||||||
# to execute this experiment run:
|
|
||||||
# python train.py +experiment=xxx
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
- override /trainer: default_trainer.yaml
|
|
||||||
- override /logger: wandb.yaml
|
|
||||||
|
|
||||||
pytorch_seed: 12345
|
|
||||||
|
|
||||||
trainer:
|
|
||||||
args:
|
|
||||||
max_epochs: 10
|
|
||||||
|
|
||||||
model:
|
|
||||||
class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
|
|
||||||
hparams:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
input_size: 784
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 256
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
datamodule:
|
|
||||||
class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
|
|
||||||
hparams:
|
|
||||||
batch_size: 32
|
|
||||||
train_val_test_split: (55_000, 5_000, 10_000)
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
# @package _global_
|
|
||||||
|
|
||||||
# to execute this experiment run:
|
|
||||||
# python train.py +experiment=xxx
|
|
||||||
|
|
||||||
defaults:
|
|
||||||
- override /trainer: default_trainer.yaml
|
|
||||||
- override /logger: wandb.yaml
|
|
||||||
|
|
||||||
pytorch_seed: 12345
|
|
||||||
|
|
||||||
trainer:
|
|
||||||
args:
|
|
||||||
max_epochs: 10
|
|
||||||
|
|
||||||
model:
|
|
||||||
class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
|
|
||||||
hparams:
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00001
|
|
||||||
input_size: 784
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 256
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
datamodule:
|
|
||||||
class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
|
|
||||||
hparams:
|
|
||||||
batch_size: 32
|
|
||||||
train_val_test_split: (55_000, 5_000, 10_000)
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# train with all loggers at once
|
# Train with all loggers at once
|
||||||
defaults:
|
defaults:
|
||||||
- comet
|
- comet
|
||||||
- csv_logger
|
- csv_logger
|
||||||
- neptune
|
|
||||||
- tensorboard
|
- tensorboard
|
||||||
- wandb
|
- wandb
|
||||||
@@ -1,13 +1,8 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# Comet loggers config
|
# Comet logger config
|
||||||
comet:
|
comet:
|
||||||
class: pytorch_lightning.loggers.CometLogger
|
class: pytorch_lightning.loggers.CometLogger
|
||||||
|
|
||||||
args:
|
args:
|
||||||
api_key: ???
|
api_key: ???
|
||||||
project_name: "project_template_test"
|
project_name: "project_template_test"
|
||||||
|
|
||||||
extra_options:
|
|
||||||
log_optimizer_name: True
|
|
||||||
log_train_val_test_sizes: True
|
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# default loggers is just lightning CSVLogger which doesn't require any additional dependencies
|
# Csv logger config
|
||||||
csv_logger:
|
csv_logger:
|
||||||
class: pytorch_lightning.loggers.CSVLogger
|
class: pytorch_lightning.loggers.CSVLogger
|
||||||
|
|
||||||
args: {}
|
args: {}
|
||||||
|
|
||||||
extra_options: {}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
# @package _group_
|
|
||||||
|
|
||||||
# Neptune loggers config
|
|
||||||
neptune:
|
|
||||||
class: pytorch_lightning.loggers.NeptuneLogger
|
|
||||||
|
|
||||||
args: {}
|
|
||||||
|
|
||||||
extra_options:
|
|
||||||
log_optimizer_name: True
|
|
||||||
log_train_val_test_sizes: True
|
|
||||||
@@ -1,9 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# Tensorboard loggers config
|
# Tensorboard logger config
|
||||||
tensorboard:
|
tensorboard:
|
||||||
class: pytorch_lightning.loggers.TensorboardLogger
|
class: pytorch_lightning.loggers.TensorboardLogger
|
||||||
|
|
||||||
args: {}
|
args: {}
|
||||||
|
|
||||||
extra_options: {}
|
|
||||||
@@ -1,16 +1,27 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# Weights&Biases loggers config
|
# Weights&Biases logger config
|
||||||
wandb:
|
wandb:
|
||||||
class: pytorch_lightning.loggers.WandbLogger
|
class: pytorch_lightning.loggers.WandbLogger
|
||||||
|
|
||||||
args:
|
args:
|
||||||
project: "project_template_test"
|
project: "project_template_test"
|
||||||
entity: "" # change to your username or name of your team on wandb
|
entity: "" # change to your username or name of your team on wandb
|
||||||
log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
|
offline: False # set True to store all logs only locally
|
||||||
offline: False # set True to store all logs only locally
|
job_type: "train"
|
||||||
|
save_dir: ${paths.logs_dir}
|
||||||
|
|
||||||
extra_options:
|
# some extra things which will be logged by the environment
|
||||||
log_gradients: False # set True to log gradient histograms (avoid this for very big models)
|
extra_logs:
|
||||||
log_optimizer_name: True
|
watch_model: True # make wandb watch model
|
||||||
log_train_val_test_sizes: True
|
log_gradients: False # log gradient histograms (avoid this for very big models)
|
||||||
|
|
||||||
|
log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset
|
||||||
|
|
||||||
|
log_model_args: True # log
|
||||||
|
log_datamodule_args: True # log
|
||||||
|
log_optimizer_args: True # log
|
||||||
|
log_trainer_args: False # log
|
||||||
|
|
||||||
|
log_model_class_name: True
|
||||||
|
log_datamodule_class_name: True
|
||||||
|
log_optimizer_class_name: True
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
# @package _group_
|
|
||||||
|
|
||||||
class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel"
|
|
||||||
|
|
||||||
hparams:
|
|
||||||
YYYYYYY: XXXXXXXXXXXXXXXXXXX
|
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel"
|
class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel"
|
||||||
|
args:
|
||||||
hparams:
|
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
weight_decay: 0.00001
|
weight_decay: 0.00001
|
||||||
input_size: 784
|
input_size: 784
|
||||||
|
|||||||
Whitespace-only changes.
@@ -1 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
|
class: torch.optim.Adam
|
||||||
|
args:
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.000001
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# trainer args for debugging model
|
||||||
|
args:
|
||||||
|
gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||||
|
auto_select_gpus: True
|
||||||
|
|
||||||
|
fast_dev_run: True
|
||||||
|
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: "top"
|
||||||
|
default_root_dir: ${paths.logs_dir}/lightning_logs
|
||||||
@@ -4,10 +4,9 @@
|
|||||||
# they will be combined with trainer args specified in experiment config
|
# they will be combined with trainer args specified in experiment config
|
||||||
# (if the argument repeats in experiment config, then it will override the one set here)
|
# (if the argument repeats in experiment config, then it will override the one set here)
|
||||||
args:
|
args:
|
||||||
num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||||
auto_select_gpus: True
|
auto_select_gpus: True
|
||||||
num_sanity_val_steps: 3
|
num_sanity_val_steps: 3
|
||||||
progress_bar_refresh_rate: 10
|
|
||||||
weights_summary: "top"
|
weights_summary: "top"
|
||||||
profiler: "simple" # use profiler to print execution time profiling after training ends
|
progress_bar_refresh_rate: 10
|
||||||
max_epochs: 100
|
default_root_dir: ${paths.logs_dir}/lightning_logs
|
||||||
@@ -165,7 +165,7 @@ class SaveCodeToWandbCallback(Callback):
|
|||||||
"template_utils/custom_callbacks.py",
|
"template_utils/custom_callbacks.py",
|
||||||
"template_utils/initializers.py",
|
"template_utils/initializers.py",
|
||||||
"train.py",
|
"train.py",
|
||||||
"project_config.yaml",
|
"config.yaml",
|
||||||
"run_configs.yaml",
|
"run_configs.yaml",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -8,22 +8,22 @@ class MNISTDataModule(LightningDataModule):
|
|||||||
"""
|
"""
|
||||||
This is example of datamodule for MNIST dataset.
|
This is example of datamodule for MNIST dataset.
|
||||||
|
|
||||||
The path to datamodule should be specified in your run config. (run_configs.yaml)
|
The path to datamodule should be specified in your run config.
|
||||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
The 'args' dict contains datamodule args specified in config.
|
||||||
|
|
||||||
To learn how to create datamodules visit:
|
To learn how to create datamodules visit:
|
||||||
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, data_dir: str, hparams: dict):
|
def __init__(self, data_dir, **args):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml
|
self.data_dir = data_dir + "/MNIST" # data_dir is specified in config.yaml
|
||||||
|
|
||||||
self.batch_size = hparams.get("batch_size") or 64
|
self.batch_size = args.get("batch_size") or 64
|
||||||
self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||||
self.num_workers = hparams.get("num_workers") or 1
|
self.num_workers = args.get("num_workers") or 1
|
||||||
self.pin_memory = hparams.get("pin_memory") or False
|
self.pin_memory = args.get("pin_memory") or False
|
||||||
|
|
||||||
self.transforms = transforms.ToTensor()
|
self.transforms = transforms.ToTensor()
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ from sklearn.metrics import accuracy_score
|
|||||||
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
|
||||||
|
from template_utils.initializers import init_optimizer
|
||||||
|
|
||||||
# import custom architectures
|
# import custom architectures
|
||||||
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
||||||
@@ -9,10 +10,10 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
|||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
"""
|
"""
|
||||||
This is example of lightning model for MNIST digits classification.
|
This is example of lightning model for MNIST classification.
|
||||||
|
|
||||||
The path to model should be specified in your run config. (run_configs.yaml)
|
The path to model should be specified in your run config. (run_configs.yaml)
|
||||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
The 'hparams' dict contains model args specified in config. (run_configs.yaml)
|
||||||
|
|
||||||
This class enables you to specify what happens during training, validation and test step.
|
This class enables you to specify what happens during training, validation and test step.
|
||||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||||
@@ -21,11 +22,12 @@ class LitModel(pl.LightningModule):
|
|||||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, optimizer_config, **hparams):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.save_hyperparameters(kwargs)
|
self.optimizer_config = optimizer_config
|
||||||
|
self.save_hyperparameters(hparams)
|
||||||
|
|
||||||
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
self.model = SimpleMNISTClassifier(hparams=hparams)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
@@ -77,4 +79,4 @@ class LitModel(pl.LightningModule):
|
|||||||
return loss
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
def configure_optimizers(self):
|
||||||
return torch.optim.Adam(self.parameters(), lr=self.hparams["lr"], weight_decay=self.hparams["weight_decay"])
|
return init_optimizer(optimizer_config=self.optimizer_config, model=self)
|
||||||
@@ -7,9 +7,8 @@ import importlib.util
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
from pytorch_lightning import callbacks as lightning_callbacks
|
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
||||||
from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks
|
import torch
|
||||||
from pytorch_lightning.loggers import CSVLogger
|
|
||||||
|
|
||||||
|
|
||||||
def format_path(path: str, base_dir: str):
|
def format_path(path: str, base_dir: str):
|
||||||
@@ -28,245 +27,161 @@ def format_config_paths(config: dict, base_dir: str) -> dict:
|
|||||||
def load_object(obj_path):
|
def load_object(obj_path):
|
||||||
obj_path, obj_name = obj_path.rsplit('.', 1)
|
obj_path, obj_name = obj_path.rsplit('.', 1)
|
||||||
module = importlib.import_module(obj_path)
|
module = importlib.import_module(obj_path)
|
||||||
|
|
||||||
assert hasattr(module, obj_name), \
|
assert hasattr(module, obj_name), \
|
||||||
f'Object `{obj_name}` cannot be loaded from `{obj_path}`.'
|
f'Object `{obj_name}` cannot be loaded from `{obj_path}`.'
|
||||||
|
|
||||||
return getattr(module, obj_name)
|
return getattr(module, obj_name)
|
||||||
|
|
||||||
|
|
||||||
def init_model(model_config: dict) -> pl.LightningModule:
|
def init_object(obj_path, args):
|
||||||
|
return load_object(obj_path)(**args)
|
||||||
|
|
||||||
|
|
||||||
|
def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule:
|
||||||
"""
|
"""
|
||||||
Load LightningModule from path specified in run config.
|
Load LightningModule from path specified in config.
|
||||||
"""
|
"""
|
||||||
model_class = model_config["class"]
|
model_class = model_config["class"]
|
||||||
model_hparams = model_config["hparams"]
|
model_args = model_config["args"]
|
||||||
|
|
||||||
LitModel = load_object(model_class)
|
LitModel = load_object(model_class)
|
||||||
assert issubclass(LitModel, pl.LightningModule), \
|
assert issubclass(LitModel, pl.LightningModule), \
|
||||||
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
||||||
|
return LitModel(optimizer_config, **model_args)
|
||||||
return LitModel(hparams=model_hparams)
|
|
||||||
|
|
||||||
|
|
||||||
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||||
"""
|
"""
|
||||||
Load LightningDataModule from path specified in run config.
|
Load LightningDataModule from path specified config.
|
||||||
"""
|
"""
|
||||||
datamodule_class = datamodule_config["class"]
|
datamodule_class = datamodule_config["class"]
|
||||||
datamodule_hparams = datamodule_config["hparams"]
|
datamodule_args = datamodule_config["args"]
|
||||||
|
|
||||||
DataModule = load_object(datamodule_class)
|
DataModule = load_object(datamodule_class)
|
||||||
|
|
||||||
assert issubclass(DataModule, pl.LightningDataModule), \
|
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||||
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
||||||
|
datamodule = DataModule(data_dir=data_dir, **datamodule_args)
|
||||||
datamodule = DataModule(data_dir=data_dir, hparams=datamodule_hparams)
|
|
||||||
datamodule.prepare_data()
|
datamodule.prepare_data()
|
||||||
datamodule.setup()
|
datamodule.setup()
|
||||||
|
|
||||||
return datamodule
|
return datamodule
|
||||||
|
|
||||||
|
|
||||||
def init_trainer(project_config: dict,
|
def init_optimizer(optimizer_config, model):
|
||||||
run_config: dict,
|
optimizer_class = optimizer_config["class"]
|
||||||
|
optimizer_args = optimizer_config["args"]
|
||||||
|
Optim = load_object(optimizer_class)
|
||||||
|
assert issubclass(Optim, torch.optim.Optimizer), \
|
||||||
|
f"Specified optimizer class `{optimizer_class}` is not a subclass of `torch.optim.Optimizer`."
|
||||||
|
return Optim(model.parameters(), **optimizer_args)
|
||||||
|
|
||||||
|
|
||||||
|
def init_trainer(trainer_config: dict,
|
||||||
callbacks: List[pl.Callback],
|
callbacks: List[pl.Callback],
|
||||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||||
"""
|
"""
|
||||||
Initialize PyTorch Lightning Trainer.
|
Initialize PyTorch Lightning Trainer.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Get path to checkpoint that you want to resume with if it was set in the run config
|
|
||||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
|
|
||||||
|
|
||||||
trainer = pl.Trainer(
|
trainer = pl.Trainer(
|
||||||
# whether to use gpu and how many
|
|
||||||
gpus=project_config["num_of_gpus"],
|
|
||||||
|
|
||||||
# experiment logging
|
|
||||||
logger=loggers,
|
|
||||||
|
|
||||||
# useful lightning_callbacks
|
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
|
logger=loggers,
|
||||||
# resume training from checkpoint if it was set in the run config
|
**trainer_config["args"]
|
||||||
resume_from_checkpoint=resume_from_checkpoint
|
|
||||||
if resume_from_checkpoint != "None"
|
|
||||||
and resume_from_checkpoint != "False"
|
|
||||||
and resume_from_checkpoint is not False
|
|
||||||
else None,
|
|
||||||
|
|
||||||
# print related
|
|
||||||
progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
|
|
||||||
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
|
|
||||||
weights_summary=project_config["printing"]["weights_summary"],
|
|
||||||
|
|
||||||
# number of validation sanity checks
|
|
||||||
num_sanity_val_steps=3,
|
|
||||||
|
|
||||||
# default log dir if no loggers is found
|
|
||||||
default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"),
|
|
||||||
|
|
||||||
# insert all other trainer args specified in run config
|
|
||||||
**run_config["trainer"]["args"]
|
|
||||||
)
|
)
|
||||||
|
|
||||||
return trainer
|
return trainer
|
||||||
|
|
||||||
|
|
||||||
def init_callbacks(project_config: dict,
|
def init_callbacks(config: dict) -> List[pl.Callback]:
|
||||||
run_config: dict,
|
|
||||||
use_wandb: bool,
|
|
||||||
base_dir: str) -> List[pl.Callback]:
|
|
||||||
"""
|
"""
|
||||||
Initialize default lightning_callbacks and lightning_callbacks specified in run config.
|
Initialize callbacks specified in config.
|
||||||
"""
|
"""
|
||||||
|
callbacks_config = config.get("callbacks", None)
|
||||||
default_callbacks = project_config.get("default_callbacks", {})
|
|
||||||
run_callbacks = run_config.get("lightning_callbacks", {})
|
|
||||||
|
|
||||||
# namespaces in which lightning_callbacks will be searched for
|
|
||||||
namespaces = [
|
|
||||||
lightning_callbacks,
|
|
||||||
custom_callbacks,
|
|
||||||
wandb_callbacks,
|
|
||||||
]
|
|
||||||
|
|
||||||
callbacks = []
|
callbacks = []
|
||||||
|
|
||||||
all_callback_configs = {}
|
if not callbacks_config:
|
||||||
for callback_config in default_callbacks:
|
return callbacks
|
||||||
all_callback_configs[callback_config] = default_callbacks[callback_config]
|
|
||||||
for callback_config in run_callbacks:
|
|
||||||
all_callback_configs[callback_config] = run_callbacks[callback_config]
|
|
||||||
|
|
||||||
for callback_config in all_callback_configs:
|
for callback_name, callback_conf in callbacks_config.items():
|
||||||
found = False
|
callback_class = callback_conf.get("class", None)
|
||||||
for namespace in namespaces:
|
if callback_class:
|
||||||
if hasattr(namespace, callback_config):
|
callback_obj = init_object(callback_class, callback_conf.get("args", {}))
|
||||||
callback_class = getattr(namespace, callback_config)
|
callbacks.append(callback_obj)
|
||||||
callbacks.append(callback_class(**all_callback_configs[callback_config]))
|
|
||||||
found = True
|
|
||||||
break
|
|
||||||
if not found:
|
|
||||||
raise ModuleNotFoundError(f"Callback '{callback_config}' not found.")
|
|
||||||
|
|
||||||
if use_wandb:
|
|
||||||
callbacks.append(
|
|
||||||
wandb_callbacks.SaveCodeToWandbCallback(
|
|
||||||
base_dir=base_dir,
|
|
||||||
wandb_save_dir=project_config["logs_dir"],
|
|
||||||
run_config=run_config
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
|
|
||||||
def init_loggers(project_config: dict,
|
def init_loggers(config: dict,
|
||||||
run_config: dict,
|
|
||||||
model: pl.LightningModule,
|
model: pl.LightningModule,
|
||||||
datamodule: pl.LightningDataModule,
|
datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]:
|
||||||
use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
|
|
||||||
"""
|
"""
|
||||||
Initialize loggers.
|
Initialize loggers specified in config.
|
||||||
"""
|
"""
|
||||||
|
loggers_config = config.get("loggers", None)
|
||||||
loggers = []
|
loggers = []
|
||||||
if use_wandb:
|
|
||||||
wandb_logger = init_wandb_logger(
|
if not loggers_config:
|
||||||
project_config=project_config,
|
return loggers
|
||||||
run_config=run_config,
|
|
||||||
model=model,
|
for logger_name, logger_conf in loggers_config.items():
|
||||||
datamodule=datamodule
|
logger_class = loggers_config.get("class", None)
|
||||||
)
|
if logger_class:
|
||||||
if wandb_logger:
|
if logger_class == "pytorch_lightning.loggers.WandbLogger":
|
||||||
loggers.append(wandb_logger)
|
logger_obj = init_wandb(config, model, datamodule)
|
||||||
|
else:
|
||||||
|
logger_obj = init_object(logger_class, logger_conf.get("args", {}))
|
||||||
|
loggers.append(logger_obj)
|
||||||
|
|
||||||
return loggers
|
return loggers
|
||||||
|
|
||||||
|
|
||||||
def init_wandb_logger(project_config: dict,
|
def init_wandb(config: dict,
|
||||||
run_config: dict,
|
model: pl.LightningModule,
|
||||||
model: pl.LightningModule,
|
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
||||||
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
|
||||||
"""
|
"""
|
||||||
Initialize Weights&Biases loggers.
|
Initialize Weights&Biases logger.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if "loggers" not in project_config or "wandb" not in project_config["loggers"]:
|
|
||||||
return None
|
|
||||||
|
|
||||||
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
||||||
# instead of auto-creating a new run
|
# instead of auto-creating a new run
|
||||||
os.environ["WANDB_RESUME"] = "must"
|
os.environ["WANDB_RESUME"] = "must"
|
||||||
|
|
||||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
|
wandb_config = config["loggers"]["wandb"]
|
||||||
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
wandb_logger = WandbLogger(**wandb_config["args"])
|
||||||
|
|
||||||
wandb_logger = WandbLogger(
|
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
||||||
project=project_config["loggers"]["wandb"]["project"],
|
if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]):
|
||||||
entity=project_config["loggers"]["wandb"]["entity"],
|
os.makedirs(wandb_config["args"]["save_dir"])
|
||||||
log_model=project_config["loggers"]["wandb"]["log_model"],
|
|
||||||
offline=project_config["loggers"]["wandb"]["offline"],
|
|
||||||
|
|
||||||
group=run_config.get("wandb", {}).get("group", None),
|
|
||||||
job_type=run_config.get("wandb", {}).get("job_type", "train"),
|
|
||||||
tags=run_config.get("wandb", {}).get("tags", []),
|
|
||||||
notes=run_config.get("wandb", {}).get("notes", ""),
|
|
||||||
|
|
||||||
# resume run only if ckpt was set in the run config
|
|
||||||
id=wandb_run_id
|
|
||||||
if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None
|
|
||||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
|
||||||
else None,
|
|
||||||
|
|
||||||
save_dir=project_config["logs_dir"],
|
|
||||||
save_code=False
|
|
||||||
)
|
|
||||||
|
|
||||||
if not os.path.exists(project_config["logs_dir"]):
|
|
||||||
os.makedirs(project_config["logs_dir"])
|
|
||||||
|
|
||||||
if hasattr(model, 'model'):
|
if hasattr(model, 'model'):
|
||||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
if wandb_config["extra_options"]["log_gradients"]:
|
||||||
wandb_logger.watch(model.model, log='gradients')
|
wandb_logger.watch(model.model, log='gradients')
|
||||||
else:
|
else:
|
||||||
wandb_logger.watch(model.model, log=None)
|
wandb_logger.watch(model.model, log=None)
|
||||||
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
||||||
else:
|
else:
|
||||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
if wandb_config["extra_options"]["log_gradients"]:
|
||||||
wandb_logger.watch(model, log='gradients')
|
wandb_logger.watch(model, log='gradients')
|
||||||
else:
|
else:
|
||||||
wandb_logger.watch(model, log=None)
|
wandb_logger.watch(model, log=None)
|
||||||
|
|
||||||
wandb_logger.log_hyperparams({
|
if wandb_config["extra_options"]["log_train_val_test_sizes"]:
|
||||||
"optimizer": model.configure_optimizers().__class__.__name__,
|
wandb_logger.log_hyperparams({
|
||||||
"train_size": len(datamodule.data_train)
|
"train_size": len(datamodule.data_train)
|
||||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||||
"val_size": len(datamodule.data_val)
|
"val_size": len(datamodule.data_val)
|
||||||
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
||||||
"test_size": len(datamodule.data_test)
|
"test_size": len(datamodule.data_test)
|
||||||
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
||||||
})
|
})
|
||||||
wandb_logger.log_hyperparams({"num_of_gpus": project_config["num_of_gpus"]})
|
|
||||||
wandb_logger.log_hyperparams(run_config["trainer"]["args"])
|
if wandb_config["extra_options"]["log_model_args"]:
|
||||||
wandb_logger.log_hyperparams(run_config["model"]["hparams"])
|
wandb_logger.log_hyperparams(config["model"]["args"])
|
||||||
wandb_logger.log_hyperparams(run_config["model"]["load_from"])
|
if wandb_config["extra_options"]["log_datamodule_args"]:
|
||||||
wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"])
|
wandb_logger.log_hyperparams(config["datamodule"]["args"])
|
||||||
wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"])
|
if wandb_config["extra_options"]["log_optimizer_args"]:
|
||||||
|
wandb_logger.log_hyperparams(config["optimizer"]["args"])
|
||||||
|
if wandb_config["extra_options"]["log_trainer_args"]:
|
||||||
|
wandb_logger.log_hyperparams(config["trainer"]["args"])
|
||||||
|
|
||||||
|
if wandb_config["extra_options"]["log_model_class_name"]:
|
||||||
|
wandb_logger.log_hyperparams({"model_class": config["model"]["class"]})
|
||||||
|
if wandb_config["extra_options"]["log_datamodule_class_name"]:
|
||||||
|
wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]})
|
||||||
|
if wandb_config["extra_options"]["log_optimizer_class_name"]:
|
||||||
|
wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]})
|
||||||
|
|
||||||
return wandb_logger
|
return wandb_logger
|
||||||
|
|
||||||
|
|
||||||
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
|
|
||||||
"""Initialize tensorboard loggers"""
|
|
||||||
# TODO
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def init_comet_logger(project_config: dict,
|
|
||||||
run_config: dict,
|
|
||||||
model: pl.LightningModule,
|
|
||||||
datamodule: pl.LightningDataModule) -> pl.loggers.CometLogger:
|
|
||||||
|
|
||||||
comet_logger = CometLogger()
|
|
||||||
@@ -4,6 +4,8 @@ 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 pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
|
from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
|
||||||
|
|
||||||
|
# ckpt can be a url!
|
||||||
|
|
||||||
|
|
||||||
def predict():
|
def predict():
|
||||||
"""
|
"""
|
||||||
|
|||||||
+30
-77
@@ -1,17 +1,20 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
|
||||||
from pytorch_lightning.loggers import LightningLoggerBase
|
from pytorch_lightning.loggers import LightningLoggerBase
|
||||||
|
import pytorch_lightning as pl
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
# hydra imports
|
||||||
|
from omegaconf import DictConfig, OmegaConf
|
||||||
|
import hydra.conf.hydra.output
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from argparse import ArgumentParser
|
|
||||||
from typing import List
|
from typing import List
|
||||||
import yaml
|
import logging
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
from template_utils.initializers import (
|
from template_utils.initializers import (
|
||||||
normalize_config_paths,
|
format_config_paths,
|
||||||
init_model,
|
init_model,
|
||||||
init_datamodule,
|
init_datamodule,
|
||||||
init_callbacks,
|
init_callbacks,
|
||||||
@@ -19,56 +22,44 @@ from template_utils.initializers import (
|
|||||||
init_trainer
|
init_trainer
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# Everything will be loaded relatively to placement of 'train.py' file!
|
|
||||||
BASE_DIR: str = os.path.dirname(__file__)
|
BASE_DIR: str = os.path.dirname(__file__)
|
||||||
|
LOG = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
def train(config):
|
||||||
|
|
||||||
# Set global PyTorch seed
|
# Set global PyTorch seed
|
||||||
if "seed" in run_config:
|
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||||
torch.manual_seed(run_config["seed"])
|
torch.manual_seed(config["seeds"]["pytorch_seed"])
|
||||||
|
|
||||||
# Covert paths to absolute and normalize them
|
# Covert paths to absolute and normalize them
|
||||||
project_config, run_config = normalize_config_paths(
|
config = format_config_paths(config=config, base_dir=BASE_DIR)
|
||||||
project_config=project_config,
|
|
||||||
run_config=run_config,
|
|
||||||
base_dir=BASE_DIR
|
|
||||||
)
|
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
model: LightningModule = init_model(
|
model: pl.LightningModule = init_model(
|
||||||
model_config=run_config["model"]
|
model_config=config["model"],
|
||||||
|
optimizer_config=config["optimizer"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: LightningDataModule = init_datamodule(
|
datamodule: pl.LightningDataModule = init_datamodule(
|
||||||
datamodule_config=run_config["datamodule"],
|
datamodule_config=config["datamodule"],
|
||||||
data_dir=project_config["data_dir"]
|
data_dir=config["paths"]["data_dir"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning lightning_callbacks ⚡
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
callbacks: List[Callback] = init_callbacks(
|
callbacks: List[pl.Callback] = init_callbacks(config=config)
|
||||||
project_config=project_config,
|
|
||||||
run_config=run_config,
|
|
||||||
use_wandb=use_wandb,
|
|
||||||
base_dir=BASE_DIR
|
|
||||||
)
|
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers ⚡
|
# Init PyTorch Lightning loggers ⚡
|
||||||
loggers: List[LightningLoggerBase] = init_loggers(
|
loggers: List[pl.loggers.LightningLoggerBase] = init_loggers(
|
||||||
project_config=project_config,
|
config=config,
|
||||||
run_config=run_config,
|
|
||||||
model=model,
|
model=model,
|
||||||
datamodule=datamodule,
|
datamodule=datamodule
|
||||||
use_wandb=use_wandb
|
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: Trainer = init_trainer(
|
trainer: pl.Trainer = init_trainer(
|
||||||
project_config=project_config,
|
trainer_config=config["trainer"],
|
||||||
run_config=run_config,
|
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
loggers=loggers
|
loggers=loggers
|
||||||
)
|
)
|
||||||
@@ -83,49 +74,11 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
|||||||
trainer.test()
|
trainer.test()
|
||||||
|
|
||||||
|
|
||||||
def load_config(path):
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path
|
def main(config: DictConfig) -> None:
|
||||||
with open(abs_path, "r") as ymlfile:
|
LOG.info(OmegaConf.to_yaml(config, resolve=True)) # print content of config
|
||||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
train(config)
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
def main(project_config_path: str, run_configs_path: str, run_config_name: str, use_wandb: bool):
|
|
||||||
# Load configs
|
|
||||||
project_config: dict = load_config(path=project_config_path)
|
|
||||||
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
|
||||||
|
|
||||||
print("EXECUTING RUN:", run_config_name)
|
|
||||||
# pprint.pprint(run_config, sort_dicts=False)
|
|
||||||
print()
|
|
||||||
|
|
||||||
# Train model
|
|
||||||
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
main()
|
||||||
parser.add_argument("--project_config_path",
|
|
||||||
type=str,
|
|
||||||
default="project_config.yaml",
|
|
||||||
help="Path to file containing your project configuration")
|
|
||||||
parser.add_argument("--run_configs_path",
|
|
||||||
type=str,
|
|
||||||
default="run_configs.yaml",
|
|
||||||
help="Path to file containing your run configurations")
|
|
||||||
parser.add_argument("--run_config_name",
|
|
||||||
type=str,
|
|
||||||
default="SIMPLE_CONFIG_EXAMPLE_MNIST",
|
|
||||||
help="Name of you configuration in run_configs.yaml")
|
|
||||||
parser.add_argument("--no_wandb",
|
|
||||||
dest='use_wandb',
|
|
||||||
action='store_false',
|
|
||||||
help="Whether to use Weights&Biases or not")
|
|
||||||
|
|
||||||
parser.set_defaults(use_wandb=True)
|
|
||||||
args = parser.parse_args()
|
|
||||||
|
|
||||||
main(project_config_path=args.project_config_path,
|
|
||||||
run_configs_path=args.run_configs_path,
|
|
||||||
run_config_name=args.run_config_name,
|
|
||||||
use_wandb=args.use_wandb)
|
|
||||||
@@ -4,6 +4,5 @@ torchaudio>=0.7.0
|
|||||||
pytorch-lightning>=1.0.8
|
pytorch-lightning>=1.0.8
|
||||||
hydra-core
|
hydra-core
|
||||||
wandb>=0.10.12
|
wandb>=0.10.12
|
||||||
PyYAML>=5.3.1
|
|
||||||
scikit-learn>=0.23.2
|
scikit-learn>=0.23.2
|
||||||
pandas>=1.1.5
|
pandas>=1.1.5
|
||||||
Reference in new issue
Block a user