start remaking project

This commit is contained in:
hobogalaxy committed 2020-12-09 21:47:31 +01:00
1 parent 06e479d9ff
commit 392552a5aa
14 files changed
+409 -273

No files matched your search

+228
View File
@@ -0,0 +1,228 @@
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):
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 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.
"""
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
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
@@ -0,0 +1,42 @@
# THIS FILE WILL EXECUTE ALL RUNS SPECIFIED IN run_configs.yaml ONE AFTER THE OTHER
# YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS
from argparse import ArgumentParser
from train import train
import wandb
import yaml
import os
def main(project_config_path, run_configs_path):
with open(project_config_path, "r") as ymlfile:
project_config = yaml.load(ymlfile, Loader=yaml.FullLoader)
with open(run_configs_path, "r") as ymlfile:
run_configs = yaml.load(ymlfile, Loader=yaml.FullLoader)
# EXECUTE ALL RUNS ONE AFTER THE OTHER
for conf_name in run_configs:
print()
print("EXECUTING RUN:", conf_name)
print("CONFIG:")
for section in run_configs[conf_name]:
print(" " + section + ":")
for key in run_configs[conf_name][section]:
print(" " + key + ":", run_configs[conf_name][section][key])
print()
train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
wandb.finish()
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-p", "--project_config_path", type=str,
default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "project_config.yaml"))
parser.add_argument("-r", "--run_configs_path", type=str,
default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "run_configs.yaml"))
args = parser.parse_args()
main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path)
+31
View File
@@ -0,0 +1,31 @@
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
import wandb
import train
# Choose which run config to optimize
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1"
# Load configs
project_config = train.load_config("project_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"].keys():
run_config["trainer"][key] = value
elif key in run_config["model"].keys():
run_config["model"][key] = value
elif key in run_config["dataset"].keys():
run_config["dataset"][key] = value
# Execute run
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
+238
View File
@@ -0,0 +1,238 @@
# pytorch lightning imports
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
from pytorch_lightning.profiler import SimpleProfiler
import pytorch_lightning as pl
# normal imports
from typing import List
import importlib.util
import os
# template utils imports
import template_utils.callbacks
def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
"""
Load LightningModule from path specified in run config.
"""
model_path = model_config["load_from"]["model_path"]
model_class = model_config["load_from"]["model_class"]
if not os.path.isabs(model_path):
model_path = os.path.join(base_dir, model_path)
assert os.path.isfile(model_path), f"incorrect model path: {model_path}"
spec = importlib.util.spec_from_file_location("lightning_model", model_path)
lightning_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lightning_module)
assert hasattr(lightning_module, model_class), \
f"model class {model_class} doesn't exists in file {model_path}"
LitModel = getattr(lightning_module, model_class)
assert issubclass(LitModel, pl.LightningModule), \
f"specified model class {model_class} is not a LightningModule"
model = LitModel(hparams=model_config["hparams"])
return model
def init_datamodule(datamodule_config: dict, data_path: str, base_dir: str) -> pl.LightningDataModule:
"""
Load LightningDataModule from path specified in run config.
"""
datamodule_path = datamodule_config["load_from"]["datamodule_path"]
datamodule_class = datamodule_config["load_from"]["datamodule_class"]
if not os.path.isabs(datamodule_path):
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
spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path)
lightning_module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lightning_module)
assert hasattr(lightning_module, datamodule_class), \
f"datamodule class {datamodule_class} doesn't exists in file {datamodule_path}"
DataModule = getattr(lightning_module, datamodule_class)
assert issubclass(DataModule, pl.LightningDataModule), \
f"specified datamodule class {datamodule_class} is not a LightningDataModule"
datamodule = DataModule(hparams=datamodule_config["hparams"])
datamodule.prepare_data()
datamodule.setup()
return datamodule
def init_trainer(project_config: dict,
run_config: dict,
callbacks: List[pl.Callback],
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
"""
Initialize PyTorch Lightning Trainer.
"""
# Get path to checkpoint that you want to resume with if it was set in the run config
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
trainer = pl.Trainer(
# whether to use gpu and how many
gpus=project_config["num_of_gpus"],
# experiment logging
logger=loggers,
# useful callbacks
callbacks=callbacks,
# resume training from checkpoint if it was set in the run config
resume_from_checkpoint=resume_from_checkpoint
if resume_from_checkpoint != "None"
and resume_from_checkpoint != "False"
and resume_from_checkpoint is not False
else None,
# print related
progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
weights_summary=project_config["printing"]["weights_summary"],
# number of validation sanity checks
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"),
# insert all other trainer parameters specified in run config
**run_config["trainer"]
)
return trainer
def init_callbacks(project_config: dict,
run_config: dict,
use_wandb: bool,
base_dir: str) -> List[pl.Callback]:
"""
Initialize default callbacks and callbacks specified in run config.
"""
default_callbacks = project_config["default_callbacks"]
run_callbacks = run_config["callbacks"]
callbacks = []
for callback_config in default_callbacks:
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
callbacks.append(callback_class(**callback_config["args"]))
for callback_config in run_callbacks:
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
callbacks.append(callback_class(**callback_config["args"]))
if use_wandb:
callbacks.append(
template_utils.callbacks.SaveCodeToWandbCallback(
base_dir=os.path.dirname(os.path.dirname(__file__)),
wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"),
run_config=run_config
)
)
return callbacks
def init_loggers(project_config: dict,
run_config: dict,
lit_model: pl.LightningModule,
datamodule: pl.LightningDataModule,
use_wandb: bool,
base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
"""
Initialize loggers.
"""
return []
def init_wandb_logger(project_config: dict,
run_config: dict,
lit_model: pl.LightningModule,
datamodule: pl.LightningDataModule,
log_path: str = "logs/") -> pl.loggers.WandbLogger:
"""
Initialize Weights&Biases logger.
"""
# with this line wandb will throw an error if the run to be resumed does not exist yet
# instead of auto-creating a new run
os.environ["WANDB_RESUME"] = "must"
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
wandb_logger = WandbLogger(
project=project_config["loggers"]["wandb"]["project"],
entity=project_config["loggers"]["wandb"]["entity"],
log_model=project_config["loggers"]["wandb"]["log_model"],
offline=project_config["loggers"]["wandb"]["offline"],
group=run_config.get("wandb", {}).get("group", None),
job_type=run_config.get("wandb", {}).get("job_type", "train"),
tags=run_config.get("wandb", {}).get("tags", []),
notes=run_config.get("wandb", {}).get("notes", ""),
# resume run only if ckpt was set in the run config
id=wandb_run_id
if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None
and resume_from_checkpoint is not False and wandb_run_id is not False
else None,
save_dir=log_path,
save_code=False
)
if not os.path.exists(log_path):
os.makedirs(log_path)
if hasattr(lit_model, 'model'):
wandb_logger.watch(lit_model.model, log=None)
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,
"val_size": len(datamodule.data_val)
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
"test_size": len(datamodule.data_test)
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
})
wandb_logger.log_hyperparams(run_config["trainer"])
wandb_logger.log_hyperparams(run_config["model"])
wandb_logger.log_hyperparams(run_config["dataset"])
return wandb_logger
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
"""Initialize tensorboard logger"""
# TODO
return None
+39
View File
@@ -0,0 +1,39 @@
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()