BIG clean up and refactoring

This commit is contained in:
hobogalaxy committed 2020-11-27 20:23:05 +01:00
1 parent a905c0b094
commit e7a579d720
24 files changed
+369 -597

No files matched your search

+182
View File
@@ -0,0 +1,182 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import pytorch_lightning as pl
from shutil import copy
import inspect
import torch
import wandb
import os
class ExampleCallback(pl.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(pl.Callback):
"""
Save model in .onnx format and upload to wandb.
Might crash since not all models are compatible with onnx.
"""
def __init__(self, datamodule, save_dir):
first_batch = next(iter(datamodule.train_dataloader()))
x, y = first_batch
self.dummy_input = x
self.save_dir = 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.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.save_dir)
class ImagePredictionLoggerCallback(pl.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(pl.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(pl.Callback):
"""
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
Expects validation step to return predictions and targets.
Works only for single label classification!
"""
def __init__(self):
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=[str(i) for i in range(len(f1))], # class names can be hardcoded here
y_labels=["f1", "precision", "recall"],
matrix_values=[f1, p, r],
show_text=True,
)}, commit=False)
self.preds = []
self.targets = []
class SaveCodeToWandbCallback(pl.Callback):
"""
Upload specified code files to wandb at the beginning of the run.
"""
def __init__(self, wandb_save_dir, lit_model, datamodule):
self.wandb_save_dir = wandb_save_dir
self.additional_files_to_be_saved = [
"utils/callbacks.py",
"utils/init_utils.py",
"train.py",
"project_config.yaml",
"run_configs.yaml",
]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
self.datamodule_path = os.path.dirname(inspect.getfile(datamodule.__class__))
def on_sanity_check_end(self, trainer, pl_module):
"""Upload files when all validation sanity checks end."""
for file in self.additional_files_to_be_saved:
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(file, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
for filename in os.listdir(self.model_path):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path),
filename)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
file_path = os.path.join(self.model_path, filename)
copy(file_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
for filename in os.listdir(self.datamodule_path):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", os.path.basename(
self.datamodule_path), filename)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
file_path = os.path.join(self.datamodule_path, filename)
copy(file_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
+30
View File
@@ -0,0 +1,30 @@
# 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)
+76
View File
@@ -0,0 +1,76 @@
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
import importlib
import os
def init_lit_model(hparams):
"""Load LitModel from folder specified in run config."""
module_path = "models." + hparams["model_folder"] + ".lightning_module"
lit_model = importlib.import_module(module_path).LitModel(hparams=hparams)
return lit_model
def init_data_module(hparams):
"""Load DataModule from folder specified in run config."""
module_path = "data_modules." + hparams["datamodule_folder"] + ".datamodule"
datamodule = importlib.import_module(module_path).DataModule(hparams=hparams)
datamodule.prepare_data()
datamodule.setup()
return datamodule
def init_main_callbacks(project_config):
"""Initialize EarlyStopping callback and ModelCheckpoint callback."""
callbacks = [
EarlyStopping(
monitor=project_config["callbacks"]["early_stop"]["monitor"],
patience=project_config["callbacks"]["early_stop"]["patience"],
mode=project_config["callbacks"]["early_stop"]["mode"],
),
ModelCheckpoint(
monitor=project_config["callbacks"]["checkpoint"]["monitor"],
save_top_k=project_config["callbacks"]["checkpoint"]["save_top_k"],
mode=project_config["callbacks"]["checkpoint"]["mode"],
save_last=project_config["callbacks"]["checkpoint"]["save_last"],
)
]
return callbacks
def init_wandb_logger(config, run_config, lit_model, datamodule):
"""Initialize Weights&Biases logger."""
wandb_logger = WandbLogger(
project=config["loggers"]["wandb"]["project"],
job_type=config["loggers"]["wandb"]["job_type"],
tags=config["loggers"]["wandb"]["tags"],
entity=config["loggers"]["wandb"]["team"],
id=config["resume_training"]["wandb"]["wandb_run_id"]
if config["resume_training"]["wandb"]["resume_wandb_run"] else None,
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
save_dir="logs/",
save_code=False
)
if not os.path.exists("logs/"):
os.mkdir("logs/")
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_name": lit_model.model.__class__.__name__,
"optimizer": lit_model.configure_optimizers().__class__.__name__,
"train_size": len(datamodule.data_train) if datamodule.data_train is not None else 0,
"val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0,
"test_size": len(datamodule.data_test) if datamodule.data_train 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_loggger():
"""TODO"""
return None
-35
View File
@@ -1,35 +0,0 @@
from models.transfer_learning_img_classifier.lightning_module import LitModel
from data_modules import transforms
from PIL import Image
def predict():
"""
Loads model from checkpoint.
Model used in lightning_module.py and declaration of that model in models.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("../../example_img.png").convert("RGB")
# preprocess
img = transforms.imagenet_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()
+37
View File
@@ -0,0 +1,37 @@
from models.simple_mnist_classifier.lightning_module import LitModel
from data_modules.mnist_digits_datamodule import transforms
from PIL import Image
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()
-76
View File
@@ -1,76 +0,0 @@
import wandb
import os
def upload_artifact():
FOLDER_TO_UPLOAD_PATH = "../data/skyhacks"
ARTIFACT_NAME = "skyhacks-dataset"
TYPE = "dataset" # type can be anything but we recommend sticking to "dataset" / "model" / "result"
WANDB_PROJECT = "hackathon_template_test"
WANDB_TEAM = "kino"
# Set project which will own the artifact
os.mkdir("../logs") if not os.path.exists("../logs") else None
run = wandb.init(
project=WANDB_PROJECT,
entity=WANDB_TEAM,
dir="../logs",
name="artifact_upload",
job_type="artifact"
)
# Recursively add all files from a directory
artifact = wandb.Artifact(
name=ARTIFACT_NAME,
type=TYPE
)
artifact.add_dir(FOLDER_TO_UPLOAD_PATH)
# artifact.add_file(MODEL_PATH)
# Upload artifact
run.log_artifact(artifact, aliases=["latest"])
print("Files are being uploaded now...")
def download_artifact():
SAVE_DIR = "../data/skyhacks"
ARTIFACT = "kino/hackathon_template_test/skyhacks-dataset:v0"
# Choose what artifact you want to download
api = wandb.Api()
artifact = api.artifact(ARTIFACT)
# Download artifact
artifact.download(root=SAVE_DIR)
print("Files are being downloaded now...")
# TODO
# def download_model_from_wandb_run():
# """
# WARNING: This will overwrite your lightning_modules/models.py and lightning_modules/lightning_module.py files!
# """
# RUN_ID = "kino/hackathon_template_test/lx9voyom"
# MODEL_PATH = "last.ckpt"
# CODE_PATHS = [
# "code/lightning_modules/lightning_module.py",
# "code/lightning_modules/models.py"
# ]
#
# api = wandb.Api()
# run = api.run(path=RUN_ID)
#
# # download model
# run.file(MODEL_PATH).download(replace=True)
#
# # download and replace your code
# for path in CODE_PATHS:
# run.file(path).download(root="../lightning_modules/", replace=True)
if __name__ == "__main__":
upload_artifact()
# download_artifact()
# download_model_from_wandb_run()