fix bugs
This commit is contained in:
1 parent
0030c94b17
commit
66097c4bf3
11 files changed
+160
-198
No files matched your search
@@ -0,0 +1,5 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
- default_callbacks.yaml
|
||||||
|
|
||||||
@@ -9,12 +9,15 @@ defaults:
|
|||||||
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
|
|
||||||
|
|
||||||
# path to working directory (the directory that `train.py` was executed from in command line)
|
# path to working directory (the directory that `train.py` was executed from in command line)
|
||||||
work_dir: ${hydra:runtime.cwd}
|
work_dir: ${hydra:runtime.cwd}
|
||||||
|
|
||||||
|
|
||||||
# path to folder with data
|
# path to folder with data
|
||||||
data_dir: ${work_dir}/data/
|
data_dir: ${work_dir}/data/
|
||||||
|
|
||||||
|
|
||||||
# hydra output paths
|
# hydra output paths
|
||||||
hydra:
|
hydra:
|
||||||
run:
|
run:
|
||||||
@@ -23,13 +26,17 @@ hydra:
|
|||||||
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
|
|
||||||
|
|
||||||
# extra things that are logged by all loggers as hyperparameters, before training starts
|
# extra things that are logged by all loggers as hyperparameters, before training starts
|
||||||
extra_logs:
|
extra_logs:
|
||||||
log_train_val_test_sizes: True,
|
log_seeds: True
|
||||||
log_trainer_args: False,
|
|
||||||
log_model_args: True,
|
log_trainer_args: False
|
||||||
log_datamodule_args: True,
|
log_datamodule_args: True
|
||||||
log_optimizer_args: True,
|
|
||||||
log_model_class_name: True,
|
log_model_class: True
|
||||||
log_datamodule_class_name: True,
|
log_optimizer_class: True
|
||||||
log_optimizer_class_name: True
|
log_datamodule_class: True
|
||||||
|
|
||||||
|
log_train_val_test_sizes: True
|
||||||
|
log_model_architecture_class_name: True
|
||||||
@@ -4,3 +4,5 @@ class: "pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule"
|
|||||||
args:
|
args:
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
|
num_workers: 1
|
||||||
|
pin_memory: False
|
||||||
@@ -2,10 +2,10 @@
|
|||||||
|
|
||||||
# Weights&Biases logger config
|
# Weights&Biases logger config
|
||||||
wandb:
|
wandb:
|
||||||
class: pytorch_lightning.logger.WandbLogger
|
class: pytorch_lightning.loggers.wandb.WandbLogger
|
||||||
args:
|
args:
|
||||||
project: "env_tests"
|
project: "env_tests"
|
||||||
entity: "lodz" # set to name of your wandb team or just remove
|
# entity: "team_name" # set to name of your wandb team or just remove it
|
||||||
offline: False # set True to store all logs only locally
|
offline: False # set True to store all logs only locally
|
||||||
job_type: "train"
|
job_type: "train"
|
||||||
save_dir: "."
|
save_dir: "."
|
||||||
@@ -3,8 +3,8 @@
|
|||||||
# default args passed to Lightning Trainer on every experiment
|
# default args passed to Lightning Trainer on every experiment
|
||||||
# they can be combined or overwritten with args set in experiment config
|
# they can be combined or overwritten with args set in experiment config
|
||||||
args:
|
args:
|
||||||
gpus: -1 # set -1 to train on all GPUs available, 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
|
progress_bar_refresh_rate: 10
|
||||||
weights_summary: null # null in yaml represents python None value
|
weights_summary: null # null in yaml represents python None value
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import wandb
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
class SaveOnnxModelToWandbCallback(Callback):
|
class SaveOnnxModelToWandb(Callback):
|
||||||
"""
|
"""
|
||||||
Save model in .onnx format and upload to wandb.
|
Save model in .onnx format and upload to wandb.
|
||||||
Might crash since not all lightning_models are compatible with onnx.
|
Might crash since not all lightning_models are compatible with onnx.
|
||||||
@@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback):
|
|||||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||||
|
|
||||||
|
|
||||||
class ImagePredictionWandbLoggerCallback(Callback):
|
class SaveImagePredictionsToWandb(Callback):
|
||||||
"""
|
"""
|
||||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||||
"""
|
"""
|
||||||
@@ -58,7 +58,7 @@ class ImagePredictionWandbLoggerCallback(Callback):
|
|||||||
]}, commit=False)
|
]}, commit=False)
|
||||||
|
|
||||||
|
|
||||||
class MetricsHeatmapWandbLoggerCallback(Callback):
|
class SaveMetricsHeatmapToWandb(Callback):
|
||||||
"""
|
"""
|
||||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
@@ -107,7 +107,7 @@ class MetricsHeatmapWandbLoggerCallback(Callback):
|
|||||||
self.targets = []
|
self.targets = []
|
||||||
|
|
||||||
|
|
||||||
class ConfusionMatrixWandbLoggerCallback(Callback):
|
class SaveConfusionMatrixToWandb(Callback):
|
||||||
"""
|
"""
|
||||||
Generate Confusion Matrix.
|
Generate Confusion Matrix.
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
@@ -152,7 +152,7 @@ class ConfusionMatrixWandbLoggerCallback(Callback):
|
|||||||
self.targets = []
|
self.targets = []
|
||||||
|
|
||||||
|
|
||||||
class SaveCodeToWandbCallback(Callback):
|
class SaveCodeToWandb(Callback):
|
||||||
"""
|
"""
|
||||||
Upload specified code files to wandb at the beginning of the run.
|
Upload specified code files to wandb at the beginning of the run.
|
||||||
"""
|
"""
|
||||||
@@ -175,13 +175,8 @@ class SaveCodeToWandbCallback(Callback):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
class SaveBestMetricScores(Callback):
|
class SaveBestMetricScoresToWandb(Callback):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.train_loss_list = []
|
|
||||||
self.train_acc_list = []
|
|
||||||
self.train_loss_best = None
|
|
||||||
self.train_acc_best = None
|
|
||||||
|
|
||||||
self.val_loss_list = []
|
self.val_loss_list = []
|
||||||
self.val_acc_list = []
|
self.val_acc_list = []
|
||||||
self.val_loss_best = None
|
self.val_loss_best = None
|
||||||
@@ -190,8 +185,6 @@ class SaveBestMetricScores(Callback):
|
|||||||
self.ready = False
|
self.ready = False
|
||||||
|
|
||||||
def clear_lists(self):
|
def clear_lists(self):
|
||||||
self.train_loss_list.clear()
|
|
||||||
self.train_acc_list.clear()
|
|
||||||
self.val_loss_list.clear()
|
self.val_loss_list.clear()
|
||||||
self.val_acc_list.clear()
|
self.val_acc_list.clear()
|
||||||
|
|
||||||
@@ -206,25 +199,10 @@ class SaveBestMetricScores(Callback):
|
|||||||
self.val_loss_list.append(loss)
|
self.val_loss_list.append(loss)
|
||||||
self.val_acc_list.append(acc)
|
self.val_acc_list.append(acc)
|
||||||
|
|
||||||
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
|
||||||
"""Gather data from single batch."""
|
|
||||||
if self.ready:
|
|
||||||
loss, acc, preds, targets = outputs
|
|
||||||
self.train_loss_list.append(loss)
|
|
||||||
self.train_acc_list.append(acc)
|
|
||||||
|
|
||||||
def on_epoch_end(self, trainer, pl_module):
|
def on_epoch_end(self, trainer, pl_module):
|
||||||
if self.ready:
|
if self.ready:
|
||||||
for logger in trainer.logger.experiment:
|
for logger in trainer.logger.experiment:
|
||||||
# currently works only for wandb
|
|
||||||
if isinstance(logger, wandb_run):
|
if isinstance(logger, wandb_run):
|
||||||
loss = sum(self.train_loss_list) / len(self.train_loss_list)
|
|
||||||
acc = sum(self.train_acc_list) / len(self.train_acc_list)
|
|
||||||
self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best
|
|
||||||
self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best
|
|
||||||
logger.log({"train_loss_best": self.train_loss_best}, commit=False)
|
|
||||||
logger.log({"train_acc_best": self.train_acc_best}, commit=False)
|
|
||||||
|
|
||||||
loss = sum(self.val_loss_list) / len(self.val_loss_list)
|
loss = sum(self.val_loss_list) / len(self.val_loss_list)
|
||||||
acc = sum(self.val_acc_list) / len(self.val_acc_list)
|
acc = sum(self.val_acc_list) / len(self.val_acc_list)
|
||||||
self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best
|
self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best
|
||||||
|
|||||||
@@ -7,10 +7,6 @@ from torchvision.datasets import MNIST
|
|||||||
class MNISTDataModule(LightningDataModule):
|
class MNISTDataModule(LightningDataModule):
|
||||||
"""
|
"""
|
||||||
This is example of datamodule for MNIST dataset.
|
This is example of datamodule for MNIST dataset.
|
||||||
|
|
||||||
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:
|
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
|
||||||
"""
|
"""
|
||||||
@@ -20,10 +16,10 @@ class MNISTDataModule(LightningDataModule):
|
|||||||
|
|
||||||
self.data_dir = data_dir # data_dir is specified in config.yaml
|
self.data_dir = data_dir # data_dir is specified in config.yaml
|
||||||
|
|
||||||
self.batch_size = args.get("batch_size") or 64
|
self.batch_size = args["batch_size"]
|
||||||
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
self.train_val_test_split = args["train_val_test_split"]
|
||||||
self.num_workers = args.get("num_workers") or 1
|
self.num_workers = args["num_workers"]
|
||||||
self.pin_memory = args.get("pin_memory") or False
|
self.pin_memory = args["pin_memory"]
|
||||||
|
|
||||||
self.transforms = transforms.ToTensor()
|
self.transforms = transforms.ToTensor()
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +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
|
from template_utils.initializers import load_class
|
||||||
|
|
||||||
# import custom architectures
|
# import custom architectures
|
||||||
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
||||||
@@ -11,23 +11,19 @@ from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
|||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
"""
|
"""
|
||||||
This is example of lightning model for MNIST 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 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.
|
||||||
|
|
||||||
To learn how to create lightning models visit:
|
To learn how to create lightning models visit:
|
||||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, optimizer_config, **hparams):
|
def __init__(self, model_config, optimizer_config):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
self.optimizer_config = optimizer_config
|
hparams = {**model_config["args"], **optimizer_config["args"]}
|
||||||
self.save_hyperparameters(hparams)
|
self.save_hyperparameters(hparams)
|
||||||
|
self.optimizer_config = optimizer_config
|
||||||
|
|
||||||
self.model = SimpleMNISTClassifier(hparams=hparams)
|
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
@@ -41,11 +37,10 @@ class LitModel(pl.LightningModule):
|
|||||||
# training metrics
|
# training metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback
|
return loss
|
||||||
return loss, acc, preds, y
|
|
||||||
|
|
||||||
# logic for a single validation step
|
# logic for a single validation step
|
||||||
def validation_step(self, batch, batch_idx):
|
def validation_step(self, batch, batch_idx):
|
||||||
@@ -56,10 +51,11 @@ class LitModel(pl.LightningModule):
|
|||||||
# validation metrics
|
# validation metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
return loss, acc, preds, y
|
# we can return here anything and then read it in some callback
|
||||||
|
return loss, {"preds": preds, "acc": acc, "y": y}
|
||||||
|
|
||||||
# logic for a single testing step
|
# logic for a single testing step
|
||||||
def test_step(self, batch, batch_idx):
|
def test_step(self, batch, batch_idx):
|
||||||
@@ -70,10 +66,11 @@ class LitModel(pl.LightningModule):
|
|||||||
# test metrics
|
# test metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = accuracy_score(preds.cpu(), y.cpu())
|
||||||
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
self.log('test_acc', acc, on_step=False, on_epoch=True)
|
||||||
|
|
||||||
return loss
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
def configure_optimizers(self):
|
||||||
return init_optimizer(optimizer_config=self.optimizer_config, model=self)
|
Optimizer = load_class(self.optimizer_config["class"])
|
||||||
|
return Optimizer(self.parameters(), **self.optimizer_config["args"])
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
|
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
|
||||||
from pytorch_lightning.callbacks.lr_monitor import LearningRateMonitor
|
# hydra imports
|
||||||
import torch
|
from omegaconf import DictConfig, OmegaConf
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List, Tuple
|
from typing import List
|
||||||
import importlib
|
import importlib
|
||||||
import os
|
import logging
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def load_class(class_path) -> type:
|
def load_class(class_path) -> type:
|
||||||
@@ -27,11 +30,10 @@ def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule
|
|||||||
Load LightningModule from path specified in config.
|
Load LightningModule from path specified in config.
|
||||||
"""
|
"""
|
||||||
model_class = model_config["class"]
|
model_class = model_config["class"]
|
||||||
model_args = model_config["args"]
|
|
||||||
LitModel = load_class(model_class)
|
LitModel = load_class(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(model_config=model_config, optimizer_config=optimizer_config)
|
||||||
|
|
||||||
|
|
||||||
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||||
@@ -49,15 +51,6 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM
|
|||||||
return datamodule
|
return datamodule
|
||||||
|
|
||||||
|
|
||||||
def init_optimizer(optimizer_config, model):
|
|
||||||
optimizer_class = optimizer_config["class"]
|
|
||||||
optimizer_args = optimizer_config["args"]
|
|
||||||
Optim = load_class(optimizer_class)
|
|
||||||
assert issubclass(Optim, torch.optim.Optimizer), \
|
|
||||||
f"Specified optimizer class `{optimizer_class}` is not subclass of `torch.optim.Optimizer`."
|
|
||||||
return Optim(model.parameters(), **optimizer_args)
|
|
||||||
|
|
||||||
|
|
||||||
def init_trainer(trainer_config: dict,
|
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:
|
||||||
@@ -72,16 +65,11 @@ def init_trainer(trainer_config: dict,
|
|||||||
return trainer
|
return trainer
|
||||||
|
|
||||||
|
|
||||||
def init_callbacks(config: dict) -> List[pl.Callback]:
|
def init_callbacks(callbacks_config: dict) -> List[pl.Callback]:
|
||||||
"""
|
"""
|
||||||
Initialize callbacks specified in config.
|
Initialize callbacks specified in config.
|
||||||
"""
|
"""
|
||||||
callbacks_config = config.get("callbacks", None)
|
|
||||||
callbacks = []
|
callbacks = []
|
||||||
|
|
||||||
if not callbacks_config:
|
|
||||||
return callbacks
|
|
||||||
|
|
||||||
for callback_name, callback_conf in callbacks_config.items():
|
for callback_name, callback_conf in callbacks_config.items():
|
||||||
class_path = callback_conf.get("class", None)
|
class_path = callback_conf.get("class", None)
|
||||||
if class_path:
|
if class_path:
|
||||||
@@ -89,100 +77,108 @@ def init_callbacks(config: dict) -> List[pl.Callback]:
|
|||||||
assert issubclass(callback_obj.__class__, pl.Callback), \
|
assert issubclass(callback_obj.__class__, pl.Callback), \
|
||||||
f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`."
|
f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`."
|
||||||
callbacks.append(callback_obj)
|
callbacks.append(callback_obj)
|
||||||
|
|
||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
|
|
||||||
def init_loggers(config: dict,
|
def init_loggers(loggers_config: dict) -> List[pl.loggers.LightningLoggerBase]:
|
||||||
model: pl.LightningModule,
|
|
||||||
datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]:
|
|
||||||
"""
|
"""
|
||||||
Initialize logger specified in config.
|
Initialize loggers specified in config.
|
||||||
"""
|
"""
|
||||||
loggers_config = config.get("logger", None)
|
|
||||||
loggers = []
|
loggers = []
|
||||||
|
|
||||||
if not loggers_config:
|
|
||||||
return loggers
|
|
||||||
|
|
||||||
for logger_name, logger_conf in loggers_config.items():
|
for logger_name, logger_conf in loggers_config.items():
|
||||||
class_path = logger_conf.get("class", None)
|
class_path = logger_conf.get("class", None)
|
||||||
if class_path:
|
if class_path:
|
||||||
if class_path == "pytorch_lightning.logger.WandbLogger":
|
|
||||||
logger_obj = init_wandb(config, model, datamodule)
|
|
||||||
else:
|
|
||||||
logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {}))
|
logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {}))
|
||||||
assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \
|
assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \
|
||||||
f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`."
|
f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`."
|
||||||
loggers.append(logger_obj)
|
loggers.append(logger_obj)
|
||||||
|
|
||||||
return loggers
|
return loggers
|
||||||
|
|
||||||
|
|
||||||
def init_wandb(config: dict,
|
def get_wandb_logger(loggers: List[pl.loggers.LightningLoggerBase]) -> WandbLogger:
|
||||||
model: pl.LightningModule,
|
for logger in loggers:
|
||||||
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
if isinstance(logger, WandbLogger):
|
||||||
"""
|
return logger
|
||||||
Initialize Weights&Biases logger.
|
|
||||||
"""
|
|
||||||
# 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"
|
|
||||||
|
|
||||||
wandb_config = config["logger"]["wandb"]
|
|
||||||
wandb_logger = WandbLogger(**wandb_config["args"])
|
|
||||||
|
|
||||||
# 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"])
|
|
||||||
|
|
||||||
|
def make_wandb_watch_model(loggers: List[pl.loggers.LightningLoggerBase], model: pl.LightningModule):
|
||||||
|
wandb_logger = get_wandb_logger(loggers)
|
||||||
|
if wandb_logger:
|
||||||
if hasattr(model, 'model'):
|
if hasattr(model, 'model'):
|
||||||
if wandb_config["extra_logs"]["log_gradients"]:
|
|
||||||
wandb_logger.watch(model.model, log='gradients')
|
|
||||||
else:
|
|
||||||
wandb_logger.watch(model.model, log=None)
|
wandb_logger.watch(model.model, log=None)
|
||||||
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
|
||||||
else:
|
|
||||||
if wandb_config["extra_logs"]["log_gradients"]:
|
|
||||||
wandb_logger.watch(model, log='gradients')
|
|
||||||
else:
|
else:
|
||||||
wandb_logger.watch(model, log=None)
|
wandb_logger.watch(model, log=None)
|
||||||
|
|
||||||
if wandb_config["extra_logs"]["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_logs"]["log_model_args"]:
|
def log_hparams(loggers: List[pl.loggers.LightningLoggerBase], hparams: dict):
|
||||||
wandb_logger.log_hyperparams(config["model"]["args"])
|
for logger in loggers:
|
||||||
if wandb_config["extra_logs"]["log_datamodule_args"]:
|
logger.log_hyperparams(hparams)
|
||||||
wandb_logger.log_hyperparams(config["datamodule"]["args"])
|
|
||||||
if wandb_config["extra_logs"]["log_optimizer_args"]:
|
|
||||||
wandb_logger.log_hyperparams(config["optimizer"]["args"])
|
|
||||||
if wandb_config["extra_logs"]["log_trainer_args"]:
|
|
||||||
wandb_logger.log_hyperparams(config["trainer"]["args"])
|
|
||||||
|
|
||||||
if wandb_config["extra_logs"]["log_model_class_name"]:
|
|
||||||
wandb_logger.log_hyperparams({"model_class": config["model"]["class"]})
|
|
||||||
if wandb_config["extra_logs"]["log_datamodule_class_name"]:
|
|
||||||
wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]})
|
|
||||||
if wandb_config["extra_logs"]["log_optimizer_class_name"]:
|
|
||||||
wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]})
|
|
||||||
|
|
||||||
return wandb_logger
|
|
||||||
|
|
||||||
|
|
||||||
def log_extra_hparams(config: dict,
|
def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
|
||||||
|
config: dict,
|
||||||
model: pl.LightningModule,
|
model: pl.LightningModule,
|
||||||
datamodule: pl.LightningDataModule,
|
datamodule: pl.LightningDataModule,
|
||||||
loggers: List[pl.loggers.LightningLoggerBase],
|
|
||||||
callbacks: List[pl.callbacks.Callback]):
|
callbacks: List[pl.callbacks.Callback]):
|
||||||
pass
|
if "extra_logs" not in config:
|
||||||
|
return
|
||||||
|
|
||||||
|
extra_logs = config["extra_logs"]
|
||||||
|
|
||||||
|
if "log_seeds" in extra_logs and extra_logs["log_seeds"] and "seeds" in config:
|
||||||
|
log_hparams(loggers, config["seeds"])
|
||||||
|
|
||||||
|
if "log_trainer_args" in extra_logs and extra_logs["log_trainer_args"]:
|
||||||
|
log_hparams(loggers, config["trainer"]["args"])
|
||||||
|
if "log_model_args" in extra_logs and extra_logs["log_model_args"]:
|
||||||
|
log_hparams(loggers, config["model"]["args"])
|
||||||
|
if "log_optimizer_args" in extra_logs and extra_logs["log_optimizer_args"]:
|
||||||
|
log_hparams(loggers, config["optimizer"]["args"])
|
||||||
|
if "log_datamodule_args" in extra_logs and extra_logs["log_datamodule_args"]:
|
||||||
|
log_hparams(loggers, config["datamodule"]["args"])
|
||||||
|
|
||||||
|
if "log_model_class" in extra_logs and extra_logs["log_model_class"]:
|
||||||
|
log_hparams(loggers, {"model_class": config["model"]["class"]})
|
||||||
|
if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]:
|
||||||
|
log_hparams(loggers, {"optimizer_class": config["optimizer"]["class"]})
|
||||||
|
if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]:
|
||||||
|
log_hparams(loggers, {"datamodule_class": config["datamodule"]["class"]})
|
||||||
|
|
||||||
|
if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]:
|
||||||
|
hparams = {}
|
||||||
|
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None:
|
||||||
|
hparams["train_size"] = len(datamodule.data_train)
|
||||||
|
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None:
|
||||||
|
hparams["val_size"] = len(datamodule.data_val)
|
||||||
|
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None:
|
||||||
|
hparams["test_size"] = len(datamodule.data_test)
|
||||||
|
log_hparams(loggers, hparams)
|
||||||
|
|
||||||
|
if "log_model_architecture_class_name" in extra_logs and extra_logs["log_model_architecture_class_name"]:
|
||||||
|
if hasattr(model, "model"):
|
||||||
|
log_hparams(loggers, {"model_architecture_class_name": model.model.__class__.__name__})
|
||||||
|
|
||||||
|
|
||||||
|
def show_init_info(model, datamodule, callbacks, loggers):
|
||||||
|
message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Datamodule initialised:" + "\n" + datamodule.__module__ + "." + datamodule.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Callbacks initialised:" + "\n"
|
||||||
|
for cb in callbacks:
|
||||||
|
message += cb.__module__ + "." + cb.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Loggers initialised:" + "\n"
|
||||||
|
for logger in loggers:
|
||||||
|
message += logger.__module__ + "." + logger.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
|
||||||
|
def show_config(config: DictConfig):
|
||||||
|
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
|
||||||
|
|
||||||
|
|
||||||
def validate_config(config: dict):
|
def validate_config(config: dict):
|
||||||
|
|||||||
+24
-43
@@ -5,84 +5,65 @@ import torch
|
|||||||
|
|
||||||
# hydra imports
|
# hydra imports
|
||||||
from omegaconf import DictConfig, OmegaConf
|
from omegaconf import DictConfig, OmegaConf
|
||||||
import hydra.conf.hydra.output
|
|
||||||
import hydra
|
import hydra
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List
|
from typing import List
|
||||||
import logging
|
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
from template_utils.initializers import (
|
import template_utils.initializers as utils
|
||||||
validate_config,
|
|
||||||
init_model,
|
|
||||||
init_datamodule,
|
|
||||||
init_callbacks,
|
|
||||||
init_loggers,
|
|
||||||
init_trainer
|
|
||||||
)
|
|
||||||
|
|
||||||
log = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train(config):
|
||||||
validate_config(config)
|
utils.validate_config(config=config)
|
||||||
|
|
||||||
# Set global PyTorch seed
|
# Set global PyTorch seed
|
||||||
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||||
torch.manual_seed(config["seeds"]["pytorch_seed"])
|
torch.manual_seed(seed=config["seeds"]["pytorch_seed"])
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
model: pl.LightningModule = init_model(
|
model: pl.LightningModule = utils.init_model(
|
||||||
model_config=config["model"],
|
model_config=config["model"],
|
||||||
optimizer_config=config["optimizer"]
|
optimizer_config=config["optimizer"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: pl.LightningDataModule = init_datamodule(
|
datamodule: pl.LightningDataModule = utils.init_datamodule(
|
||||||
datamodule_config=config["datamodule"],
|
datamodule_config=config["datamodule"],
|
||||||
data_dir=config["data_dir"]
|
data_dir=config["data_dir"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning callbacks ⚡
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
callbacks: List[pl.Callback] = init_callbacks(config=config)
|
callbacks = []
|
||||||
|
if "callbacks" in config:
|
||||||
|
callbacks: List[pl.Callback] = utils.init_callbacks(callbacks_config=config["callbacks"])
|
||||||
|
|
||||||
# Init PyTorch Lightning logger ⚡
|
# Init PyTorch Lightning loggers ⚡
|
||||||
loggers: List[pl.loggers.LightningLoggerBase] = init_loggers(
|
loggers = []
|
||||||
|
if "logger" in config:
|
||||||
|
loggers: List[pl.loggers.LightningLoggerBase] = utils.init_loggers(loggers_config=config["logger"])
|
||||||
|
|
||||||
|
# If WandbLogger was initialized, make it watch the model
|
||||||
|
utils.make_wandb_watch_model(loggers=loggers, model=model)
|
||||||
|
|
||||||
|
# Log to all loggers everything specified in 'extra_logs' section of config
|
||||||
|
utils.log_extra_hparams(
|
||||||
|
loggers=loggers,
|
||||||
config=config,
|
config=config,
|
||||||
model=model,
|
model=model,
|
||||||
datamodule=datamodule
|
datamodule=datamodule,
|
||||||
|
callbacks=callbacks
|
||||||
)
|
)
|
||||||
|
|
||||||
message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n"
|
utils.show_init_info(model, datamodule, callbacks, loggers)
|
||||||
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)
|
|
||||||
|
|
||||||
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
|
||||||
log.info(f"Using pytorch seed: {config['seeds']['pytorch_seed']}\n")
|
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: pl.Trainer = init_trainer(
|
trainer: pl.Trainer = utils.init_trainer(
|
||||||
trainer_config=config["trainer"],
|
trainer_config=config["trainer"],
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
loggers=loggers
|
loggers=loggers
|
||||||
)
|
)
|
||||||
|
|
||||||
# Evaluate model on test set before training
|
|
||||||
# trainer.test(model=model, datamodule=datamodule)
|
|
||||||
|
|
||||||
# Train the model
|
# Train the model
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
@@ -92,7 +73,7 @@ def train(config):
|
|||||||
|
|
||||||
@hydra.main(config_path="configs/", config_name="config.yaml")
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
def main(config: DictConfig) -> None:
|
def main(config: DictConfig) -> None:
|
||||||
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") # print content of config
|
utils.show_config(config) # print content of config
|
||||||
train(config)
|
train(config)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
torch>=1.7.0
|
torch>=1.7.0
|
||||||
torchvision>=0.8.1
|
torchvision>=0.8.1
|
||||||
torchaudio>=0.7.0
|
torchaudio>=0.7.0
|
||||||
pytorch-lightning>=1.0.8
|
pytorch-lightning>=1.1.3
|
||||||
hydra-core
|
hydra-core
|
||||||
wandb>=0.10.12
|
wandb>=0.10.12
|
||||||
scikit-learn>=0.23.2
|
scikit-learn>=0.23.2
|
||||||
|
|||||||
Reference in new issue
Block a user