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

+40
View File
@@ -0,0 +1,40 @@
num_of_gpus: -1
hparams:
max_epochs: 30
batch_size: 64
lr: 0.001
accumulate_grad_batches: 1
gradient_clip_val: 0.5
lin1_size: 128
lin2_size: 256
lin3_size: 128
resume:
resume_from_ckpt: False
wandb_run_id: "8uuomodb"
ckpt_path: "wandb/run-20201111_022721-8uuomodb/files/hackathon_template_test/8uuomodb/checkpoints/epoch=2.ckpt"
loggers:
wandb:
project: "hackathon_template_test"
team: "kino"
group: None
job_type: "train"
tags: []
callbacks:
checkpoint:
monitor: "val_acc"
save_top_k: 1
save_last: True
mode: "max"
early_stop:
monitor: "val_acc"
patience: 100
mode: "max"
printing:
progress_bar_refresh_rate: 20
weights_summary: "full"
profiler: True
View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
import wandb
import main
# Load project config
config = main.load_config()
# Initialize wandb
wandb.init()
# Replace project config hyperparameters with the ones loaded from wandb sweep server
sweep_hparams = wandb.Config._as_dict(wandb.config)
for key, value in sweep_hparams.items():
if key != "_wandb":
config["hparams"][key] = value
# Execute run
main.main(config)
+108
View File
@@ -0,0 +1,108 @@
# pytorch lightning
import pytorch_lightning as pl
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning.profiler import SimpleProfiler, AdvancedProfiler
# yaml
import yaml
# wandb
from pytorch_lightning.loggers import WandbLogger
# custom pipeline_modules
from pipeline_modules.lightning_wrapper import LitModel
from project.pipeline_modules.data_modules import MNISTDataModule
def init_wandb(config, model, dataloader):
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=True,
offline=False
)
wandb_logger.watch(model.model, log='all')
wandb_logger.log_hyperparams({
"model_name": model.model.__class__.__name__,
"dataset_name": dataloader.__class__.__name__,
"optimizer": model.configure_optimizers().__class__.__name__,
"train_size": len(dataloader.data_train),
"val_size": len(dataloader.data_val),
"test_size": len(dataloader.data_test),
"input_dims": dataloader.dims,
})
# download model from a specific wandb run
# wandb.restore('model-best.h5', run_path="kino/some_project/a1b2c3d")
return wandb_logger
def main(config):
# Init our model
model = LitModel(config)
# Init data module
datamodule = MNISTDataModule(batch_size=config["hparams"]["batch_size"])
datamodule.prepare_data()
datamodule.setup()
# Init wandb logger
wandb_logger = init_wandb(config, model, datamodule)
# Init callbacks
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"],
),
# ExampleCallback(),
# LearningRateMonitor(),
# SaveOnnxToWandbCallback(dataloader=datamodule.train_dataloader(), wandb_save_dir=wandb_logger.save_dir)
]
# Init trainer
trainer = pl.Trainer(
logger=wandb_logger,
callbacks=callbacks,
gpus=config["num_of_gpus"],
max_epochs=config["hparams"]["max_epochs"],
resume_from_checkpoint=config["resume"]["ckpt_path"] if config["resume"]["resume_from_ckpt"] else None,
accumulate_grad_batches=config["hparams"]["accumulate_grad_batches"],
gradient_clip_val=config["hparams"]["gradient_clip_val"],
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
weights_summary=config["printing"]["weights_summary"],
# fast_dev_run=True,
# min_epochs=10,
# limit_train_batches=0.01
# limit_val_batches=0.01
# limit_test_batches=0.01
# auto_scale_batch_size="power",
# amp_backend='apex',
# precision=16,
)
# Train the model ⚡
trainer.fit(model=model, datamodule=datamodule)
# Evaluate model on test set
trainer.test()
def load_config():
with open("config.yaml", "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
return config
if __name__ == "__main__":
main(config=load_config())
+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)