this is slowly becoming actually useful

This commit is contained in:
hobogalaxy committed 2020-11-24 18:15:52 +01:00
1 parent d518ddb63d
commit 8628600ea3
15 files changed
+190 -176

No files matched your search

+170
View File
@@ -0,0 +1,170 @@
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):
self.wandb_save_dir = wandb_save_dir
self.additional_files_to_be_saved = [
"lightning_modules/data_modules/datamodules.py",
"lightning_modules/data_modules/datasets.py",
"lightning_modules/data_modules/transforms.py",
"lightning_modules/callbacks.py",
"lightning_modules/init_utils.py",
"train.py",
"config.yaml"
]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__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
@@ -0,0 +1,131 @@
from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST, CIFAR10
import pytorch_lightning as pl
# custom data_modules
class ExampleDataModule(pl.LightningDataModule):
"""All datamodules should look like this!"""
def __init__(self, transforms, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__()
self.transforms = transforms
self.data_dir = data_dir
self.batch_size = batch_size
self.data_split_ratio = data_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
pass
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
pass
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
class MNISTDataModule(pl.LightningDataModule):
def __init__(self, transforms, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__()
self.transforms = transforms
self.data_dir = data_dir
self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
self.data_train, self.data_val = random_split(trainset, train_val_split)
self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
class CIFAR10DataModule(pl.LightningDataModule):
def __init__(self, transforms, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__()
self.transforms = transforms
self.data_dir = data_dir
self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
CIFAR10(self.data_dir, train=True, download=True)
CIFAR10(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = CIFAR10(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
self.data_train, self.data_val = random_split(trainset, train_val_split)
self.data_test = CIFAR10(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
@@ -0,0 +1,21 @@
from torch.utils.data import Dataset
from PIL import Image
import os
class TestDatasetForImgs(Dataset):
def __init__(self, img_dir, transform):
self.transform = transform
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
def __getitem__(self, idx):
image = Image.open(self.images[idx]).convert("RGB")
if self.transform is not None:
image = self.transform(image)
return image
def __len__(self):
return len(self.images)
@@ -0,0 +1,40 @@
from torchvision import transforms
minst_train_preprocess = transforms.Compose([
transforms.ToTensor(),
])
mnist_test_preprocess = transforms.Compose([
transforms.ToTensor()
])
img_augmentation_transformations = [
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
transforms.RandomHorizontalFlip(p=0.65),
transforms.RandomRotation((-15, 15)),
transforms.ColorJitter(hue=.05, saturation=.05),
]
imagenet_train_preprocess = transforms.Compose([
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
transforms.RandomCrop(224),
transforms.ToTensor(),
transforms.RandomApply(img_augmentation_transformations, 0.8),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
imagenet_test_preprocess = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])
cifar10_train_preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.RandomHorizontalFlip(p=0.5),
])
cifar10_test_preprocess = transforms.Compose([
transforms.ToTensor(),
])
+68
View File
@@ -0,0 +1,68 @@
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from lightning_modules.data_modules import datamodules, transforms
import importlib
def init_lit_model(model_config):
module_path = "models." + model_config["model_folder_name"] + ".lightning_module"
return importlib.import_module(module_path).LitModel(hparams=model_config)
def init_datamodule(model_config):
datamodule_class = getattr(datamodules, model_config["dataset"]["class_name"])
train_transforms = getattr(transforms, model_config["dataset"]["train_transforms"])
datamodule = datamodule_class(
transforms=train_transforms,
batch_size=model_config["batch_size"],
**model_config["dataset"]
)
datamodule.prepare_data()
datamodule.setup()
return datamodule
def init_main_callbacks(config):
callbacks = [
EarlyStopping(
monitor=config["callbacks"]["early_stop"]["monitor"],
patience=config["callbacks"]["early_stop"]["patience"],
mode=config["callbacks"]["early_stop"]["mode"],
),
ModelCheckpoint(
monitor=config["callbacks"]["checkpoint"]["monitor"],
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"],
mode=config["callbacks"]["checkpoint"]["mode"],
save_last=config["callbacks"]["checkpoint"]["save_last"],
)
]
return callbacks
def init_wandb_logger(config, lit_model, datamodule):
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
)
wandb_logger.watch(lit_model.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,
})
return wandb_logger
def init_tensorboard_loggger():
"""TODO"""
return None