change folder structure

This commit is contained in:
hobogalaxy committed 2020-11-15 23:17:43 +01:00
1 parent 24f78a31df
commit eb8ac55ab7
9 files changed
+5 -6

No files matched your search

+54
View File
@@ -0,0 +1,54 @@
from pytorch_lightning.callbacks import Callback
import torch
import wandb
import os
class ExampleCallback(Callback):
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 SaveOnnxToWandbCallback(Callback):
def __init__(self, dataloader, wandb_save_dir):
first_batch = next(iter(dataloader))
x, y = first_batch
self.dummy_input = x
self.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.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(Callback):
def __init__(self, val_samples, num_samples=32):
super().__init__()
self.val_imgs, self.val_labels = val_samples[:num_samples]
def on_validation_epoch_end(self, trainer, pl_module):
val_imgs = self.val_imgs.to(device=pl_module.device)
logits = pl_module(val_imgs)
preds = torch.argmax(logits, -1)
trainer.logger.experiment.log({
"examples": [wandb.Image(x, caption=f"Pred:{pred}, Label:{y}")
for x, pred, y in zip(val_imgs, preds, self.val_labels)],
"global_step": trainer.global_step
})
+43
View File
@@ -0,0 +1,43 @@
# pytorch
from torch.utils.data import DataLoader, random_split
# pytorch lightning
import pytorch_lightning as pl
# torchvision
from torchvision.datasets import MNIST
from torchvision import transforms
class MNISTDataModule(pl.LightningDataModule):
def __init__(self, data_dir='data/mnist', batch_size=256):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.transform = transforms.ToTensor()
self.dims = None
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
# download data
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
def setup(self, stage=None):
mnist_train = MNIST(self.data_dir, train=True, transform=self.transform)
self.data_train, self.data_val = random_split(mnist_train, [55000, 5000])
self.dims = self.data_train[0][0].shape
self.data_test = MNIST(self.data_dir, train=False, transform=self.transform)
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)
Whitespace-only changes.
@@ -0,0 +1,67 @@
# pytorch
import torch
import torch.nn.functional as F
# pytorch lightning
import pytorch_lightning as pl
from pytorch_lightning.metrics.functional import accuracy, precision, recall, f1_score, fbeta_score
# custom models
from pipeline_modules.models import ModelMNISTv1, ModelMNISTv2
class LitModel(pl.LightningModule):
def __init__(self, config):
super().__init__()
self.save_hyperparameters(config["hparams"])
self.model = ModelMNISTv2(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)
acc = accuracy(preds, y)
self.log('train_loss', loss, on_epoch=True, logger=True)
self.log('train_acc', acc, on_epoch=True, logger=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)
acc = accuracy(preds, y)
self.log('val_loss', loss, prog_bar=True, logger=True)
self.log('val_acc', acc, prog_bar=True, logger=True)
return loss
# 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)
acc = accuracy(preds, y)
self.log('test_loss', loss, prog_bar=True, logger=True)
self.log('test_acc', acc, prog_bar=True, logger=True)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr)
+53
View File
@@ -0,0 +1,53 @@
from torch import nn
import torch.nn.functional as F
class ModelMNISTv1(nn.Module):
def __init__(self, config):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.layer_1 = nn.Linear(28 * 28, config["lin1_size"])
self.layer_2 = nn.Linear(config["lin1_size"], config["lin2_size"])
self.layer_3 = nn.Linear(config["lin2_size"], 10)
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)
x = self.layer_1(x)
x = F.relu(x)
x = self.layer_2(x)
x = F.relu(x)
x = self.layer_3(x)
return F.log_softmax(x, dim=1)
class ModelMNISTv2(nn.Module):
def __init__(self, config):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.layer_1 = nn.Linear(28 * 28, config["lin1_size"])
self.layer_2 = nn.Linear(config["lin1_size"], config["lin2_size"])
self.layer_3 = nn.Linear(config["lin2_size"], config["lin3_size"])
self.layer_4 = nn.Linear(config["lin3_size"], 10)
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)
x = self.layer_1(x)
x = F.relu(x)
x = self.layer_2(x)
x = F.relu(x)
x = self.layer_3(x)
x = F.relu(x)
x = self.layer_4(x)
return F.log_softmax(x, dim=1)