callbacks work
This commit is contained in:
1 parent
23e9c4fecf
commit
f75d2a83ef
5 files changed
+59
-28
No files matched your search
@@ -30,11 +30,11 @@ The directory structure of new project looks like this:
|
|||||||
│ │
|
│ │
|
||||||
│ ├── notebooks <- Jupyter notebooks
|
│ ├── notebooks <- Jupyter notebooks
|
||||||
│ │
|
│ │
|
||||||
│ ├── utils <- Different utilities
|
│ ├── template_utils <- Different utilities
|
||||||
│ │ ├── callbacks.py <- Useful training callbacks
|
│ │ ├── callbacks.py <- Useful training callbacks
|
||||||
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
|
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
|
||||||
│ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other
|
│ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other
|
||||||
│ │ ├── init_utils.py <- Useful initializers
|
│ │ ├── initializers.py <- Useful initializers
|
||||||
│ │ └── predict_example.py <- Example of inference with trained model
|
│ │ └── predict_example.py <- Example of inference with trained model
|
||||||
│ │
|
│ │
|
||||||
│ ├── datamodules <- All your datamodules should be located here!
|
│ ├── datamodules <- All your datamodules should be located here!
|
||||||
|
|||||||
@@ -40,7 +40,7 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
|||||||
limit_train_batches: 0.8 # train only on 80% of training data
|
limit_train_batches: 0.8 # train only on 80% of training data
|
||||||
limit_val_batches: 1.0 # validate on 100% of validation data
|
limit_val_batches: 1.0 # validate on 100% of validation data
|
||||||
limit_test_batches: 1.0 # test on 100% of test data
|
limit_test_batches: 1.0 # test on 100% of test data
|
||||||
val_check_interval: 2 # perform validation every 2 epochs
|
val_check_interval: 0.5 # perform twice per epoch
|
||||||
model:
|
model:
|
||||||
load_from:
|
load_from:
|
||||||
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||||
@@ -80,6 +80,8 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
|||||||
mode: "max"
|
mode: "max"
|
||||||
ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py
|
ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py
|
||||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||||
|
MetricsHeatmapLoggerCallback: # some custom callback class from template_utils/callbacks.py
|
||||||
|
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||||
resume_training:
|
resume_training:
|
||||||
checkpoint_path: None # path to your checkpoint
|
checkpoint_path: None # path to your checkpoint
|
||||||
wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
|
wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
|
||||||
@@ -9,6 +9,7 @@ import importlib.util
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
|
from pytorch_lightning import callbacks as lightning_callbacks
|
||||||
from template_utils import callbacks as custom_callbacks
|
from template_utils import callbacks as custom_callbacks
|
||||||
from template_utils import wandb_callbacks
|
from template_utils import wandb_callbacks
|
||||||
|
|
||||||
@@ -141,7 +142,8 @@ def init_trainer(project_config: dict,
|
|||||||
|
|
||||||
def init_callbacks(project_config: dict,
|
def init_callbacks(project_config: dict,
|
||||||
run_config: dict,
|
run_config: dict,
|
||||||
use_wandb: bool) -> List[pl.Callback]:
|
use_wandb: bool,
|
||||||
|
base_dir: str) -> List[pl.Callback]:
|
||||||
"""
|
"""
|
||||||
Initialize default callbacks and callbacks specified in run config.
|
Initialize default callbacks and callbacks specified in run config.
|
||||||
"""
|
"""
|
||||||
@@ -149,26 +151,40 @@ def init_callbacks(project_config: dict,
|
|||||||
default_callbacks = project_config.get("default_callbacks", {})
|
default_callbacks = project_config.get("default_callbacks", {})
|
||||||
run_callbacks = run_config.get("callbacks", {})
|
run_callbacks = run_config.get("callbacks", {})
|
||||||
|
|
||||||
# print(default_callbacks)
|
# namespaces in which callbacks will be searched for
|
||||||
|
namespaces = [
|
||||||
|
lightning_callbacks,
|
||||||
|
custom_callbacks,
|
||||||
|
wandb_callbacks,
|
||||||
|
]
|
||||||
|
|
||||||
callbacks = []
|
callbacks = []
|
||||||
|
|
||||||
# for callback_config in default_callbacks:
|
all_callback_configs = {}
|
||||||
# callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
for callback_config in default_callbacks:
|
||||||
# callbacks.append(callback_class(**callback_config["args"]))
|
all_callback_configs[callback_config] = default_callbacks[callback_config]
|
||||||
#
|
for callback_config in run_callbacks:
|
||||||
# for callback_config in run_callbacks:
|
all_callback_configs[callback_config] = run_callbacks[callback_config]
|
||||||
# callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
|
||||||
# callbacks.append(callback_class(**callback_config["args"]))
|
for callback_config in all_callback_configs:
|
||||||
#
|
found = False
|
||||||
# if use_wandb:
|
for namespace in namespaces:
|
||||||
# callbacks.append(
|
if hasattr(namespace, callback_config):
|
||||||
# wandb_callbacks.SaveCodeToWandbCallback(
|
callback_class = getattr(namespace, callback_config)
|
||||||
# base_dir=os.path.dirname(os.path.dirname(__file__)),
|
callbacks.append(callback_class(**all_callback_configs[callback_config]))
|
||||||
# wandb_save_dir=project_config["logs_dir"],
|
found = True
|
||||||
# run_config=run_config
|
break
|
||||||
# )
|
if not found:
|
||||||
# )
|
raise ModuleNotFoundError(f"Callback '{callback_config}' not found.")
|
||||||
|
|
||||||
|
if use_wandb:
|
||||||
|
callbacks.append(
|
||||||
|
wandb_callbacks.SaveCodeToWandbCallback(
|
||||||
|
base_dir=base_dir,
|
||||||
|
wandb_save_dir=project_config["logs_dir"],
|
||||||
|
run_config=run_config
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||||
|
from pytorch_lightning.loggers import WandbLogger
|
||||||
|
from wandb.sdk.wandb_run import Run as wandb_run
|
||||||
from pytorch_lightning import Callback
|
from pytorch_lightning import Callback
|
||||||
from shutil import copy
|
from shutil import copy
|
||||||
import torch
|
import torch
|
||||||
@@ -88,8 +90,13 @@ class MetricsHeatmapLoggerCallback(Callback):
|
|||||||
r = recall_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)
|
p = precision_score(self.preds, self.targets, average=None)
|
||||||
|
|
||||||
trainer.logger.experiment.log({
|
logger = None
|
||||||
f"f1_p_r_heatmap_{trainer.current_epoch}_{trainer.logger.id}": wandb.plots.HeatMap(
|
for some_logger in trainer.logger.experiment:
|
||||||
|
if isinstance(some_logger, wandb_run):
|
||||||
|
logger = some_logger
|
||||||
|
|
||||||
|
logger.log({
|
||||||
|
f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap(
|
||||||
x_labels=self.class_names,
|
x_labels=self.class_names,
|
||||||
y_labels=["f1", "precision", "recall"],
|
y_labels=["f1", "precision", "recall"],
|
||||||
matrix_values=[f1, p, r],
|
matrix_values=[f1, p, r],
|
||||||
@@ -129,7 +136,12 @@ class ConfusionMatrixLoggerCallback(Callback):
|
|||||||
self.preds = torch.cat(self.preds).tolist()
|
self.preds = torch.cat(self.preds).tolist()
|
||||||
self.targets = torch.cat(self.targets).tolist()
|
self.targets = torch.cat(self.targets).tolist()
|
||||||
|
|
||||||
trainer.logger.experiment.log({
|
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}": wandb.plot.confusion_matrix(
|
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
||||||
self.preds,
|
self.preds,
|
||||||
self.targets,
|
self.targets,
|
||||||
@@ -147,8 +159,8 @@ class SaveCodeToWandbCallback(Callback):
|
|||||||
def __init__(self, base_dir, wandb_save_dir, run_config):
|
def __init__(self, base_dir, wandb_save_dir, run_config):
|
||||||
self.base_dir = base_dir
|
self.base_dir = base_dir
|
||||||
self.wandb_save_dir = wandb_save_dir
|
self.wandb_save_dir = wandb_save_dir
|
||||||
self.model_folder = run_config["model"]["model_folder"]
|
self.model_folder = run_config["model"]["load_from"]["model_path"]
|
||||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
|
||||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||||
"template_utils/callbacks.py",
|
"template_utils/callbacks.py",
|
||||||
"template_utils/initializers.py",
|
"template_utils/initializers.py",
|
||||||
|
|||||||
+3
-2
@@ -53,7 +53,8 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
|||||||
callbacks: List[Callback] = init_callbacks(
|
callbacks: List[Callback] = init_callbacks(
|
||||||
project_config=project_config,
|
project_config=project_config,
|
||||||
run_config=run_config,
|
run_config=run_config,
|
||||||
use_wandb=use_wandb
|
use_wandb=use_wandb,
|
||||||
|
base_dir=BASE_DIR
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers ⚡
|
# Init PyTorch Lightning loggers ⚡
|
||||||
@@ -96,7 +97,7 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str,
|
|||||||
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
||||||
|
|
||||||
print("EXECUTING RUN:", run_config_name)
|
print("EXECUTING RUN:", run_config_name)
|
||||||
pprint.pprint(run_config, sort_dicts=False)
|
# pprint.pprint(run_config, sort_dicts=False)
|
||||||
print()
|
print()
|
||||||
|
|
||||||
# Train model
|
# Train model
|
||||||
|
|||||||
Reference in new issue
Block a user