Dev (#78)
* add neptune integration * improve readme * quick fix * improve datamodule * remove unnecessary folders from .gitignore * change folder structure * add optuna config * add bash tests * redesign readme.md * change wandb callbacks names * fix wandb callbacks * resolve issues with sweeping alongside wandb * improve rich config printing * update readme * Update README.md
This commit is contained in:
56 files changed
+1294
-837
No files matched your search
@@ -0,0 +1 @@
|
||||
# makes 'src' a Python module
|
||||
@@ -0,0 +1,32 @@
|
||||
from torch import nn
|
||||
|
||||
|
||||
class SimpleDenseNet(nn.Module):
|
||||
def __init__(self, hparams):
|
||||
super().__init__()
|
||||
|
||||
self.model = nn.Sequential(
|
||||
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
|
||||
nn.BatchNorm1d(hparams["lin1_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout1"]),
|
||||
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
|
||||
nn.BatchNorm1d(hparams["lin2_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout2"]),
|
||||
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
|
||||
nn.BatchNorm1d(hparams["lin3_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout3"]),
|
||||
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
|
||||
nn.LogSoftmax(dim=1),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
batch_size, channels, width, height = x.size()
|
||||
|
||||
# mnist images are (1, 28, 28) (channels, width, height)
|
||||
# (b, 1, 28, 28) -> (b, 1*28*28)
|
||||
x = x.view(batch_size, -1)
|
||||
|
||||
return self.model(x)
|
||||
@@ -0,0 +1,29 @@
|
||||
from pytorch_lightning import Callback
|
||||
|
||||
|
||||
class ExampleCallback(Callback):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def on_init_start(self, trainer):
|
||||
print("Starting to initialize trainer!")
|
||||
|
||||
def on_init_end(self, trainer):
|
||||
print("Trainer is initialized now.")
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
print("Do something when training ends.")
|
||||
|
||||
|
||||
class UnfreezeModelCallback(Callback):
|
||||
"""
|
||||
Unfreeze all model parameters after a few epochs.
|
||||
"""
|
||||
|
||||
def __init__(self, wait_epochs=5):
|
||||
self.wait_epochs = wait_epochs
|
||||
|
||||
def on_epoch_end(self, trainer, pl_module):
|
||||
if trainer.current_epoch == self.wait_epochs:
|
||||
for param in pl_module.model.model.parameters():
|
||||
param.requires_grad = True
|
||||
@@ -0,0 +1,234 @@
|
||||
# wandb
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
import wandb
|
||||
|
||||
# pytorch
|
||||
from pytorch_lightning import Callback
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
|
||||
# others
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
from typing import List
|
||||
import glob
|
||||
import os
|
||||
|
||||
|
||||
def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
||||
logger = None
|
||||
for lg in trainer.logger:
|
||||
if isinstance(lg, WandbLogger):
|
||||
logger = lg
|
||||
|
||||
if not logger:
|
||||
raise Exception(
|
||||
"You're using wandb related callback, "
|
||||
"but WandbLogger was not found for some reason..."
|
||||
)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
class UploadCodeToWandbAsArtifact(Callback):
|
||||
"""Upload all *.py files to wandb as an artifact at the beginning of the run."""
|
||||
|
||||
def __init__(self, code_dir: str):
|
||||
self.code_dir = code_dir
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
experiment = logger.experiment
|
||||
|
||||
code = wandb.Artifact("project-source", type="code")
|
||||
for path in glob.glob(os.path.join(self.code_dir, "**/*.py"), recursive=True):
|
||||
code.add_file(path)
|
||||
|
||||
experiment.use_artifact(code)
|
||||
|
||||
|
||||
class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
"""Upload experiment checkpoints to wandb as an artifact at the end of training."""
|
||||
|
||||
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
||||
self.ckpt_dir = ckpt_dir
|
||||
self.upload_best_only = upload_best_only
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
experiment = logger.experiment
|
||||
|
||||
ckpts = wandb.Artifact("experiment-ckpts", type="checkpoints")
|
||||
|
||||
if self.upload_best_only:
|
||||
ckpts.add_file(trainer.checkpoint_callback.best_model_path)
|
||||
else:
|
||||
for path in glob.glob(
|
||||
os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True
|
||||
):
|
||||
ckpts.add_file(path)
|
||||
|
||||
experiment.use_artifact(ckpts)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
self.log_freq = log_freq
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class LogF1PrecisionRecallHeatmapToWandb(Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap from validation step outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
|
||||
def __init__(self, class_names: List[str] = None):
|
||||
self.class_names = class_names
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
self.ready = False
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Start executing this callback only after all validation sanity checks end."""
|
||||
self.ready = True
|
||||
|
||||
def on_validation_batch_end(
|
||||
self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx
|
||||
):
|
||||
"""Gather data from single batch."""
|
||||
if self.ready:
|
||||
preds, targets = outputs["preds"], outputs["targets"]
|
||||
self.preds.append(preds)
|
||||
self.targets.append(targets)
|
||||
|
||||
def on_validation_epoch_end(self, trainer, pl_module):
|
||||
"""Generate f1, precision and recall heatmap."""
|
||||
if self.ready:
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
experiment = logger.experiment
|
||||
|
||||
self.preds = torch.cat(self.preds).cpu()
|
||||
self.targets = torch.cat(self.targets).cpu()
|
||||
f1 = f1_score(self.preds, self.targets, average=None)
|
||||
r = recall_score(self.preds, self.targets, average=None)
|
||||
p = precision_score(self.preds, self.targets, average=None)
|
||||
|
||||
experiment.log(
|
||||
{
|
||||
f"f1_p_r_heatmap/{trainer.current_epoch}_{experiment.id}": wandb.plots.HeatMap(
|
||||
x_labels=self.class_names,
|
||||
y_labels=["f1", "precision", "recall"],
|
||||
matrix_values=[f1, p, r],
|
||||
show_text=True,
|
||||
)
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
|
||||
|
||||
class LogConfusionMatrixToWandb(Callback):
|
||||
"""
|
||||
Generate Confusion Matrix.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
|
||||
def __init__(self, class_names: List[str] = None):
|
||||
self.class_names = class_names
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
self.ready = False
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Start executing this callback only after all validation sanity checks end."""
|
||||
self.ready = True
|
||||
|
||||
def on_validation_batch_end(
|
||||
self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx
|
||||
):
|
||||
"""Gather data from single batch."""
|
||||
if self.ready:
|
||||
preds, targets = outputs["preds"], outputs["targets"]
|
||||
self.preds.append(preds)
|
||||
self.targets.append(targets)
|
||||
|
||||
def on_validation_epoch_end(self, trainer, pl_module):
|
||||
"""Generate confusion matrix."""
|
||||
if self.ready:
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
experiment = logger.experiment
|
||||
|
||||
self.preds = torch.cat(self.preds).tolist()
|
||||
self.targets = torch.cat(self.targets).tolist()
|
||||
|
||||
experiment.log(
|
||||
{
|
||||
f"confusion_matrix/{trainer.current_epoch}_{experiment.id}": wandb.plot.confusion_matrix(
|
||||
preds=self.preds,
|
||||
y_true=self.targets,
|
||||
class_names=self.class_names,
|
||||
)
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
|
||||
|
||||
''' BUGGED :(
|
||||
class LogBestMetricScoresToWandb(Callback):
|
||||
"""
|
||||
Store in wandb:
|
||||
- max train acc
|
||||
- min train loss
|
||||
- max val acc
|
||||
- min val loss
|
||||
Useful for comparing runs in table views, as wandb doesn't currently support column aggregation.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.train_loss_best = None
|
||||
self.train_acc_best = None
|
||||
self.val_loss_best = None
|
||||
self.val_acc_best = None
|
||||
self.ready = False
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Start executing this callback only after all validation sanity checks end."""
|
||||
self.ready = True
|
||||
|
||||
def on_epoch_end(self, trainer, pl_module):
|
||||
if self.ready:
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
experiment = logger.experiment
|
||||
|
||||
metrics = trainer.callback_metrics
|
||||
|
||||
if not self.train_loss_best or metrics["train/loss"] < self.train_loss_best:
|
||||
self.train_loss_best = metrics["train_loss"]
|
||||
|
||||
if not self.train_acc_best or metrics["train/acc"] > self.train_acc_best:
|
||||
self.train_acc_best = metrics["train/acc"]
|
||||
|
||||
if not self.val_loss_best or metrics["val/loss"] < self.val_loss_best:
|
||||
self.val_loss_best = metrics["val/loss"]
|
||||
|
||||
if not self.val_acc_best or metrics["val/acc"] > self.val_acc_best:
|
||||
self.val_acc_best = metrics["val/acc"]
|
||||
|
||||
experiment.log({"train/loss_best": self.train_loss_best}, commit=False)
|
||||
experiment.log({"train/acc_best": self.train_acc_best}, commit=False)
|
||||
experiment.log({"val/loss_best": self.val_loss_best}, commit=False)
|
||||
experiment.log({"val/acc_best": self.val_acc_best}, commit=False)
|
||||
'''
|
||||
@@ -0,0 +1,73 @@
|
||||
from torch.utils.data import DataLoader, ConcatDataset, random_split
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torchvision.transforms import transforms
|
||||
from torchvision.datasets import MNIST
|
||||
|
||||
|
||||
class MNISTDataModule(LightningDataModule):
|
||||
"""
|
||||
This is example of LightningDataModule for MNIST dataset.
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = kwargs["data_dir"]
|
||||
self.batch_size = kwargs["batch_size"]
|
||||
self.train_val_test_split = kwargs["train_val_test_split"]
|
||||
self.num_workers = kwargs["num_workers"]
|
||||
self.pin_memory = kwargs["pin_memory"]
|
||||
|
||||
self.transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
|
||||
# self.dims is returned when you call datamodule.size()
|
||||
self.dims = (1, 28, 28)
|
||||
|
||||
self.data_train = None
|
||||
self.data_val = None
|
||||
self.data_test = None
|
||||
|
||||
def prepare_data(self):
|
||||
"""Download data if needed. This method is called only from a single GPU.
|
||||
Do not use it to assign state (self.x = y)."""
|
||||
MNIST(self.data_dir, train=True, download=True)
|
||||
MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage=None):
|
||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
||||
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
|
||||
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
|
||||
dataset = ConcatDataset(datasets=[trainset, testset])
|
||||
self.data_train, self.data_val, self.data_test = random_split(
|
||||
dataset, self.train_val_test_split
|
||||
)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(
|
||||
dataset=self.data_train,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory,
|
||||
shuffle=True,
|
||||
)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(
|
||||
dataset=self.data_val,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory,
|
||||
shuffle=False,
|
||||
)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(
|
||||
dataset=self.data_test,
|
||||
batch_size=self.batch_size,
|
||||
num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory,
|
||||
shuffle=False,
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
from torch.utils.data import Dataset
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
|
||||
class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder and converting them to monochromatic.
|
||||
Can be used to perform inference with trained MNIST model.
|
||||
"""
|
||||
|
||||
def __init__(self, img_dir, transform):
|
||||
self.transform = transform
|
||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||
|
||||
def __getitem__(self, idx):
|
||||
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||
# image = Image.open(self.images[idx]).convert("RGB")
|
||||
|
||||
if self.transform is not None:
|
||||
image = self.transform(image)
|
||||
|
||||
return image
|
||||
|
||||
def __len__(self):
|
||||
return len(self.images)
|
||||
@@ -0,0 +1,94 @@
|
||||
from pytorch_lightning.metrics.classification import Accuracy
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
# import custom architectures
|
||||
from src.architectures.simple_dense_net import SimpleDenseNet
|
||||
|
||||
|
||||
class LitModelMNIST(pl.LightningModule):
|
||||
"""
|
||||
This is example of LightningModule for MNIST classification.
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__()
|
||||
self.save_hyperparameters()
|
||||
self.accuracy = Accuracy()
|
||||
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||
|
||||
self.train_acc_hist = []
|
||||
self.train_loss_hist = []
|
||||
self.val_acc_hist = []
|
||||
self.val_loss_hist = []
|
||||
|
||||
def forward(self, x):
|
||||
return self.architecture(x)
|
||||
|
||||
# logic for a single training step
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# training metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||
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 or in training_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": y}
|
||||
|
||||
# logic for a single validation step
|
||||
def validation_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# validation metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||
|
||||
# we can return here anything and then read it in some callback or in validation_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": y}
|
||||
|
||||
# logic for a single testing step
|
||||
def test_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# test metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
||||
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
||||
|
||||
return loss
|
||||
|
||||
def training_epoch_end(self, outputs):
|
||||
self.train_acc_hist.append(self.trainer.callback_metrics["train/acc"])
|
||||
self.train_loss_hist.append(self.trainer.callback_metrics["train/loss"])
|
||||
self.log("train/acc_best", max(self.train_acc_hist), prog_bar=False)
|
||||
self.log("train/loss_best", min(self.train_loss_hist), prog_bar=False)
|
||||
|
||||
def validation_epoch_end(self, outputs):
|
||||
self.val_acc_hist.append(self.trainer.callback_metrics["val/acc"])
|
||||
self.val_loss_hist.append(self.trainer.callback_metrics["val/loss"])
|
||||
self.log("val/acc_best", max(self.val_acc_hist), prog_bar=False)
|
||||
self.log("val/loss_best", min(self.val_loss_hist), prog_bar=False)
|
||||
|
||||
def configure_optimizers(self):
|
||||
if self.hparams.optimizer == "adam":
|
||||
return torch.optim.Adam(
|
||||
self.parameters(),
|
||||
lr=self.hparams.lr,
|
||||
weight_decay=self.hparams.weight_decay,
|
||||
)
|
||||
else:
|
||||
raise Exception("Invalid optimizer name")
|
||||
@@ -0,0 +1,10 @@
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
mnist_train_transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
|
||||
mnist_test_transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
@@ -0,0 +1,37 @@
|
||||
from src.models.mnist_model import LitModelMNIST
|
||||
from src.transforms import mnist_transforms
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def predict():
|
||||
"""
|
||||
This method is example of inference with a trained model.
|
||||
It Loads trained image classification model from checkpoint.
|
||||
Then it loads example image and predicts its label.
|
||||
"""
|
||||
|
||||
# ckpt can be also a URL!
|
||||
CKPT_PATH = "epoch=0.ckpt"
|
||||
|
||||
# load model from checkpoint
|
||||
trained_model = LitModelMNIST.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
|
||||
# switch to evaluation mode
|
||||
trained_model.eval()
|
||||
trained_model.freeze()
|
||||
|
||||
# load data
|
||||
img = Image.open("data/example_img.png").convert("L") # convert to black and white
|
||||
# img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
|
||||
|
||||
# preprocess
|
||||
img = mnist_transforms.mnist_test_transforms(img)
|
||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||
|
||||
# inference
|
||||
output = trained_model(img)
|
||||
print(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
predict()
|
||||
@@ -0,0 +1,154 @@
|
||||
# pytorch lightning imports
|
||||
import pytorch_lightning as pl
|
||||
|
||||
# hydra imports
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from hydra.utils import get_original_cwd, to_absolute_path
|
||||
|
||||
# loggers
|
||||
import wandb
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
|
||||
# from pytorch_lightning.loggers.neptune import NeptuneLogger
|
||||
# from pytorch_lightning.loggers.comet import CometLogger
|
||||
# from pytorch_lightning.loggers.mlflow import MLFlowLogger
|
||||
# from pytorch_lightning.loggers.tensorboard import TensorBoardLogger
|
||||
|
||||
# rich imports
|
||||
from rich import print
|
||||
from rich.syntax import Syntax
|
||||
from rich.tree import Tree
|
||||
|
||||
# normal imports
|
||||
from typing import List
|
||||
|
||||
|
||||
def print_config(config: DictConfig):
|
||||
"""Prints content of Hydra config using Rich library.
|
||||
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
"""
|
||||
|
||||
# TODO print main config path and experiment config path
|
||||
# directory = to_absolute_path("configs/config.yaml")
|
||||
# print(f"Main config path: [link file://{directory}]{directory}")
|
||||
|
||||
style = "dim"
|
||||
|
||||
tree = Tree(f":gear: FULL HYDRA CONFIG", style=style, guide_style=style)
|
||||
|
||||
trainer = OmegaConf.to_yaml(config["trainer"], resolve=True)
|
||||
trainer_branch = tree.add("Trainer", style=style, guide_style=style)
|
||||
trainer_branch.add(Syntax(trainer, "yaml"))
|
||||
|
||||
model = OmegaConf.to_yaml(config["model"], resolve=True)
|
||||
model_branch = tree.add("Model", style=style, guide_style=style)
|
||||
model_branch.add(Syntax(model, "yaml"))
|
||||
|
||||
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=True)
|
||||
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style)
|
||||
datamodule_branch.add(Syntax(datamodule, "yaml"))
|
||||
|
||||
callbacks_branch = tree.add("Callbacks", style=style, guide_style=style)
|
||||
if "callbacks" in config:
|
||||
for cb_name, cb_conf in config["callbacks"].items():
|
||||
cb = callbacks_branch.add(cb_name, style=style, guide_style=style)
|
||||
cb.add(Syntax(OmegaConf.to_yaml(cb_conf, resolve=True), "yaml"))
|
||||
else:
|
||||
callbacks_branch.add("None")
|
||||
|
||||
logger_branch = tree.add("Logger", style=style, guide_style=style)
|
||||
if "logger" in config:
|
||||
for lg_name, lg_conf in config["logger"].items():
|
||||
lg = logger_branch.add(lg_name, style=style, guide_style=style)
|
||||
lg.add(Syntax(OmegaConf.to_yaml(lg_conf, resolve=True), "yaml"))
|
||||
else:
|
||||
logger_branch.add("None")
|
||||
|
||||
seed = config.get("seed", "None")
|
||||
seed_branch = tree.add(f"Seed", style=style, guide_style=style)
|
||||
seed_branch.add(seed, style=style, guide_style=style)
|
||||
|
||||
print(tree)
|
||||
|
||||
|
||||
def log_hparams_to_all_loggers(
|
||||
config: DictConfig,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
trainer: pl.Trainer,
|
||||
callbacks: List[pl.Callback],
|
||||
logger: List[pl.loggers.LightningLoggerBase],
|
||||
):
|
||||
"""This method controls which parameters from Hydra config are saved by Lightning loggers.
|
||||
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
model (pl.LightningModule): [description]
|
||||
datamodule (pl.LightningDataModule): [description]
|
||||
trainer (pl.Trainer): [description]
|
||||
callbacks (List[pl.Callback]): [description]
|
||||
logger (List[pl.loggers.LightningLoggerBase]): [description]
|
||||
"""
|
||||
|
||||
hparams = {}
|
||||
|
||||
# save all params of model, datamodule and trainer
|
||||
hparams.update(config["model"])
|
||||
hparams.update(config["datamodule"])
|
||||
hparams.update(config["trainer"])
|
||||
hparams.pop("_target_")
|
||||
|
||||
# save seed
|
||||
hparams["seed"] = config.get("seed", "None")
|
||||
|
||||
# save targets
|
||||
hparams["_class_model"] = config["model"]["_target_"]
|
||||
hparams["_class_datamodule"] = config["datamodule"]["_target_"]
|
||||
|
||||
# save sizes of each dataset
|
||||
if hasattr(datamodule, "data_train") and datamodule.data_train:
|
||||
hparams["train_size"] = len(datamodule.data_train)
|
||||
if hasattr(datamodule, "data_val") and datamodule.data_val:
|
||||
hparams["val_size"] = len(datamodule.data_val)
|
||||
if hasattr(datamodule, "data_test") and datamodule.data_test:
|
||||
hparams["test_size"] = len(datamodule.data_test)
|
||||
|
||||
# save number of model parameters
|
||||
hparams["#params_total"] = sum(p.numel() for p in model.parameters())
|
||||
hparams["#params_trainable"] = sum(
|
||||
p.numel() for p in model.parameters() if p.requires_grad
|
||||
)
|
||||
hparams["#params_not_trainable"] = sum(
|
||||
p.numel() for p in model.parameters() if not p.requires_grad
|
||||
)
|
||||
|
||||
# send hparams to all loggers
|
||||
for lg in logger:
|
||||
lg.log_hyperparams(hparams)
|
||||
|
||||
|
||||
def finish(
|
||||
config: DictConfig,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
trainer: pl.Trainer,
|
||||
callbacks: List[pl.Callback],
|
||||
logger: List[pl.loggers.LightningLoggerBase],
|
||||
):
|
||||
"""Makes sure everything closed properly.
|
||||
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
model (pl.LightningModule): [description]
|
||||
datamodule (pl.LightningDataModule): [description]
|
||||
trainer (pl.Trainer): [description]
|
||||
callbacks (List[pl.Callback]): [description]
|
||||
logger (List[pl.loggers.LightningLoggerBase]): [description]
|
||||
"""
|
||||
|
||||
# without this sweeps with wandb logger might crash!
|
||||
for lg in logger:
|
||||
if isinstance(lg, WandbLogger):
|
||||
wandb.finish()
|
||||
Reference in new issue
Block a user