redesign project structure
This commit is contained in:
1 parent
104688be1b
commit
0ae8995eb3
19 files changed
+287
-188
No files matched your search
@@ -1,7 +1,6 @@
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||
import pytorch_lightning as pl
|
||||
from shutil import copy, copyfile
|
||||
import seaborn
|
||||
from shutil import copy
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
@@ -88,6 +87,7 @@ 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 = []
|
||||
@@ -128,7 +128,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
|
||||
class SaveCodeToWandbCallback(pl.Callback):
|
||||
"""
|
||||
Upload specified files to wandb at the beginning of the run.
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
"""
|
||||
def __init__(self, wandb_save_dir):
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
@@ -136,12 +136,12 @@ class SaveCodeToWandbCallback(pl.Callback):
|
||||
"training_modules/callbacks.py",
|
||||
"training_modules/datamodules.py",
|
||||
"training_modules/datasets.py",
|
||||
"training_modules/lightning_wrapper.py",
|
||||
"training_modules/lightning_module.py",
|
||||
"training_modules/loggers.py",
|
||||
"training_modules/models.py",
|
||||
"training_modules/transforms.py",
|
||||
"train.py",
|
||||
"config.yaml"
|
||||
"train_config.yaml"
|
||||
]
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
|
||||
@@ -1,22 +1,23 @@
|
||||
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 *
|
||||
from models.transfer_learning_cifar10_classifier.transforms 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):
|
||||
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90, num_workers=1,
|
||||
pin_memory=False):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.split_ratio = split_ratio
|
||||
self.num_workers = num_workers
|
||||
self.pin_memory = pin_memory
|
||||
|
||||
self.data_train = None
|
||||
self.data_val = None
|
||||
@@ -35,22 +36,28 @@ class ExampleDataModule(pl.LightningDataModule):
|
||||
pass
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
||||
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)
|
||||
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)
|
||||
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, data_dir='data/mnist', batch_size=64, split_ratio=0.90):
|
||||
def __init__(self, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||
pin_memory=False):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.split_ratio = split_ratio
|
||||
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
|
||||
@@ -68,7 +75,7 @@ class MNISTDataModule(pl.LightningDataModule):
|
||||
"""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_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)
|
||||
@@ -78,22 +85,28 @@ class MNISTDataModule(pl.LightningDataModule):
|
||||
self.input_size = np.prod(self.input_dims)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
||||
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)
|
||||
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)
|
||||
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, data_dir="data/cifar10", batch_size=64, split_ratio=0.90):
|
||||
def __init__(self, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||
pin_memory=False):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.split_ratio = split_ratio
|
||||
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
|
||||
@@ -111,7 +124,7 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
||||
"""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_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)
|
||||
@@ -121,10 +134,13 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
||||
self.input_size = np.prod(self.input_dims)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
||||
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)
|
||||
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)
|
||||
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory)
|
||||
@@ -1,71 +0,0 @@
|
||||
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=None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
# we can return here anything and then read it in some callback
|
||||
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)
|
||||
|
||||
return loss
|
||||
|
||||
def configure_optimizers(self):
|
||||
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"])
|
||||
@@ -2,15 +2,16 @@ from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogge
|
||||
import os
|
||||
|
||||
|
||||
def get_wandb_logger(config, lit_model, datamodule):
|
||||
def get_wandb_logger(train_config, model_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"],
|
||||
project=train_config["loggers"]["wandb"]["project"],
|
||||
job_type=train_config["loggers"]["wandb"]["job_type"],
|
||||
tags=train_config["loggers"]["wandb"]["tags"],
|
||||
entity=train_config["loggers"]["wandb"]["team"],
|
||||
id=model_config["resume_training"]["wandb"]["wandb_run_id"]
|
||||
if model_config["resume_training"]["wandb"]["resume_wandb_run"] else None,
|
||||
log_model=train_config["loggers"]["wandb"]["log_model"],
|
||||
offline=train_config["loggers"]["wandb"]["offline"],
|
||||
save_dir="logs/",
|
||||
save_code=False
|
||||
)
|
||||
|
||||
@@ -1,149 +0,0 @@
|
||||
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.Linear(3*32*32, config["lin1_size"]), # for CIFAR10
|
||||
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)
|
||||
@@ -1,23 +0,0 @@
|
||||
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]),
|
||||
])
|
||||
Reference in new issue
Block a user