start redesigning project structure for version 4.0
This commit is contained in:
1 parent
42652e3752
commit
fa8b9ecc16
18 files changed
+140
-130
No files matched your search
@@ -0,0 +1,32 @@
|
||||
from torch import nn
|
||||
|
||||
|
||||
class SimpleMNISTClassifier(nn.Module):
|
||||
|
||||
def __init__(self, hparams):
|
||||
super().__init__()
|
||||
|
||||
# mnist images are (1, 28, 28) (channels, width, height)
|
||||
self.model = nn.Sequential(
|
||||
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
|
||||
nn.BatchNorm1d(hparams["lin1_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=0.3),
|
||||
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
|
||||
nn.BatchNorm1d(hparams["lin2_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=0.25),
|
||||
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
|
||||
nn.BatchNorm1d(hparams["lin3_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=0.2),
|
||||
nn.Linear(hparams["lin3_size"], hparams["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)
|
||||
@@ -0,0 +1,27 @@
|
||||
from torch.utils.data import Dataset
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
|
||||
class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder and converting them to monochromatic.
|
||||
Can be used to perform inference with trained MNIST model.
|
||||
'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by lightning_datamodules.
|
||||
"""
|
||||
|
||||
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("L") # convert to black and white
|
||||
# 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,28 @@
|
||||
from pytorch_lightning import Callback
|
||||
|
||||
|
||||
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 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
|
||||
@@ -0,0 +1,175 @@
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from wandb.sdk.wandb_run import Run as wandb_run
|
||||
from pytorch_lightning import Callback
|
||||
from shutil import copy
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
|
||||
|
||||
class SaveOnnxModelToWandbCallback(Callback):
|
||||
"""
|
||||
Save model in .onnx format and upload to wandb.
|
||||
Might crash since not all lightning_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 ImagePredictionWandbLoggerCallback(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 MetricsHeatmapWandbLoggerCallback(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)
|
||||
|
||||
logger = None
|
||||
for some_logger in trainer.logger.experiment:
|
||||
if isinstance(some_logger, wandb_run):
|
||||
logger = some_logger
|
||||
|
||||
logger.log({
|
||||
f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": 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 ConfusionMatrixWandbLoggerCallback(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()
|
||||
|
||||
logger = None
|
||||
for some_logger in trainer.logger.experiment:
|
||||
if isinstance(some_logger, wandb_run):
|
||||
logger = some_logger
|
||||
|
||||
logger.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"]["load_from"]["model_path"]
|
||||
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
|
||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||
"template_utils/custom_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
|
||||
pass
|
||||
@@ -0,0 +1,54 @@
|
||||
from torch.utils.data import DataLoader, ConcatDataset, random_split
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torchvision.transforms import transforms
|
||||
from torchvision.datasets import MNIST
|
||||
|
||||
|
||||
class MNISTDataModule(LightningDataModule):
|
||||
"""
|
||||
This is example of datamodule for MNIST dataset.
|
||||
|
||||
The path to datamodule should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
||||
"""
|
||||
|
||||
def __init__(self, data_dir: str, hparams: dict):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml
|
||||
|
||||
self.batch_size = hparams.get("batch_size") or 64
|
||||
self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||
self.num_workers = hparams.get("num_workers") or 1
|
||||
self.pin_memory = hparams.get("pin_memory") or False
|
||||
|
||||
self.transforms = transforms.ToTensor()
|
||||
|
||||
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)
|
||||
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
|
||||
dataset = ConcatDataset(datasets=[trainset, testset])
|
||||
|
||||
self.data_train, self.data_val, self.data_test = random_split(dataset, self.train_val_test_split)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(dataset=self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory, shuffle=True)
|
||||
|
||||
def val_dataloader(self):
|
||||
return DataLoader(dataset=self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory)
|
||||
|
||||
def test_dataloader(self):
|
||||
return DataLoader(dataset=self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory)
|
||||
@@ -0,0 +1,79 @@
|
||||
from sklearn.metrics import accuracy_score
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
# import custom lightning_models
|
||||
from pytorch_modules.lightning_models.simple_mnist_classifier.models import *
|
||||
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
"""
|
||||
This is example of lightning model for MNIST digits classification.
|
||||
|
||||
The path to model should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
||||
|
||||
This class enables you to specify what happens during training, validation and test step.
|
||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||
"""
|
||||
|
||||
def __init__(self, hparams: dict = None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
self.save_hyperparameters(hparams)
|
||||
|
||||
self.model = SimpleMNISTClassifier(hparams=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"])
|
||||
@@ -0,0 +1,13 @@
|
||||
"""
|
||||
Example file containing data transformations which can be used by datamodule.
|
||||
"""
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
mnist_train_transforms = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
])
|
||||
|
||||
mnist_test_transforms = transforms.Compose([
|
||||
transforms.ToTensor()
|
||||
])
|
||||
Reference in new issue
Block a user