diff --git a/README.md b/README.md
index 1da4dc5..89068c3 100644
--- a/README.md
+++ b/README.md
@@ -16,7 +16,7 @@ Click on "Use this template" button above to initialize new repository.
@@ -83,7 +83,7 @@ loggers:
default_callbacks:
ModelCheckpoint:
monitor: "val_acc" <- name of the logged metric which determines when model is improving
- save_top_k: 1 <- save k best lightning_models (determined by above metric)
+ save_top_k: 1 <- save k best models (determined by above metric)
save_last: True <- additionaly always save model from last epoch
mode: "max" <- can be "max" or "min"
EarlyStopping:
@@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
max_epochs: 10
model:
load_from:
- model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py"
+ model_path: "models/simple_mnist_classifier/simple_mnist_classifier.py"
model_class: "LitModel"
hparams:
lr: 0.001
@@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
lin3_size: 128
datamodule:
load_from:
- datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
+ datamodule_path: "datamodules/mnist_datamodule/mnist_datamodule.py"
datamodule_class: "MNISTDataModule"
hparams:
batch_size: 64
@@ -138,9 +138,9 @@ Each run configuration needs to contain sections `trainer`, `model` and `datamod
Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)
-Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/pytorch_modules/lightning_models/simple_mnist_classifier.py)).
+Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/src/models/simple_mnist_classifier.py)).
-Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/pytorch_modules/lightning_datamodules/mnist_datamodule.py)).
+Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/src/datamodules/mnist_datamodule.py)).
diff --git a/conda_env.yaml b/conda_env.yaml
index 7703647..7282075 100644
--- a/conda_env.yaml
+++ b/conda_env.yaml
@@ -1,8 +1,10 @@
#name: conda_env_name
+
channels:
- pytorch
- conda-forge
- defaults
+
dependencies:
- python=3.8
- pip
diff --git a/project/configs/callbacks/default_callbacks.yaml b/project/configs/callbacks/default_callbacks.yaml
index cc0ca4a..2d014b9 100644
--- a/project/configs/callbacks/default_callbacks.yaml
+++ b/project/configs/callbacks/default_callbacks.yaml
@@ -4,7 +4,7 @@ model_checkpoint:
class: pytorch_lightning.callbacks.ModelCheckpoint
args:
monitor: "val_acc" # name of the logged metric which determines when model is improving
- save_top_k: 1 # save k best lightning_models (determined by above metric)
+ save_top_k: 1 # save k best models (determined by above metric)
save_last: True # additionaly always save model from last epoch
mode: "max" # can be "max" or "min"
filepath: "checkpoints/{epoch}"
diff --git a/project/configs/callbacks/mnist_callbacks.yaml b/project/configs/callbacks/mnist_callbacks.yaml
index dfa4e43..34e7b77 100644
--- a/project/configs/callbacks/mnist_callbacks.yaml
+++ b/project/configs/callbacks/mnist_callbacks.yaml
@@ -1,2 +1,5 @@
# @package _group_
+defaults:
+ - default_callbacks.yaml
+ - wandb_callbacks.yaml
diff --git a/project/configs/callbacks/wandb_callbacks.yaml b/project/configs/callbacks/wandb_callbacks.yaml
index 70f8ea0..d9fbf88 100644
--- a/project/configs/callbacks/wandb_callbacks.yaml
+++ b/project/configs/callbacks/wandb_callbacks.yaml
@@ -1,18 +1,31 @@
# @package _group_
save_best_metric_scores_to_wandb:
- class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
+ class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
args: {}
-save_code_to_wandb_as_artifact:
- class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb
- args:
- code_dir: ${work_dir}/
+#save_confusion_matrix_to_wandb:
+# class: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
+# args:
+# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
+#
+#
+#save_f1_precision_recall_heatmap_to_wandb:
+# class: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb
+# args:
+# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
-upload_ckpts_to_wandb_as_artifact:
- class: pytorch_modules.lightning_callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
- args:
- ckpt_dir: "checkpoints/"
- upload_best_only: True
+#upload_code_to_wandb_as_artifact:
+# class: src.callbacks.wandb_callbacks.SaveCodeToWandb
+# args:
+# code_dir: ${work_dir}/
+
+
+#upload_ckpts_to_wandb_as_artifact:
+# class: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
+# args:
+# ckpt_dir: "checkpoints/"
+# upload_best_only: True
+
diff --git a/project/configs/config.yaml b/project/configs/config.yaml
index e450c51..dc7714a 100644
--- a/project/configs/config.yaml
+++ b/project/configs/config.yaml
@@ -23,7 +23,7 @@ hydra:
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
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
extra_logs:
log_seeds: True
@@ -33,6 +33,6 @@ extra_logs:
log_model_class: True
log_optimizer_class: True
log_datamodule_class: True
+ log_model_architecture_class: True
- log_train_val_test_sizes: True
- log_model_architecture_class_name: True
+ log_train_val_test_sizes: False
diff --git a/project/configs/datamodule/mnist_datamodule.yaml b/project/configs/datamodule/mnist_datamodule.yaml
index f31d726..aa3240f 100644
--- a/project/configs/datamodule/mnist_datamodule.yaml
+++ b/project/configs/datamodule/mnist_datamodule.yaml
@@ -1,6 +1,6 @@
# @package _group_
-class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
+class: src.datamodules.mnist_datamodule.MNISTDataModule
args:
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
diff --git a/project/configs/experiment/exp_example_advanced.yaml b/project/configs/experiment/exp_example_advanced.yaml
index 0d60efc..adab2d1 100644
--- a/project/configs/experiment/exp_example_advanced.yaml
+++ b/project/configs/experiment/exp_example_advanced.yaml
@@ -26,7 +26,7 @@ trainer:
limit_val_batches: 0.9 # validate on 90% of validation data
limit_test_batches: 1.0 # test on 100% of test data
val_check_interval: 0.5 # perform validation twice per epoch
- # resume_from_checkpoint: ${work_dir}/last.ckpt # use this to resume training from checkpoint
+ # resume_from_checkpoint: ${work_dir}/last.ckpt # path to checkpoint (this can be also url for download)
model:
args: # you can add here any params you want and then access them in lightning model
diff --git a/project/configs/model/simple_mnist_classifier.yaml b/project/configs/model/simple_mnist_classifier.yaml
index 10989d0..4d8f282 100644
--- a/project/configs/model/simple_mnist_classifier.yaml
+++ b/project/configs/model/simple_mnist_classifier.yaml
@@ -1,6 +1,6 @@
# @package _group_
-class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
+class: src.models.simple_mnist_classifier.LitModel
args:
lr: 0.001
weight_decay: 0.00001
diff --git a/project/configs/trainer/default_trainer.yaml b/project/configs/trainer/default_trainer.yaml
index 49c42d5..80a2f39 100644
--- a/project/configs/trainer/default_trainer.yaml
+++ b/project/configs/trainer/default_trainer.yaml
@@ -3,9 +3,11 @@
# default args passed to Lightning Trainer on every experiment
# they can be combined or overwritten with args set in experiment config
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
+ max_epochs: 10
num_sanity_val_steps: 3
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
default_root_dir: "lightning_logs/"
+ auto_lr_find: False # "https://pytorch-lightning.readthedocs.io/en/stable/lr_finder.html"
diff --git a/project/src/__init__.py b/project/src/__init__.py
new file mode 100644
index 0000000..e24e3b1
--- /dev/null
+++ b/project/src/__init__.py
@@ -0,0 +1 @@
+# package file
diff --git a/project/pytorch_modules/architectures/simple_mnist.py b/project/src/architectures/simple_mnist.py
similarity index 100%
rename from project/pytorch_modules/architectures/simple_mnist.py
rename to project/src/architectures/simple_mnist.py
diff --git a/project/pytorch_modules/lightning_callbacks/custom_callbacks.py b/project/src/callbacks/custom_callbacks.py
similarity index 100%
rename from project/pytorch_modules/lightning_callbacks/custom_callbacks.py
rename to project/src/callbacks/custom_callbacks.py
diff --git a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py b/project/src/callbacks/wandb_callbacks.py
similarity index 70%
rename from project/pytorch_modules/lightning_callbacks/wandb_callbacks.py
rename to project/src/callbacks/wandb_callbacks.py
index 10566e4..e7a867b 100644
--- a/project/pytorch_modules/lightning_callbacks/wandb_callbacks.py
+++ b/project/src/callbacks/wandb_callbacks.py
@@ -47,7 +47,7 @@ class SaveMetricsHeatmapToWandb(Callback):
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
- def __init__(self, class_names):
+ def __init__(self, class_names=None):
self.class_names = class_names
self.preds = []
self.targets = []
@@ -60,7 +60,7 @@ class SaveMetricsHeatmapToWandb(Callback):
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["y"]
+ preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
self.preds.append(preds)
self.targets.append(targets)
@@ -96,7 +96,7 @@ class SaveConfusionMatrixToWandb(Callback):
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
- def __init__(self, class_names):
+ def __init__(self, class_names=None):
self.class_names = class_names
self.preds = []
self.targets = []
@@ -109,7 +109,7 @@ class SaveConfusionMatrixToWandb(Callback):
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["y"]
+ preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
self.preds.append(preds)
self.targets.append(targets)
@@ -119,17 +119,14 @@ class SaveConfusionMatrixToWandb(Callback):
self.preds = torch.cat(self.preds).tolist()
self.targets = torch.cat(self.targets).tolist()
- logger = None
- for some_logger in trainer.logger.experiment:
- if isinstance(some_logger, wandb_run):
- logger = some_logger
-
- logger.log({
- f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
- self.preds,
- self.targets,
- class_names=self.class_names)
- }, commit=False)
+ for logger in trainer.logger.experiment:
+ if isinstance(logger, wandb_run):
+ logger.log({
+ f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
+ preds=self.preds,
+ y_true=self.targets,
+ class_names=self.class_names)
+ }, commit=False)
self.preds = []
self.targets = []
@@ -137,62 +134,34 @@ class SaveConfusionMatrixToWandb(Callback):
class SaveBestMetricScoresToWandb(Callback):
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_acc_list = []
self.val_loss_best = None
self.val_acc_best = None
-
self.ready = False
- def clear_lists(self):
- self.train_loss_list.clear()
- self.train_acc_list.clear()
- self.val_loss_list.clear()
- self.val_acc_list.clear()
-
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_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
- """Gather data from single batch."""
- # This is bugged :/ - lets wait for lightning 1.2 update
- # if self.ready:
- # self.train_loss_list.append(outputs["loss"])
- # self.train_acc_list.append(outputs["acc"])
- pass
-
- def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
- """Gather data from single batch."""
- if self.ready:
- self.val_loss_list.append(outputs["loss"])
- self.val_acc_list.append(outputs["acc"])
-
def on_epoch_end(self, trainer, pl_module):
if self.ready:
for logger in trainer.logger.experiment:
+ metrics = trainer.callback_metrics
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)
- 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_acc_best = acc if self.val_acc_best is None or acc > self.val_acc_best else self.val_acc_best
+ if self.train_loss_best is None or metrics["train_loss"] < self.train_loss_best:
+ self.train_loss_best = metrics["train_loss"]
+ if self.train_acc_best is None or metrics["train_acc"] > self.train_acc_best:
+ self.train_acc_best = metrics["train_acc"]
+ if self.val_loss_best is None or metrics["val_loss"] < self.val_loss_best:
+ self.val_loss_best = metrics["val_loss"]
+ if self.val_acc_best is None or metrics["val_acc"] > self.val_acc_best:
+ self.val_acc_best = metrics["val_acc"]
+ logger.log({"train_loss_best": self.train_loss_best}, commit=False)
+ logger.log({"train_acc_best": self.train_acc_best}, commit=False)
logger.log({"val_loss_best": self.val_loss_best}, commit=False)
logger.log({"val_acc_best": self.val_acc_best}, commit=False)
- self.clear_lists()
-
# class SaveImagePredictionsToWandb(Callback):
# """
diff --git a/project/pytorch_modules/lightning_datamodules/mnist_datamodule.py b/project/src/datamodules/mnist_datamodule.py
similarity index 100%
rename from project/pytorch_modules/lightning_datamodules/mnist_datamodule.py
rename to project/src/datamodules/mnist_datamodule.py
diff --git a/project/pytorch_modules/datasets/img_test_dataset.py b/project/src/datasets/img_test_dataset.py
similarity index 100%
rename from project/pytorch_modules/datasets/img_test_dataset.py
rename to project/src/datasets/img_test_dataset.py
diff --git a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py b/project/src/models/simple_mnist_classifier.py
similarity index 84%
rename from project/pytorch_modules/lightning_models/simple_mnist_classifier.py
rename to project/src/models/simple_mnist_classifier.py
index 0911e98..5b2ab93 100644
--- a/project/pytorch_modules/lightning_models/simple_mnist_classifier.py
+++ b/project/src/models/simple_mnist_classifier.py
@@ -1,11 +1,11 @@
-from sklearn.metrics import accuracy_score
+from pytorch_lightning.metrics.classification import Accuracy
+from template_utils.initializers import load_class
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
-from template_utils.initializers import load_class
# import custom architectures
-from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
+from src.architectures.simple_mnist import SimpleMNISTClassifier
class LitModel(pl.LightningModule):
@@ -25,6 +25,8 @@ class LitModel(pl.LightningModule):
self.model = SimpleMNISTClassifier(hparams=self.hparams)
+ self.accuracy = Accuracy()
+
def forward(self, x):
return self.model(x)
@@ -36,12 +38,11 @@ class LitModel(pl.LightningModule):
# training metrics
preds = torch.argmax(logits, dim=1)
- acc = accuracy_score(preds.cpu(), y.cpu())
+ acc = self.accuracy(preds, y)
self.log('train_loss', loss, on_step=False, on_epoch=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": loss, "acc": acc, "preds": preds, "y": y}
+ return loss
# logic for a single validation step
def validation_step(self, batch, batch_idx):
@@ -51,11 +52,12 @@ class LitModel(pl.LightningModule):
# validation metrics
preds = torch.argmax(logits, dim=1)
- acc = accuracy_score(preds.cpu(), y.cpu())
+ acc = self.accuracy(preds, y)
self.log('val_loss', loss, on_step=False, on_epoch=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
- return {"loss": loss, "acc": acc, "preds": preds, "y": y}
+ # we can return here anything and then read it in some callback
+ return {"batch_val_loss": loss, "batch_val_acc": acc, "batch_val_preds": preds, "batch_val_y": y}
# logic for a single testing step
def test_step(self, batch, batch_idx):
@@ -65,11 +67,11 @@ class LitModel(pl.LightningModule):
# test metrics
preds = torch.argmax(logits, dim=1)
- acc = accuracy_score(preds.cpu(), y.cpu())
+ 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": loss}
+ return loss
def configure_optimizers(self):
Optimizer = load_class(self.optimizer_config["class"])
diff --git a/project/pytorch_modules/transforms/mnist_transforms.py b/project/src/transforms/mnist_transforms.py
similarity index 100%
rename from project/pytorch_modules/transforms/mnist_transforms.py
rename to project/src/transforms/mnist_transforms.py
diff --git a/project/template_utils/execute_sweep.py b/project/template_utils/execute_sweep.py
index c396584..505071f 100644
--- a/project/template_utils/execute_sweep.py
+++ b/project/template_utils/execute_sweep.py
@@ -1,31 +1,42 @@
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
+# hydra imports
+from omegaconf import DictConfig
+import hydra
+
+# template utils imports
+import template_utils.initializers as utils
+
import wandb
-import train
+from train import train
-# Choose which run config to optimize
-RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
-
-# Load configs
-project_config = train.load_config("config.yaml")
-run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
-
-# Initialize wandb
-wandb.init()
-
# Replace run config hyperparameters with the ones loaded from wandb sweep server
-sweep_hparams = wandb.Config._as_dict(wandb.config)
-for key, value in sweep_hparams.items():
- if key == "_wandb":
- continue
- elif key in run_config["trainer"]["args"]:
- run_config["trainer"]["args"][key] = value
- elif key in run_config["model"]["hparams"]:
- run_config["model"]["hparams"][key] = value
- elif key in run_config["datamodule"]["hparams"]:
- run_config["datamodule"]["hparams"][key] = value
+def replace_hparams(config, sweep_hparams):
+ for key, value in sweep_hparams.items():
+ if key == "_wandb":
+ continue
+ elif key in config["trainer"]["args"]:
+ config["trainer"]["args"][key] = value
+ elif key in config["model"]["args"]:
+ config["model"]["args"][key] = value
+ elif key in config["optimizer"]["args"]:
+ config["optimizer"]["args"][key] = value
+ elif key in config["datamodule"]["args"]:
+ config["datamodule"]["args"][key] = value
-# Execute run
-train.train(project_config=project_config, run_config=run_config, use_wandb=True)
+
+@hydra.main(config_path="configs/", config_name="config.yaml")
+def main(config: DictConfig) -> None:
+ wandb.init()
+
+ sweep_hparams = wandb.Config._as_dict(wandb.config)
+ utils.show_config(config) # print content of config
+
+ train(config)
+ wandb.finish()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/project/template_utils/inference_example.py b/project/template_utils/inference_example.py
index 755f349..fbee106 100644
--- a/project/template_utils/inference_example.py
+++ b/project/template_utils/inference_example.py
@@ -1,8 +1,8 @@
-from pytorch_modules.transforms import mnist_transforms
+from src.transforms import mnist_transforms
from PIL import Image
# the LitModel you import should be the same as the one you used for training!
-from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
+from src.models.simple_mnist_classifier import LitModel
# ckpt can be a url!
diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py
index d7bd4de..29288cd 100644
--- a/project/template_utils/initializers.py
+++ b/project/template_utils/initializers.py
@@ -138,11 +138,11 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
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"]})
+ log_hparams(loggers, {"_class_model": config["model"]["class"]})
if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]:
- log_hparams(loggers, {"optimizer_class": config["optimizer"]["class"]})
+ log_hparams(loggers, {"_class_optimizer": config["optimizer"]["class"]})
if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]:
- log_hparams(loggers, {"datamodule_class": config["datamodule"]["class"]})
+ log_hparams(loggers, {"_class_datamodule": config["datamodule"]["class"]})
if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]:
hparams = {}
@@ -154,9 +154,10 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
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 "log_model_architecture_class" in extra_logs and extra_logs["log_model_architecture_class"]:
if hasattr(model, "model"):
- log_hparams(loggers, {"model_architecture_class_name": model.model.__class__.__name__})
+ obj = model.model
+ log_hparams(loggers, {"_class_model_architecture": obj.__module__ + "." + obj.__class__.__name__})
def show_init_info(model, datamodule, callbacks, loggers):
@@ -177,6 +178,19 @@ def show_init_info(model, datamodule, callbacks, loggers):
log.info(message)
+def auto_find_lr(trainer, model, datamodule, loggers):
+ lr_finder = trainer.tuner.lr_find(model=model, datamodule=datamodule)
+ new_lr = lr_finder.suggestion()
+
+ # Save lr plot
+ fig = lr_finder.plot(suggest=True)
+ fig.savefig("lr_loss_curve.jpg")
+
+ # Set new lr
+ model.hparams.lr = new_lr
+ log_hparams(loggers, {"lr": new_lr})
+
+
def show_config(config: DictConfig):
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
diff --git a/project/test.py b/project/test.py
index 5c3af3c..b8e67e6 100644
--- a/project/test.py
+++ b/project/test.py
@@ -21,13 +21,18 @@ def my_app(cfg: DictConfig) -> None:
def test_logger():
logger = WandbLogger()
print(logger)
+ print(logger.__class__)
+ print(logger.__class__.__name__)
+ print(logger.__module__)
+ print(logger.__module__ + "." + logger.__class__.__name__)
if __name__ == "__main__":
my_app()
+
# with open("epoch=0.ckpt", "rb") as file:
# data = torch.load(file)
# print(data)
- # test_logger()
+ test_logger()
diff --git a/project/train.py b/project/train.py
index 6cf1e1d..fb13b73 100644
--- a/project/train.py
+++ b/project/train.py
@@ -16,6 +16,7 @@ import template_utils.initializers as utils
def train(config):
+ # Validate the correctness of loaded config
utils.validate_config(config=config)
# Set global PyTorch seed
@@ -56,6 +57,7 @@ def train(config):
callbacks=callbacks
)
+ # Log info in terminal about all initialized objects
utils.show_init_info(model, datamodule, callbacks, loggers)
# Init PyTorch Lightning trainer ⚡
@@ -65,6 +67,10 @@ def train(config):
loggers=loggers
)
+ # Automatically find learning rate if specified in config
+ if "auto_lr_find" in config["trainer"]["args"] and config["trainer"]["args"]["auto_lr_find"]:
+ utils.auto_find_lr(trainer, model, datamodule, loggers)
+
# Train the model
trainer.fit(model=model, datamodule=datamodule)