update progress

This commit is contained in:
hobogalaxy committed 2020-12-12 14:27:08 +01:00
1 parent 392552a5aa
commit f46f380261
9 files changed
+290 -319

No files matched your search

@@ -1,4 +1,4 @@
from torch.utils.data import DataLoader, random_split from torch.utils.data import DataLoader, ConcatDataset, random_split
from pytorch_lightning import LightningDataModule from pytorch_lightning import LightningDataModule
from torchvision.transforms import transforms from torchvision.transforms import transforms
from torchvision.datasets import MNIST from torchvision.datasets import MNIST
@@ -6,24 +6,19 @@ from torchvision.datasets import MNIST
class MNISTDataModule(LightningDataModule): class MNISTDataModule(LightningDataModule):
""" """
This is example of datamodule for MNIST digits dataset. This is example of datamodule for MNIST dataset.
All data modules should be located in separate folders with file named 'datamodule.py' containing class which
is always called 'DataModule'!
The folder name of datamodule used during training should be specified in run config and all parameters from The path to datamodule should be specified in your run config. (run_configs.yaml)
'dataset' section will be passed in 'hparams' dictionary. The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml)
All datamodules should have a structure like this one!
""" """
def __init__(self, hparams): def __init__(self, data_dir: str, hparams: dict):
super().__init__() super().__init__()
# hparams["data_dir"] is always automatically set to 'data_path' from 'project_config.yaml' self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml
self.data_dir = hparams["data_dir"]
self.batch_size = hparams.get("batch_size") or 64 self.batch_size = hparams.get("batch_size") or 64
self.train_val_split_ratio = hparams.get("train_val_split_ratio") or 0.9 self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
self.train_val_split = hparams.get("train_val_split") or None
self.num_workers = hparams.get("num_workers") or 1 self.num_workers = hparams.get("num_workers") or 1
self.pin_memory = hparams.get("pin_memory") or False self.pin_memory = hparams.get("pin_memory") or False
@@ -41,23 +36,19 @@ class MNISTDataModule(LightningDataModule):
def setup(self, stage=None): def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test.""" """Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms) 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])
if not self.train_val_split: self.data_train, self.data_val, self.data_test = random_split(dataset, self.train_val_test_split)
train_length = int(len(trainset) * self.train_val_split_ratio)
val_length = len(trainset) - train_length
self.train_val_split = [train_length, val_length]
self.data_train, self.data_val = random_split(trainset, self.train_val_split)
self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self): def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers, return DataLoader(dataset=self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory, shuffle=True) pin_memory=self.pin_memory, shuffle=True)
def val_dataloader(self): def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers, return DataLoader(dataset=self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory) pin_memory=self.pin_memory)
def test_dataloader(self): def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers, return DataLoader(dataset=self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory) pin_memory=self.pin_memory)
@@ -78,4 +78,4 @@ class LitModel(pl.LightningModule):
return loss return loss
def configure_optimizers(self): def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay) return torch.optim.Adam(self.parameters(), lr=self.hparams["lr"], weight_decay=self.hparams["weight_decay"])
+19 -21
View File
@@ -4,42 +4,40 @@ num_of_gpus: 0
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) # Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
loggers: loggers:
wandb: Weights&Biases_config:
project: "project_template_test" project: "project_template_test"
entity: "kino" entity: "kino" # change to your username or name of your team on wandb
log_model: True log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
offline: False offline: False # set True to store all logs only locally
# default callbacks initialised on every run/experiment # default callbacks initialised on every run/experiment
# you can just remove this section or certain callback if you don't want tu use it # you can just remove this section or certain callback if you don't want tu use it
# you can add here any callback class available in pytorch lightning or template_utils/callbacks.py # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py
# if you specify the same callback class also in run config then it will overwrite the one set here
# all of the callback parameters will be passed to it on initialization
default_callbacks: default_callbacks:
checkpoint: EarlyStopping: # name of PyTorch Lightning class for early stopping callback
callback_class: "ModelCheckpoint" monitor: "val_acc",
args: patience: 5,
monitor: "val_acc" mode: "max",
save_top_k: 1 ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
save_last: True monitor: "val_acc",
mode: "max" save_top_k: 1,
early_stop: save_last: True,
callback_class: "EarlyStopping" mode: "max",
args:
monitor: "val_acc"
patience: 100
mode: "max"
# configure things which are printed in terminal # configure things which are printed in terminal
printing: printing:
progress_bar_refresh_rate: 10 # refresh every 10 batches progress_bar_refresh_rate: 10 # refresh every 10 batches
weights_summary: "top" # model summary (alternatively "full") weights_summary: "top" # print model summary (alternatively "full")
profiler: False # set True to print execution time profiling after training ends profiler: False # set True to print execution time profiling after training ends
# path to data folder (either absolute or relative to placement of 'train.py' file) # path to data folder (either absolute or relative to placement of 'train.py' file)
data_path: "data/" data_dir: "data/"
# path to logs folder (either absolute or relative to placement of 'train.py' file) # path to logs folder (either absolute or relative to placement of 'train.py' file)
logs_path: "logs/" logs_dir: "logs/"
+61 -51
View File
@@ -1,42 +1,10 @@
# make sure parameters from different sections have different names # execute this run like this:
# or they will overwrite themselvess in Weights&Biases config # python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
EXAMPLE_MNIST_RUN_CONFIG: SIMPLE_CONFIG_EXAMPLE_MNIST:
seed: 1234
trainer: trainer:
args:
max_epochs: 10 max_epochs: 10
gradient_clip_val: 0.5
model:
load_from:
model_path: "models/simple_mnist_classifier/lightning_module.py"
model_class: "LitModel"
hparams:
lr: 0.001
weight_decay: 1e-5
input_size: 784 # img size is 1*28*28
output_size: 10 # there are 10 digit classes
lin1_size: 256
lin2_size: 256
lin3_size: 128
datamodule:
load_from:
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
datamodule_class: "MNISTDataModule"
hparams:
batch_size: 64
train_val_split: [50_000, 10_000]
EXAMPLE_MNIST_RUN_CONFIG_ADVANCED:
trainer:
min_epochs: 1
max_epochs: 10
gradient_clip_val: 0.5
accumulate_grad_batches: 2
fast_dev_run: False
limit_train_batches: 1.0
limit_val_batches: 1.0
limit_test_batches: 1.0
val_check_interval: 1.0
model: model:
load_from: load_from:
model_path: "models/simple_mnist_classifier/lightning_module.py" model_path: "models/simple_mnist_classifier/lightning_module.py"
@@ -54,22 +22,64 @@ EXAMPLE_MNIST_RUN_CONFIG_ADVANCED:
datamodule_path: "datamodules/mnist_datamodule/datamodule.py" datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
datamodule_class: "MNISTDataModule" datamodule_class: "MNISTDataModule"
hparams: hparams:
batch_size: 256 batch_size: 64
train_val_split: [60_000, 10_000] # use either this or 'train_val_split_ratio' train_val_test_split: [55_000, 5_000, 10_000]
# train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False # execute this run like this:
callbacks: # python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST
early_stop: ADVANCED_CONFIG_EXAMPLE_MNIST:
callback_class: "EarlyStopping" seed: 1234
trainer:
args: args:
monitor: "val_acc" min_epochs: 1 # train for at least this many epochs (denies early stopping)
patience: 5 max_epochs: 10
mode: "max" gradient_clip_val: 0.5 # gradient clipping (helps with exploding gradient issues)
wandb: accumulate_grad_batches: 2 # perform optimization step after accumulating gradient from 2 batches
fast_dev_run: False # execute 1 training, 1 validation and 1 test epoch only
limit_train_batches: 0.8 # train only on 80% of training data
limit_val_batches: 1.0 # validate on 100% of validation data
limit_test_batches: 1.0 # test on 100% of test data
val_check_interval: 2 # perform validation every 2 epochs
model:
load_from:
model_path: "models/simple_mnist_classifier/lightning_module.py"
model_class: "LitModel"
hparams: # you can add here any parameters you want and then read them in model!
lr: 0.001
weight_decay: 1e-5
input_size: 784 # img size is 1*28*28
output_size: 10 # there are 10 digit classes
lin1_size: 256
lin2_size: 256
lin3_size: 128
datamodule:
load_from:
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
datamodule_class: "MNISTDataModule"
hparams: # you can add here any parameters you want and then read them in datamodule!
batch_size: 256
train_val_test_split: [55_000, 5_000, 10_000]
num_workers: 1 # num of processes used for loading data in parallel
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
# the following sections of config are optional and can be removed:
wandb: # Weights&Biases run options
group: "" group: ""
job_type: "train"
tags: ["v2", "uwu"] tags: ["v2", "uwu"]
notes: "This is example run." notes: "This is example run."
callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
monitor: "val_acc",
patience: 5,
mode: "max",
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
monitor: "val_acc",
save_top_k: 1,
save_last: True,
mode: "max",
ConfusionMatrixLoggerCallback: # 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 checkpoint_path: None # path to your checkpoint
wandb_run_id: None wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
-200
View File
@@ -1,10 +1,4 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from pytorch_lightning import Callback from pytorch_lightning import Callback
import pytorch_lightning.callbacks
from shutil import copy
import torch
import wandb
import os
class ExampleCallback(Callback): class ExampleCallback(Callback):
@@ -21,56 +15,6 @@ class ExampleCallback(Callback):
print('Do something when training ends.') 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): class UnfreezeModelCallback(Callback):
""" """
Unfreeze model after a few epochs. Unfreeze model after a few epochs.
@@ -82,147 +26,3 @@ class UnfreezeModelCallback(Callback):
if trainer.current_epoch == self.wait_epochs: if trainer.current_epoch == self.wait_epochs:
for param in pl_module.model.model.parameters(): for param in pl_module.model.model.parameters():
param.requires_grad = True 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
+15 -14
View File
@@ -42,7 +42,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
return model 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. 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) datamodule_path = os.path.join(base_dir, datamodule_path)
assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}" assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}"
if not os.path.isabs(data_path): if not os.path.isabs(data_dir):
datamodule_config["hparams"]["data_dir"] = os.path.join(base_dir, data_path) data_dir = os.path.join(base_dir, data_dir)
else:
datamodule_config["hparams"]["data_dir"] = data_path
spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path) spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path)
lightning_module = importlib.util.module_from_spec(spec) 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), \ assert issubclass(DataModule, pl.LightningDataModule), \
f"specified datamodule class {datamodule_class} is not a 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.prepare_data()
datamodule.setup() 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, def init_trainer(project_config: dict,
run_config: dict, run_config: dict,
callbacks: List[pl.Callback], 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. Initialize PyTorch Lightning Trainer.
""" """
@@ -115,10 +114,10 @@ def init_trainer(project_config: dict,
num_sanity_val_steps=3, num_sanity_val_steps=3,
# default log dir if no logger is found # 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 # insert all other trainer args specified in run config
**run_config["trainer"] **run_config["trainer"]["args"]
) )
return trainer return trainer
@@ -132,8 +131,10 @@ def init_callbacks(project_config: dict,
Initialize default callbacks and callbacks specified in run config. Initialize default callbacks and callbacks specified in run config.
""" """
default_callbacks = project_config["default_callbacks"] default_callbacks = project_config.get("default_callbacks", {})
run_callbacks = run_config["callbacks"] run_callbacks = run_config.get("callbacks", {})
print(default_callbacks)
callbacks = [] callbacks = []
@@ -159,7 +160,7 @@ def init_callbacks(project_config: dict,
def init_loggers(project_config: dict, def init_loggers(project_config: dict,
run_config: dict, run_config: dict,
lit_model: pl.LightningModule, model: pl.LightningModule,
datamodule: pl.LightningDataModule, datamodule: pl.LightningDataModule,
use_wandb: bool, use_wandb: bool,
base_dir: str) -> List[pl.loggers.LightningLoggerBase]: base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
@@ -212,11 +213,11 @@ def init_wandb_logger(project_config: dict,
if hasattr(lit_model, 'model'): if hasattr(lit_model, 'model'):
wandb_logger.watch(lit_model.model, log=None) wandb_logger.watch(lit_model.model, log=None)
wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__})
else: else:
wandb_logger.watch(lit_model, log=None) wandb_logger.watch(lit_model, log=None)
wandb_logger.log_hyperparams({ wandb_logger.log_hyperparams({
"model": lit_model.model.__class__.__name__ if hasattr(lit_model, 'model') else None,
"optimizer": lit_model.configure_optimizers().__class__.__name__, "optimizer": lit_model.configure_optimizers().__class__.__name__,
"train_size": len(datamodule.data_train) "train_size": len(datamodule.data_train)
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0, if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
+163
View File
@@ -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
+17 -10
View File
@@ -1,4 +1,5 @@
# pytorch lightning imports # pytorch lightning imports
import torch
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
from pytorch_lightning.loggers import LightningLoggerBase from pytorch_lightning.loggers import LightningLoggerBase
@@ -18,13 +19,18 @@ from template_utils.initializers import (
) )
# Everything will be loaded relatively to placement of this file! # Everything will be loaded relatively to placement of 'train.py' file!
BASE_DIR: str = os.path.dirname(__file__) BASE_DIR: str = os.path.dirname(__file__)
def train(project_config: dict, run_config: dict, use_wandb: bool): def train(project_config: dict, run_config: dict, use_wandb: bool):
# Set global PyTorch seed
if "seed" in run_config:
torch.manual_seed(run_config["seed"])
# Init PyTorch Lightning model ⚡ # Init PyTorch Lightning model ⚡
lit_model: LightningModule = init_model( model: LightningModule = init_model(
model_config=run_config["model"], model_config=run_config["model"],
base_dir=BASE_DIR base_dir=BASE_DIR
) )
@@ -32,7 +38,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
# Init PyTorch Lightning datamodule ⚡ # Init PyTorch Lightning datamodule ⚡
datamodule: LightningDataModule = init_datamodule( datamodule: LightningDataModule = init_datamodule(
datamodule_config=run_config["datamodule"], datamodule_config=run_config["datamodule"],
data_path=project_config["data_path"], data_dir=project_config["data_dir"],
base_dir=BASE_DIR base_dir=BASE_DIR
) )
@@ -48,7 +54,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
loggers: List[LightningLoggerBase] = init_loggers( loggers: List[LightningLoggerBase] = init_loggers(
project_config=project_config, project_config=project_config,
run_config=run_config, run_config=run_config,
lit_model=lit_model, model=model,
datamodule=datamodule, datamodule=datamodule,
use_wandb=use_wandb, use_wandb=use_wandb,
base_dir=BASE_DIR base_dir=BASE_DIR
@@ -59,17 +65,18 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
project_config=project_config, project_config=project_config,
run_config=run_config, run_config=run_config,
callbacks=callbacks, callbacks=callbacks,
loggers=loggers loggers=loggers,
base_dir=BASE_DIR
) )
# Evaluate model on test set before training # Evaluate model on test set before training
# trainer.test(model=lit_model, datamodule=datamodule) # trainer.test(model=model, datamodule=datamodule)
# Train the model # Train the model
trainer.fit(model=lit_model, datamodule=datamodule) trainer.fit(model=model, datamodule=datamodule)
# Evaluate model on test set after training # Evaluate model on test set after training
# trainer.test() trainer.test()
def load_config(path): def load_config(path):
@@ -90,11 +97,11 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str,
if __name__ == "__main__": if __name__ == "__main__":
parser = ArgumentParser() parser = ArgumentParser()
parser.set_defaults(use_wandb=True)
parser.add_argument("--project_config_path", type=str, default="project_config.yaml") parser.add_argument("--project_config_path", type=str, default="project_config.yaml")
parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml")
parser.add_argument("--run_config_name", type=str, default="EXAMPLE_MNIST_RUN_CONFIG") parser.add_argument("--run_config_name", type=str, default="SIMPLE_CONFIG_EXAMPLE_MNIST")
parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') parser.add_argument("--no_wandb", dest='use_wandb', action='store_false')
parser.set_defaults(use_wandb=True)
args = parser.parse_args() args = parser.parse_args()
main(project_config_path=args.project_config_path, main(project_config_path=args.project_config_path,
+1
View File
@@ -5,3 +5,4 @@ pytorch-lightning>=1.0.8
wandb>=0.10.12 wandb>=0.10.12
PyYAML>=5.3.1 PyYAML>=5.3.1
scikit-learn>=0.23.2 scikit-learn>=0.23.2
pandas>=1.1.5