start redesigning project structure for version 4.0

This commit is contained in:
hobogalaxy committed 2020-12-29 01:48:44 +01:00
1 parent 42652e3752
commit fa8b9ecc16
18 files changed
+140 -130

No files matched your search

-28
View File
@@ -1,28 +0,0 @@
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 model 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
+7 -8
View File
@@ -1,5 +1,5 @@
# pytorch lightning imports
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.profiler import SimpleProfiler
import pytorch_lightning as pl
@@ -10,8 +10,7 @@ import os
# template utils imports
from pytorch_lightning import callbacks as lightning_callbacks
from template_utils import callbacks as custom_callbacks
from template_utils import wandb_callbacks
from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks
def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]:
@@ -24,7 +23,7 @@ def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str
os.path.normpath(os.path.join(base_dir, project_config["data_dir"]))
if not os.path.isabs(project_config["logs_dir"]):
project_config["logs_dir"] =\
project_config["logs_dir"] = \
os.path.normpath(os.path.join(base_dir, project_config["logs_dir"]))
if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
@@ -112,7 +111,7 @@ def init_trainer(project_config: dict,
# experiment logging
logger=loggers,
# useful callbacks
# useful lightning_callbacks
callbacks=callbacks,
# resume training from checkpoint if it was set in the run config
@@ -145,13 +144,13 @@ def init_callbacks(project_config: dict,
use_wandb: bool,
base_dir: str) -> List[pl.Callback]:
"""
Initialize default callbacks and callbacks specified in run config.
Initialize default lightning_callbacks and lightning_callbacks specified in run config.
"""
default_callbacks = project_config.get("default_callbacks", {})
run_callbacks = run_config.get("callbacks", {})
run_callbacks = run_config.get("lightning_callbacks", {})
# namespaces in which callbacks will be searched for
# namespaces in which lightning_callbacks will be searched for
namespaces = [
lightning_callbacks,
custom_callbacks,
-39
View File
@@ -1,39 +0,0 @@
from datamodules.mnist_datamodule import transforms
from PIL import Image
# the LitModel you import should be the same as the one you used for training!
from models.simple_mnist_classifier.lightning_module import LitModel
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.
Model used in lightning_module.py should be the same as during training!!!
"""
CKPT_PATH = "epoch=0.ckpt"
# load model from checkpoint
trained_model = LitModel.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") # for monochromatic conversion
# img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion
# preprocess
img = 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()
-175
View File
@@ -1,175 +0,0 @@
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 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 ImagePredictionWandbLoggerCallback(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 MetricsHeatmapWandbLoggerCallback(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)
logger = None
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,
y_labels=["f1", "precision", "recall"],
matrix_values=[f1, p, r],
show_text=True,
)}, commit=False)
self.preds = []
self.targets = []
class ConfusionMatrixWandbLoggerCallback(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()
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(
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"]["load_from"]["model_path"]
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
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