update progress
This commit is contained in:
1 parent
392552a5aa
commit
f46f380261
9 files changed
+291
-320
No files matched your search
@@ -1,10 +1,4 @@
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||
from pytorch_lightning import Callback
|
||||
import pytorch_lightning.callbacks
|
||||
from shutil import copy
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
|
||||
|
||||
class ExampleCallback(Callback):
|
||||
@@ -21,56 +15,6 @@ class ExampleCallback(Callback):
|
||||
print('Do something when training ends.')
|
||||
|
||||
|
||||
class SaveOnnxModelToWandbCallback(Callback):
|
||||
"""
|
||||
Save model in .onnx format and upload to wandb.
|
||||
Might crash since not all models are compatible with onnx.
|
||||
"""
|
||||
def __init__(self, datamodule, wandb_save_dir):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
x, y = first_batch
|
||||
self.dummy_input = x
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
|
||||
def save_onnx_model(self, pl_module):
|
||||
file_path = os.path.join(self.wandb_save_dir, "model.onnx")
|
||||
pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
|
||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(Callback):
|
||||
"""
|
||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||
"""
|
||||
def __init__(self, datamodule, num_samples=8):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
self.imgs, self.labels = first_batch
|
||||
self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
|
||||
self.ready = True
|
||||
|
||||
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_epoch_end(self, trainer, pl_module):
|
||||
if self.ready:
|
||||
imgs = self.imgs.to(device=pl_module.device)
|
||||
logits = pl_module(imgs)
|
||||
preds = torch.argmax(logits, -1)
|
||||
trainer.logger.experiment.log({f"img_examples": [
|
||||
wandb.Image(
|
||||
x,
|
||||
caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
|
||||
) for x, pred, y in zip(imgs, preds, self.labels)
|
||||
]}, commit=False)
|
||||
|
||||
|
||||
class UnfreezeModelCallback(Callback):
|
||||
"""
|
||||
Unfreeze model after a few epochs.
|
||||
@@ -82,147 +26,3 @@ class UnfreezeModelCallback(Callback):
|
||||
if trainer.current_epoch == self.wait_epochs:
|
||||
for param in pl_module.model.model.parameters():
|
||||
param.requires_grad = True
|
||||
|
||||
|
||||
class MetricsHeatmapLoggerCallback(Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self, class_names):
|
||||
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
|
||||
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:
|
||||
self.preds = torch.cat(self.preds)
|
||||
self.targets = torch.cat(self.targets)
|
||||
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)
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"f1_p_r_heatmap_{trainer.current_epoch}": 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 ConfusionMatrixLoggerCallback(Callback):
|
||||
"""
|
||||
Generate Confusion Matrix.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self, class_names):
|
||||
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
|
||||
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:
|
||||
self.preds = torch.cat(self.preds).tolist()
|
||||
self.targets = torch.cat(self.targets).tolist()
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
||||
self.preds,
|
||||
self.targets,
|
||||
class_names=self.class_names)
|
||||
}, commit=False)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
|
||||
|
||||
class SaveCodeToWandbCallback(Callback):
|
||||
"""
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
"""
|
||||
def __init__(self, base_dir, wandb_save_dir, run_config):
|
||||
self.base_dir = base_dir
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
self.model_folder = run_config["model"]["model_folder"]
|
||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||
"template_utils/callbacks.py",
|
||||
"template_utils/initializers.py",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
"run_configs.yaml",
|
||||
]
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Upload files when all validation sanity checks end."""
|
||||
# upload additional files
|
||||
for file in self.additional_files_to_be_saved:
|
||||
src_path = os.path.join(self.base_dir, file)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", file)
|
||||
|
||||
path, filename = os.path.split(dst_path)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
copy(src_path, dst_path)
|
||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
||||
|
||||
# upload model files
|
||||
for filename in os.listdir(os.path.join(self.base_dir, "models", self.model_folder)):
|
||||
|
||||
if filename.endswith('.py'):
|
||||
src_path = os.path.join(self.base_dir, "models", self.model_folder, filename)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "models", self.model_folder, filename)
|
||||
|
||||
path, filename = os.path.split(dst_path)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
copy(src_path, dst_path)
|
||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
||||
|
||||
# upload datamodule files
|
||||
for filename in os.listdir(os.path.join(self.base_dir, "datamodules", self.datamodule_folder)):
|
||||
|
||||
if filename.endswith('.py'):
|
||||
src_path = os.path.join(self.base_dir, "datamodules", self.datamodule_folder, filename)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "datamodules", self.datamodule_folder, filename)
|
||||
|
||||
path, filename = os.path.split(dst_path)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
copy(src_path, dst_path)
|
||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
||||
@@ -42,7 +42,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
return model
|
||||
|
||||
|
||||
def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> pl.LightningDataModule:
|
||||
def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl.LightningDataModule:
|
||||
"""
|
||||
Load LightningDataModule from path specified in run config.
|
||||
"""
|
||||
@@ -54,10 +54,8 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p
|
||||
datamodule_path = os.path.join(base_dir, datamodule_path)
|
||||
assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}"
|
||||
|
||||
if not os.path.isabs(data_path):
|
||||
datamodule_config["hparams"]["data_dir"] = os.path.join(base_dir, data_path)
|
||||
else:
|
||||
datamodule_config["hparams"]["data_dir"] = data_path
|
||||
if not os.path.isabs(data_dir):
|
||||
data_dir = os.path.join(base_dir, data_dir)
|
||||
|
||||
spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path)
|
||||
lightning_module = importlib.util.module_from_spec(spec)
|
||||
@@ -71,7 +69,7 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p
|
||||
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||
f"specified datamodule class {datamodule_class} is not a LightningDataModule"
|
||||
|
||||
datamodule = DataModule(hparams=datamodule_config["hparams"])
|
||||
datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"])
|
||||
datamodule.prepare_data()
|
||||
datamodule.setup()
|
||||
|
||||
@@ -81,7 +79,8 @@ def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> p
|
||||
def init_trainer(project_config: dict,
|
||||
run_config: dict,
|
||||
callbacks: List[pl.Callback],
|
||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||
loggers: List[pl.loggers.LightningLoggerBase],
|
||||
base_dir: str) -> pl.Trainer:
|
||||
"""
|
||||
Initialize PyTorch Lightning Trainer.
|
||||
"""
|
||||
@@ -115,10 +114,10 @@ def init_trainer(project_config: dict,
|
||||
num_sanity_val_steps=3,
|
||||
|
||||
# default log dir if no logger is found
|
||||
default_root_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs/lightning_logs"),
|
||||
default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"),
|
||||
|
||||
# insert all other trainer parameters specified in run config
|
||||
**run_config["trainer"]
|
||||
# insert all other trainer args specified in run config
|
||||
**run_config["trainer"]["args"]
|
||||
)
|
||||
|
||||
return trainer
|
||||
@@ -132,8 +131,10 @@ def init_callbacks(project_config: dict,
|
||||
Initialize default callbacks and callbacks specified in run config.
|
||||
"""
|
||||
|
||||
default_callbacks = project_config["default_callbacks"]
|
||||
run_callbacks = run_config["callbacks"]
|
||||
default_callbacks = project_config.get("default_callbacks", {})
|
||||
run_callbacks = run_config.get("callbacks", {})
|
||||
|
||||
print(default_callbacks)
|
||||
|
||||
callbacks = []
|
||||
|
||||
@@ -159,7 +160,7 @@ def init_callbacks(project_config: dict,
|
||||
|
||||
def init_loggers(project_config: dict,
|
||||
run_config: dict,
|
||||
lit_model: pl.LightningModule,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
|
||||
@@ -212,11 +213,11 @@ def init_wandb_logger(project_config: dict,
|
||||
|
||||
if hasattr(lit_model, 'model'):
|
||||
wandb_logger.watch(lit_model.model, log=None)
|
||||
wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__})
|
||||
else:
|
||||
wandb_logger.watch(lit_model, log=None)
|
||||
|
||||
wandb_logger.log_hyperparams({
|
||||
"model": lit_model.model.__class__.__name__ if hasattr(lit_model, 'model') else None,
|
||||
"optimizer": lit_model.configure_optimizers().__class__.__name__,
|
||||
"train_size": len(datamodule.data_train)
|
||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
from pytorch_lightning import Callback
|
||||
from shutil import copy
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
|
||||
|
||||
class SaveOnnxModelToWandbCallback(Callback):
|
||||
"""
|
||||
Save model in .onnx format and upload to wandb.
|
||||
Might crash since not all models are compatible with onnx.
|
||||
"""
|
||||
def __init__(self, datamodule, wandb_save_dir):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
x, y = first_batch
|
||||
self.dummy_input = x
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
|
||||
def on_train_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
|
||||
def save_onnx_model(self, pl_module):
|
||||
file_path = os.path.join(self.wandb_save_dir, "model.onnx")
|
||||
pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
|
||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(Callback):
|
||||
"""
|
||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||
"""
|
||||
def __init__(self, datamodule, num_samples=8):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
self.imgs, self.labels = first_batch
|
||||
self.imgs, self.labels = self.imgs[:num_samples], self.labels[:num_samples]
|
||||
self.ready = True
|
||||
|
||||
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_epoch_end(self, trainer, pl_module):
|
||||
if self.ready:
|
||||
imgs = self.imgs.to(device=pl_module.device)
|
||||
logits = pl_module(imgs)
|
||||
preds = torch.argmax(logits, -1)
|
||||
trainer.logger.experiment.log({f"img_examples": [
|
||||
wandb.Image(
|
||||
x,
|
||||
caption=f"Epoch: {trainer.current_epoch} Pred:{pred}, Label:{y}"
|
||||
) for x, pred, y in zip(imgs, preds, self.labels)
|
||||
]}, commit=False)
|
||||
|
||||
|
||||
class MetricsHeatmapLoggerCallback(Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self, class_names):
|
||||
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
|
||||
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:
|
||||
self.preds = torch.cat(self.preds)
|
||||
self.targets = torch.cat(self.targets)
|
||||
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)
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"f1_p_r_heatmap_{trainer.current_epoch}_{trainer.logger.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 ConfusionMatrixLoggerCallback(Callback):
|
||||
"""
|
||||
Generate Confusion Matrix.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self, class_names):
|
||||
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
|
||||
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:
|
||||
self.preds = torch.cat(self.preds).tolist()
|
||||
self.targets = torch.cat(self.targets).tolist()
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
||||
self.preds,
|
||||
self.targets,
|
||||
class_names=self.class_names)
|
||||
}, commit=False)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
|
||||
|
||||
class SaveCodeToWandbCallback(Callback):
|
||||
"""
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
"""
|
||||
def __init__(self, base_dir, wandb_save_dir, run_config):
|
||||
self.base_dir = base_dir
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
self.model_folder = run_config["model"]["model_folder"]
|
||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||
"template_utils/callbacks.py",
|
||||
"template_utils/initializers.py",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
"run_configs.yaml",
|
||||
]
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Upload files when all validation sanity checks end."""
|
||||
# upload additional files
|
||||
pass
|
||||
Reference in new issue
Block a user