diff --git a/main.py b/main.py new file mode 100644 index 0000000..b16026c --- /dev/null +++ b/main.py @@ -0,0 +1,98 @@ +# regular imports +import yaml + +# pytorch lightning +import pytorch_lightning as pl +from pytorch_lightning.callbacks import ModelCheckpoint +from pytorch_lightning.callbacks.early_stopping import EarlyStopping +from pytorch_lightning.profiler import SimpleProfiler, AdvancedProfiler + +# wandb +import wandb +from pytorch_lightning.loggers import WandbLogger + +# custom utils +from utils.data_modules import MNISTDataModule +from utils.lightning_wrapper import LitModel +from utils.callbacks import ExampleCallback + + +# Load config +with open("config.yaml", "r") as ymlfile: + config = yaml.load(ymlfile, Loader=yaml.FullLoader) + + +# Init our model +model = LitModel(config=config) + + +# Init data loader +dataloader = MNISTDataModule(batch_size=128) +dataloader.prepare_data() +dataloader.setup() + + +# Init wandb logger +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"], + log_model=True, + offline=False +) +wandb_logger.watch(model.model, log='all') + + +# Init callbacks +callbacks = [ + ExampleCallback(), + EarlyStopping( + monitor=config["callbacks"]["early_stop"]["monitor"], + patience=config["callbacks"]["early_stop"]["patience"], + mode=config["callbacks"]["early_stop"]["mode"], + verbose=False + ), +] + +checkpoint_callback = ModelCheckpoint( + monitor=config["callbacks"]["checkpoint"]["monitor"], + save_top_k=config["callbacks"]["checkpoint"]["save_top_k"], + mode=config["callbacks"]["checkpoint"]["mode"] +) + + +# Init trainer +trainer = pl.Trainer( + gpus=config["num_of_gpus"], + max_epochs=config["max_epochs"], + logger=wandb_logger, + callbacks=callbacks, + checkpoint_callback=checkpoint_callback, + resume_from_checkpoint=config["resume"]["ckpt_path"] if config["resume"]["resume_from_ckpt"] else None, + auto_scale_batch_size='power' if config["auto_scale_batch_size"] else False, + accumulate_grad_batches=config["accumulate_grad_batches"], + gradient_clip_val=config["gradient_clip_val"], + progress_bar_refresh_rate=1, + profiler=SimpleProfiler(), + weights_summary='full', + # fast_dev_run=True, + # limit_train_batches=0.01 + # limit_val_batches=0.01 + # limit_test_batches=0.01 + # amp_backend='apex', + # precision=16, +) + +# Tune trainer (finds biggest possible batch size if enabled) +if config["auto_scale_batch_size"]: + trainer.tune(model=model, datamodule=dataloader) + +# Train the model ⚡ +trainer.fit(model=model, datamodule=dataloader) + +# Evaluate model on test set +trainer.test() + +# Close wandb run +wandb.finish() diff --git a/utils/callbacks.py b/utils/callbacks.py new file mode 100644 index 0000000..c14e3c8 --- /dev/null +++ b/utils/callbacks.py @@ -0,0 +1,13 @@ +from pytorch_lightning.callbacks import Callback + + +class ExampleCallback(Callback): + + def on_init_start(self, trainer): + print('Starting to init trainer!') + + def on_init_end(self, trainer): + print('Trainer is init now') + + def on_train_end(self, trainer, pl_module): + print('Do something when training ends') diff --git a/utils/data_modules.py b/utils/data_modules.py new file mode 100644 index 0000000..62b3192 --- /dev/null +++ b/utils/data_modules.py @@ -0,0 +1,45 @@ +# 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.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): + # we set up only relevant datasets when stage is specified (automatically set by Pytorch-Lightning) + if stage == 'fit' or stage is None: + mnist_train = MNIST(self.data_dir, train=True, transform=self.transform) + self.data_train, self.data_val = random_split(mnist_train, [55000, 5000]) + + if stage == 'test' or stage is None: + 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) diff --git a/utils/lightning_wrapper.py b/utils/lightning_wrapper.py new file mode 100644 index 0000000..44a92e0 --- /dev/null +++ b/utils/lightning_wrapper.py @@ -0,0 +1,68 @@ +# 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 utils.models import ModelMNISTv1, ModelMNISTv2 + + +class LitModel(pl.LightningModule): + + def __init__(self, config): + super().__init__() + + self.save_hyperparameters(config) + self.model = ModelMNISTv1(config=self.hparams.model) + # self.model = ModelMNISTv2(config=self.hparams.model) + + def forward(self, data): + return self.model(data) + + # 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.learning_rate) diff --git a/utils/models.py b/utils/models.py new file mode 100644 index 0000000..79e983d --- /dev/null +++ b/utils/models.py @@ -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, 128) + self.layer_2 = nn.Linear(128, 256) + self.layer_3 = nn.Linear(256, 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, 256) + self.layer_2 = nn.Linear(256, 128) + self.layer_3 = nn.Linear(128, 64) + self.layer_4 = nn.Linear(64, 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)