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
|
||||
```yaml
|
||||
# set project and entity names in project/project_config.yaml
|
||||
# set project and entity names in project/config.yaml
|
||||
loggers:
|
||||
wandb:
|
||||
project: "your_project_name"
|
||||
|
||||
@@ -4,14 +4,16 @@ defaults:
|
||||
- trainer: default_trainer.yaml
|
||||
- model: simple_mnist_classifier.yaml
|
||||
- datamodule: mnist_datamodule.yaml
|
||||
- optimizer: adam.yaml
|
||||
- callbacks: default_callbacks.yaml
|
||||
- loggers: null
|
||||
|
||||
seeds:
|
||||
pytorch_seed: 12345
|
||||
|
||||
paths:
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
hydra:
|
||||
run:
|
||||
@@ -1,7 +1,6 @@
|
||||
# @package _group_
|
||||
|
||||
class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule"
|
||||
|
||||
hparams:
|
||||
args:
|
||||
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_
|
||||
|
||||
# to execute this experiment run:
|
||||
# python train.py +experiment=xxx2
|
||||
# python train.py +experiment=exp_example_advanced
|
||||
|
||||
defaults:
|
||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder
|
||||
- override /model: null # choose model from 'configs/model/' folder
|
||||
- override /datamodule: null # choose datamodule from 'configs/datamodule/' 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
|
||||
|
||||
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:
|
||||
args:
|
||||
@@ -18,16 +20,14 @@ trainer:
|
||||
gradient_clip_val: 0.5 # gradient clipping (helps with exploding gradient issues)
|
||||
accumulate_grad_batches: 2 # perform optimization step after accumulating gradient from 2 batches
|
||||
fast_dev_run: False # execute 1 training, 1 validation and 1 test epoch only
|
||||
limit_train_batches: 0.8 # train only on 80% of training data
|
||||
limit_val_batches: 1.0 # validate on 100% of validation data
|
||||
limit_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: "last.ckpt" # use this to resume training from checkpoint
|
||||
|
||||
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
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
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
|
||||
@@ -35,21 +35,23 @@ model:
|
||||
lin3_size: 128
|
||||
|
||||
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
|
||||
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
|
||||
|
||||
loggers:
|
||||
wandb:
|
||||
args: # you can add here additional loggers arguments specific for this experiment
|
||||
tags: ["uwu", "best_model"]
|
||||
notes: ""
|
||||
group: ""
|
||||
comet:
|
||||
args:
|
||||
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_
|
||||
|
||||
# train with all loggers at once
|
||||
# Train with all loggers at once
|
||||
defaults:
|
||||
- comet
|
||||
- csv_logger
|
||||
- neptune
|
||||
- tensorboard
|
||||
- wandb
|
||||
@@ -1,13 +1,8 @@
|
||||
# @package _group_
|
||||
|
||||
# Comet loggers config
|
||||
# Comet logger config
|
||||
comet:
|
||||
class: pytorch_lightning.loggers.CometLogger
|
||||
|
||||
args:
|
||||
api_key: ???
|
||||
project_name: "project_template_test"
|
||||
|
||||
extra_options:
|
||||
log_optimizer_name: True
|
||||
log_train_val_test_sizes: True
|
||||
@@ -1,9 +1,6 @@
|
||||
# @package _group_
|
||||
|
||||
# default loggers is just lightning CSVLogger which doesn't require any additional dependencies
|
||||
# Csv logger config
|
||||
csv_logger:
|
||||
class: pytorch_lightning.loggers.CSVLogger
|
||||
|
||||
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_
|
||||
|
||||
# Tensorboard loggers config
|
||||
# Tensorboard logger config
|
||||
tensorboard:
|
||||
class: pytorch_lightning.loggers.TensorboardLogger
|
||||
|
||||
args: {}
|
||||
|
||||
extra_options: {}
|
||||
@@ -1,16 +1,27 @@
|
||||
# @package _group_
|
||||
|
||||
# Weights&Biases loggers config
|
||||
# Weights&Biases logger config
|
||||
wandb:
|
||||
class: pytorch_lightning.loggers.WandbLogger
|
||||
|
||||
args:
|
||||
project: "project_template_test"
|
||||
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
|
||||
entity: "" # change to your username or name of your team on wandb
|
||||
offline: False # set True to store all logs only locally
|
||||
job_type: "train"
|
||||
save_dir: ${paths.logs_dir}
|
||||
|
||||
extra_options:
|
||||
log_gradients: False # set True to log gradient histograms (avoid this for very big models)
|
||||
log_optimizer_name: True
|
||||
log_train_val_test_sizes: True
|
||||
# some extra things which will be logged by the environment
|
||||
extra_logs:
|
||||
watch_model: True # make wandb watch model
|
||||
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_
|
||||
|
||||
class: "pytorch_modules.lightning_models.simple_mnist_classifier.LitModel"
|
||||
|
||||
hparams:
|
||||
args:
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
input_size: 784
|
||||
|
||||
Whitespace-only changes.
@@ -1 +1,6 @@
|
||||
# @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
|
||||
# (if the argument repeats in experiment config, then it will override the one set here)
|
||||
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
|
||||
num_sanity_val_steps: 3
|
||||
progress_bar_refresh_rate: 10
|
||||
weights_summary: "top"
|
||||
profiler: "simple" # use profiler to print execution time profiling after training ends
|
||||
max_epochs: 100
|
||||
progress_bar_refresh_rate: 10
|
||||
default_root_dir: ${paths.logs_dir}/lightning_logs
|
||||
@@ -165,7 +165,7 @@ class SaveCodeToWandbCallback(Callback):
|
||||
"template_utils/custom_callbacks.py",
|
||||
"template_utils/initializers.py",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
"config.yaml",
|
||||
"run_configs.yaml",
|
||||
]
|
||||
|
||||
|
||||
@@ -8,22 +8,22 @@ class MNISTDataModule(LightningDataModule):
|
||||
"""
|
||||
This is example of datamodule for MNIST dataset.
|
||||
|
||||
The path to datamodule should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
||||
The path to datamodule should be specified in your run config.
|
||||
The 'args' dict contains datamodule args specified in config.
|
||||
|
||||
To learn how to create datamodules visit:
|
||||
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__()
|
||||
|
||||
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.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||
self.num_workers = hparams.get("num_workers") or 1
|
||||
self.pin_memory = hparams.get("pin_memory") or False
|
||||
self.batch_size = args.get("batch_size") or 64
|
||||
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||
self.num_workers = args.get("num_workers") or 1
|
||||
self.pin_memory = args.get("pin_memory") or False
|
||||
|
||||
self.transforms = transforms.ToTensor()
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ from sklearn.metrics import accuracy_score
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
from template_utils.initializers import init_optimizer
|
||||
|
||||
# import custom architectures
|
||||
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
||||
@@ -9,10 +10,10 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
"""
|
||||
This is example of lightning model for MNIST digits classification.
|
||||
This is example of lightning model for MNIST classification.
|
||||
|
||||
The path to model should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
||||
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.
|
||||
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
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
def __init__(self, optimizer_config, **hparams):
|
||||
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):
|
||||
return self.model(x)
|
||||
@@ -77,4 +79,4 @@ class LitModel(pl.LightningModule):
|
||||
return loss
|
||||
|
||||
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
|
||||
|
||||
# template utils imports
|
||||
from pytorch_lightning import callbacks as lightning_callbacks
|
||||
from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks
|
||||
from pytorch_lightning.loggers import CSVLogger
|
||||
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
||||
import torch
|
||||
|
||||
|
||||
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):
|
||||
obj_path, obj_name = obj_path.rsplit('.', 1)
|
||||
module = importlib.import_module(obj_path)
|
||||
|
||||
assert hasattr(module, obj_name), \
|
||||
f'Object `{obj_name}` cannot be loaded from `{obj_path}`.'
|
||||
|
||||
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_hparams = model_config["hparams"]
|
||||
|
||||
model_args = model_config["args"]
|
||||
LitModel = load_object(model_class)
|
||||
assert issubclass(LitModel, pl.LightningModule), \
|
||||
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
||||
|
||||
return LitModel(hparams=model_hparams)
|
||||
return LitModel(optimizer_config, **model_args)
|
||||
|
||||
|
||||
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_hparams = datamodule_config["hparams"]
|
||||
|
||||
datamodule_args = datamodule_config["args"]
|
||||
DataModule = load_object(datamodule_class)
|
||||
|
||||
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
||||
|
||||
datamodule = DataModule(data_dir=data_dir, hparams=datamodule_hparams)
|
||||
datamodule = DataModule(data_dir=data_dir, **datamodule_args)
|
||||
datamodule.prepare_data()
|
||||
datamodule.setup()
|
||||
|
||||
return datamodule
|
||||
|
||||
|
||||
def init_trainer(project_config: dict,
|
||||
run_config: dict,
|
||||
def init_optimizer(optimizer_config, model):
|
||||
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],
|
||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.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(
|
||||
# whether to use gpu and how many
|
||||
gpus=project_config["num_of_gpus"],
|
||||
|
||||
# experiment logging
|
||||
logger=loggers,
|
||||
|
||||
# useful lightning_callbacks
|
||||
callbacks=callbacks,
|
||||
|
||||
# resume training from checkpoint if it was set in the run config
|
||||
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"]
|
||||
logger=loggers,
|
||||
**trainer_config["args"]
|
||||
)
|
||||
|
||||
return trainer
|
||||
|
||||
|
||||
def init_callbacks(project_config: dict,
|
||||
run_config: dict,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.Callback]:
|
||||
def init_callbacks(config: dict) -> List[pl.Callback]:
|
||||
"""
|
||||
Initialize default lightning_callbacks and lightning_callbacks specified in run config.
|
||||
Initialize callbacks specified in config.
|
||||
"""
|
||||
|
||||
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_config = config.get("callbacks", None)
|
||||
callbacks = []
|
||||
|
||||
all_callback_configs = {}
|
||||
for callback_config in default_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]
|
||||
if not callbacks_config:
|
||||
return callbacks
|
||||
|
||||
for callback_config in all_callback_configs:
|
||||
found = False
|
||||
for namespace in namespaces:
|
||||
if hasattr(namespace, callback_config):
|
||||
callback_class = getattr(namespace, callback_config)
|
||||
callbacks.append(callback_class(**all_callback_configs[callback_config]))
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
raise ModuleNotFoundError(f"Callback '{callback_config}' not found.")
|
||||
|
||||
if use_wandb:
|
||||
callbacks.append(
|
||||
wandb_callbacks.SaveCodeToWandbCallback(
|
||||
base_dir=base_dir,
|
||||
wandb_save_dir=project_config["logs_dir"],
|
||||
run_config=run_config
|
||||
)
|
||||
)
|
||||
for callback_name, callback_conf in callbacks_config.items():
|
||||
callback_class = callback_conf.get("class", None)
|
||||
if callback_class:
|
||||
callback_obj = init_object(callback_class, callback_conf.get("args", {}))
|
||||
callbacks.append(callback_obj)
|
||||
|
||||
return callbacks
|
||||
|
||||
|
||||
def init_loggers(project_config: dict,
|
||||
run_config: dict,
|
||||
def init_loggers(config: dict,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
|
||||
datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]:
|
||||
"""
|
||||
Initialize loggers.
|
||||
Initialize loggers specified in config.
|
||||
"""
|
||||
loggers_config = config.get("loggers", None)
|
||||
loggers = []
|
||||
if use_wandb:
|
||||
wandb_logger = init_wandb_logger(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
model=model,
|
||||
datamodule=datamodule
|
||||
)
|
||||
if wandb_logger:
|
||||
loggers.append(wandb_logger)
|
||||
|
||||
if not loggers_config:
|
||||
return loggers
|
||||
|
||||
for logger_name, logger_conf in loggers_config.items():
|
||||
logger_class = loggers_config.get("class", None)
|
||||
if logger_class:
|
||||
if logger_class == "pytorch_lightning.loggers.WandbLogger":
|
||||
logger_obj = init_wandb(config, model, datamodule)
|
||||
else:
|
||||
logger_obj = init_object(logger_class, logger_conf.get("args", {}))
|
||||
loggers.append(logger_obj)
|
||||
|
||||
return loggers
|
||||
|
||||
|
||||
def init_wandb_logger(project_config: dict,
|
||||
run_config: dict,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
||||
def init_wandb(config: dict,
|
||||
model: pl.LightningModule,
|
||||
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
|
||||
# instead of auto-creating a new run
|
||||
os.environ["WANDB_RESUME"] = "must"
|
||||
|
||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
|
||||
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
||||
wandb_config = config["loggers"]["wandb"]
|
||||
wandb_logger = WandbLogger(**wandb_config["args"])
|
||||
|
||||
wandb_logger = WandbLogger(
|
||||
project=project_config["loggers"]["wandb"]["project"],
|
||||
entity=project_config["loggers"]["wandb"]["entity"],
|
||||
log_model=project_config["loggers"]["wandb"]["log_model"],
|
||||
offline=project_config["loggers"]["wandb"]["offline"],
|
||||
|
||||
group=run_config.get("wandb", {}).get("group", None),
|
||||
job_type=run_config.get("wandb", {}).get("job_type", "train"),
|
||||
tags=run_config.get("wandb", {}).get("tags", []),
|
||||
notes=run_config.get("wandb", {}).get("notes", ""),
|
||||
|
||||
# resume run only if ckpt was set in the run config
|
||||
id=wandb_run_id
|
||||
if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None
|
||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
||||
else None,
|
||||
|
||||
save_dir=project_config["logs_dir"],
|
||||
save_code=False
|
||||
)
|
||||
|
||||
if not os.path.exists(project_config["logs_dir"]):
|
||||
os.makedirs(project_config["logs_dir"])
|
||||
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
||||
if "save_dir" in wandb_config["args"] and not os.path.exists(wandb_config["args"]["save_dir"]):
|
||||
os.makedirs(wandb_config["args"]["save_dir"])
|
||||
|
||||
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')
|
||||
else:
|
||||
wandb_logger.watch(model.model, log=None)
|
||||
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
||||
else:
|
||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
||||
if wandb_config["extra_options"]["log_gradients"]:
|
||||
wandb_logger.watch(model, log='gradients')
|
||||
else:
|
||||
wandb_logger.watch(model, log=None)
|
||||
|
||||
wandb_logger.log_hyperparams({
|
||||
"optimizer": model.configure_optimizers().__class__.__name__,
|
||||
"train_size": len(datamodule.data_train)
|
||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||
"val_size": len(datamodule.data_val)
|
||||
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
||||
"test_size": len(datamodule.data_test)
|
||||
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
||||
})
|
||||
wandb_logger.log_hyperparams({"num_of_gpus": project_config["num_of_gpus"]})
|
||||
wandb_logger.log_hyperparams(run_config["trainer"]["args"])
|
||||
wandb_logger.log_hyperparams(run_config["model"]["hparams"])
|
||||
wandb_logger.log_hyperparams(run_config["model"]["load_from"])
|
||||
wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"])
|
||||
wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"])
|
||||
if wandb_config["extra_options"]["log_train_val_test_sizes"]:
|
||||
wandb_logger.log_hyperparams({
|
||||
"train_size": len(datamodule.data_train)
|
||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||
"val_size": len(datamodule.data_val)
|
||||
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
||||
"test_size": len(datamodule.data_test)
|
||||
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
||||
})
|
||||
|
||||
if wandb_config["extra_options"]["log_model_args"]:
|
||||
wandb_logger.log_hyperparams(config["model"]["args"])
|
||||
if wandb_config["extra_options"]["log_datamodule_args"]:
|
||||
wandb_logger.log_hyperparams(config["datamodule"]["args"])
|
||||
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
|
||||
|
||||
|
||||
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!
|
||||
from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
|
||||
|
||||
# ckpt can be a url!
|
||||
|
||||
|
||||
def predict():
|
||||
"""
|
||||
|
||||
+30
-77
@@ -1,17 +1,20 @@
|
||||
# pytorch lightning imports
|
||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
|
||||
# hydra imports
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
import hydra.conf.hydra.output
|
||||
|
||||
# normal imports
|
||||
from argparse import ArgumentParser
|
||||
from typing import List
|
||||
import yaml
|
||||
import logging
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
from template_utils.initializers import (
|
||||
normalize_config_paths,
|
||||
format_config_paths,
|
||||
init_model,
|
||||
init_datamodule,
|
||||
init_callbacks,
|
||||
@@ -19,56 +22,44 @@ from template_utils.initializers import (
|
||||
init_trainer
|
||||
)
|
||||
|
||||
|
||||
# Everything will be loaded relatively to placement of 'train.py' 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
|
||||
if "seed" in run_config:
|
||||
torch.manual_seed(run_config["seed"])
|
||||
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||
torch.manual_seed(config["seeds"]["pytorch_seed"])
|
||||
|
||||
# Covert paths to absolute and normalize them
|
||||
project_config, run_config = normalize_config_paths(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
config = format_config_paths(config=config, base_dir=BASE_DIR)
|
||||
|
||||
# Init PyTorch Lightning model ⚡
|
||||
model: LightningModule = init_model(
|
||||
model_config=run_config["model"]
|
||||
model: pl.LightningModule = init_model(
|
||||
model_config=config["model"],
|
||||
optimizer_config=config["optimizer"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning datamodule ⚡
|
||||
datamodule: LightningDataModule = init_datamodule(
|
||||
datamodule_config=run_config["datamodule"],
|
||||
data_dir=project_config["data_dir"]
|
||||
datamodule: pl.LightningDataModule = init_datamodule(
|
||||
datamodule_config=config["datamodule"],
|
||||
data_dir=config["paths"]["data_dir"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning lightning_callbacks ⚡
|
||||
callbacks: List[Callback] = init_callbacks(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
use_wandb=use_wandb,
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
# Init PyTorch Lightning callbacks ⚡
|
||||
callbacks: List[pl.Callback] = init_callbacks(config=config)
|
||||
|
||||
# Init PyTorch Lightning loggers ⚡
|
||||
loggers: List[LightningLoggerBase] = init_loggers(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
loggers: List[pl.loggers.LightningLoggerBase] = init_loggers(
|
||||
config=config,
|
||||
model=model,
|
||||
datamodule=datamodule,
|
||||
use_wandb=use_wandb
|
||||
datamodule=datamodule
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
trainer: Trainer = init_trainer(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
trainer: pl.Trainer = init_trainer(
|
||||
trainer_config=config["trainer"],
|
||||
callbacks=callbacks,
|
||||
loggers=loggers
|
||||
)
|
||||
@@ -83,49 +74,11 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
trainer.test()
|
||||
|
||||
|
||||
def load_config(path):
|
||||
abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path
|
||||
with open(abs_path, "r") as ymlfile:
|
||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||
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)
|
||||
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||
def main(config: DictConfig) -> None:
|
||||
LOG.info(OmegaConf.to_yaml(config, resolve=True)) # print content of config
|
||||
train(config)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
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)
|
||||
main()
|
||||
@@ -4,6 +4,5 @@ torchaudio>=0.7.0
|
||||
pytorch-lightning>=1.0.8
|
||||
hydra-core
|
||||
wandb>=0.10.12
|
||||
PyYAML>=5.3.1
|
||||
scikit-learn>=0.23.2
|
||||
pandas>=1.1.5
|
||||
Reference in new issue
Block a user