add hack_utils with artifact_tools.py and refactor project one more time

This commit is contained in:
hobogalaxy committed 2020-11-20 01:20:41 +01:00
1 parent 7c922e4ffe
commit 6761d81353
12 files changed
+337 -25

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import pytorch_lightning as pl
import seaborn
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 SaveModelOnnxCallback(pl.Callback):
"""
Save model in .onnx format.
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)
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.
"""
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 = []
+130
View File
@@ -0,0 +1,130 @@
from pl_bolts.models.self_supervised.cpc.transforms import CPCTrainTransformsImageNet128
from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST, CIFAR10
import pytorch_lightning as pl
import numpy as np
# custom
from training_modules.transforms import *
from training_modules.datasets import *
class ExampleDataModule(pl.LightningDataModule):
"""All datamodules should look like this!"""
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.split_ratio = split_ratio
self.data_train = None
self.data_val = None
self.data_test = None
# optional variables
self.input_dims = None
self.input_size = 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)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size)
class MNISTDataModule(pl.LightningDataModule):
def __init__(self, data_dir='data/mnist', batch_size=64, split_ratio=0.90):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.split_ratio = split_ratio
self.data_train = None
self.data_val = None
self.data_test = None
self.input_dims = None
self.input_size = 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=transforms.ToTensor())
train_dataset_length = int(len(trainset) * self.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=transforms.ToTensor())
self.input_dims = self.data_train[0][0].shape
self.input_size = np.prod(self.input_dims)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size)
class CIFAR10DataModule(pl.LightningDataModule):
def __init__(self, data_dir="data/cifar10", batch_size=64, split_ratio=0.90):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.split_ratio = split_ratio
self.data_train = None
self.data_val = None
self.data_test = None
self.input_dims = None
self.input_size = 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=transforms.ToTensor())
train_dataset_length = int(len(trainset) * self.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=transforms.ToTensor())
self.input_dims = self.data_train[0][0].shape
self.input_size = np.prod(self.input_dims)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size)
def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size)
def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size)
+21
View File
@@ -0,0 +1,21 @@
from torch.utils.data import Dataset
from PIL import Image
import os
class TestDataset(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,74 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from pl_bolts.models.regression import LinearRegression, LogisticRegression
from torch.nn.functional import one_hot
import torch.nn.functional as F
import pytorch_lightning as pl
# custom models
from training_modules.models import *
class LitModel(pl.LightningModule):
def __init__(self, hparams):
super().__init__()
self.save_hyperparameters(hparams)
self.model = SimpleLinearMNIST(config=self.hparams)
def forward(self, x):
return self.model(x)
# logic for a single training step
def training_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# training metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
# f1 = f1_score(preds, y, average="micro")
# self.log('train_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
return loss
# logic for a single validation step
def validation_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# validation metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
# f1 = f1_score(preds, y, average="micro")
# self.log('val_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
return preds, y
# logic for a single testing step
def test_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# test metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
# f1 = f1_score(preds, y, average="micro")
# self.log('test_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"])
+35
View File
@@ -0,0 +1,35 @@
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
import os
def get_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"]["wandb_run_id"] if config["resume"]["resume_from_ckpt"] else None,
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
save_dir="logs/"
)
os.mkdir("logs/") if not os.path.exists("logs/") else None
wandb_logger.watch(lit_model.model, log=None)
wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__,
"datamodule_name": datamodule.__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,
"input_dims": datamodule.input_dims,
"input_size": datamodule.input_size,
})
# download model from a specific wandb run
# wandb.restore('model-best.h5', run_path="kino/some_project/a1b2c3d")
return wandb_logger
def get_tensorboard_loggger():
"""TODO"""
return None
+148
View File
@@ -0,0 +1,148 @@
from pl_bolts.models.self_supervised import CPCV2
from efficientnet_pytorch import EfficientNet
import torch.nn.functional as F
from torchvision import models
from torch import nn
import torch
class SimpleLinearMNIST(nn.Module):
def __init__(self, config):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
nn.Linear(28 * 28, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin2_size"], config["lin3_size"]),
nn.BatchNorm1d(config["lin3_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin3_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
batch_size, channels, width, height = x.size()
# (b, 1, 28, 28) -> (b, 1*28*28)
x = x.view(batch_size, -1)
return self.model(x)
class EfficientNetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = EfficientNet.from_pretrained('efficientnet-b1')
for param in self.model.parameters():
param.requires_grad = False
self.model._fc = nn.Sequential(
nn.Linear(self.model._fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnet18(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnextPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnext101_32x8d(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
# this model doesn't work yet, we wait for lightning-bolts patch
# class ResnetPretrainedUnsupervised(nn.Module):
# """
# Trained without labels on Imagenet.
# Perhaps the features when trained without labels are much better for classification or other tasks.
# """
# def __init__(self, config):
# super().__init__()
#
# self.model = CPCV2(encoder='resnet18', pretrained='imagenet128').encoder
# # self.model = CPCV2(encoder='resnet18', pretrained='stl10').encoder
#
# for param in self.model.parameters():
# param.requires_grad = False
#
# self.model.fc = nn.Sequential(
# nn.Linear(self.model.fc.in_features, config["lin1_size"]),
# nn.BatchNorm1d(config["lin1_size"]),
# nn.ReLU(),
# nn.Dropout(p=0.25),
# nn.Linear(config["lin1_size"], config["lin2_size"]),
# nn.BatchNorm1d(config["lin2_size"]),
# nn.ReLU(),
# nn.Dropout(p=0.2),
# nn.Linear(config["lin2_size"], config["output_size"]),
# nn.LogSoftmax(dim=1)
# )
#
# def forward(self, x):
# return self.model(x)
+23
View File
@@ -0,0 +1,23 @@
from torchvision import transforms
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),
]
efficient_net_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]),
])
efficient_net_test_preprocess = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
])