Dev (#93)
* rework lightning model for mnist * sort imports * add comment to pre-commit-config * remove returns from test_step because it's bugged * update experiment configs * Update README.md
This commit is contained in:
1 parent
67d531ab67
commit
b1e0bf9717
23 files changed
+480
-320
No files matched your search
@@ -2,7 +2,7 @@ from torch import nn
|
||||
|
||||
|
||||
class SimpleDenseNet(nn.Module):
|
||||
def __init__(self, hparams):
|
||||
def __init__(self, hparams: dict):
|
||||
super().__init__()
|
||||
|
||||
self.model = nn.Sequential(
|
||||
@@ -19,7 +19,6 @@ class SimpleDenseNet(nn.Module):
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout3"]),
|
||||
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
|
||||
nn.LogSoftmax(dim=1),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
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 all model parameters 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
|
||||
@@ -1,17 +1,13 @@
|
||||
# wandb
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
import wandb
|
||||
|
||||
# pytorch
|
||||
from pytorch_lightning import Callback
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
|
||||
# others
|
||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||
from typing import List
|
||||
import glob
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
import wandb
|
||||
from pytorch_lightning import Callback
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from sklearn.metrics import f1_score, precision_score, recall_score
|
||||
|
||||
|
||||
def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
from torch.utils.data import DataLoader, ConcatDataset, random_split
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torchvision.transforms import transforms
|
||||
from torch.utils.data import ConcatDataset, DataLoader, random_split
|
||||
from torchvision.datasets import MNIST
|
||||
from torchvision.transforms import transforms
|
||||
|
||||
|
||||
class MNISTDataModule(LightningDataModule):
|
||||
"""
|
||||
This is example of LightningDataModule for MNIST dataset.
|
||||
Example of LightningDataModule for MNIST dataset.
|
||||
|
||||
A DataModule standardizes the training, val, test splits, data preparation and transforms.
|
||||
The main advantage is consistent data splits, data preparation and transforms across models.
|
||||
|
||||
Read the docs:
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
||||
"""
|
||||
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
from torch.utils.data import Dataset
|
||||
from PIL import Image
|
||||
import os
|
||||
|
||||
from PIL import Image
|
||||
from torch.utils.data import Dataset
|
||||
|
||||
|
||||
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.
|
||||
"""
|
||||
"""Example dataset class for loading images from folder."""
|
||||
|
||||
def __init__(self, img_dir, transform):
|
||||
def __init__(self, dir: str, transform):
|
||||
self.transform = transform
|
||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||
self.images = [os.path.join(dir, fname) for fname in os.listdir(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:
|
||||
if self.transform:
|
||||
image = self.transform(image)
|
||||
|
||||
return image
|
||||
|
||||
+91
-56
@@ -1,94 +1,129 @@
|
||||
from pytorch_lightning.metrics.classification import Accuracy
|
||||
from typing import Any, Dict, List, Sequence, Tuple, Union
|
||||
|
||||
import hydra
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
from pytorch_lightning.metrics.classification import Accuracy
|
||||
from torch.optim import Optimizer
|
||||
|
||||
# import custom architectures
|
||||
from src.architectures.simple_dense_net import SimpleDenseNet
|
||||
|
||||
|
||||
class LitModelMNIST(pl.LightningModule):
|
||||
"""
|
||||
This is example of LightningModule for MNIST classification.
|
||||
Example of LightningModule for MNIST classification.
|
||||
|
||||
A LightningModule organizes your PyTorch code into 5 sections:
|
||||
- Computations (init).
|
||||
- Train loop (training_step)
|
||||
- Validation loop (validation_step)
|
||||
- Test loop (test_step)
|
||||
- Optimizers (configure_optimizers)
|
||||
|
||||
Read the docs:
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__()
|
||||
|
||||
# this line ensures params passed to LightningModule will be saved to ckpt
|
||||
# it also allows to access params with 'self.hparams' attribute
|
||||
self.save_hyperparameters()
|
||||
self.accuracy = Accuracy()
|
||||
|
||||
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||
|
||||
self.train_acc_hist = []
|
||||
self.train_loss_hist = []
|
||||
self.val_acc_hist = []
|
||||
self.val_loss_hist = []
|
||||
# loss function
|
||||
self.criterion = torch.nn.CrossEntropyLoss()
|
||||
|
||||
def forward(self, x):
|
||||
# use separate metric instance for train, val and test step
|
||||
# to ensure a proper reduction over the epoch
|
||||
self.train_accuracy = Accuracy()
|
||||
self.val_accuracy = Accuracy()
|
||||
self.test_accuracy = Accuracy()
|
||||
|
||||
self.metric_hist = {
|
||||
"train/acc": [],
|
||||
"val/acc": [],
|
||||
"train/loss": [],
|
||||
"val/loss": [],
|
||||
}
|
||||
|
||||
def forward(self, x) -> torch.Tensor:
|
||||
return self.architecture(x)
|
||||
|
||||
# logic for a single training step
|
||||
def training_step(self, batch, batch_idx):
|
||||
def step(self, batch) -> Dict[str, torch.Tensor]:
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# training metrics
|
||||
loss = self.criterion(logits, y)
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
return loss, preds, y
|
||||
|
||||
def training_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log train metrics to your loggers!
|
||||
acc = self.train_accuracy(preds, targets)
|
||||
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||
self.log("train/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||
|
||||
# we can return here anything and then read it in some callback or in training_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": y}
|
||||
# we can return here dict with any tensors
|
||||
# and then read it in some callback or in training_epoch_end() below
|
||||
# remember to always return loss from training_step, or else backpropagation will fail!
|
||||
return {"loss": loss, "preds": preds, "targets": targets}
|
||||
|
||||
# logic for a single validation step
|
||||
def validation_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
def validation_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# validation metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
# log val metrics to your loggers!
|
||||
acc = self.val_accuracy(preds, targets)
|
||||
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||
|
||||
# we can return here anything and then read it in some callback or in validation_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": y}
|
||||
# we can return here dict with any tensors
|
||||
# and then read it in some callback or in validation_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": targets}
|
||||
|
||||
# logic for a single testing step
|
||||
def test_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
def test_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# test metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
acc = self.accuracy(preds, y)
|
||||
# log test metrics to your loggers!
|
||||
acc = self.test_accuracy(preds, targets)
|
||||
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
||||
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
||||
|
||||
return loss
|
||||
return {"loss": loss}
|
||||
|
||||
def training_epoch_end(self, outputs):
|
||||
self.train_acc_hist.append(self.trainer.callback_metrics["train/acc"])
|
||||
self.train_loss_hist.append(self.trainer.callback_metrics["train/loss"])
|
||||
self.log("train/acc_best", max(self.train_acc_hist), prog_bar=False)
|
||||
self.log("train/loss_best", min(self.train_loss_hist), prog_bar=False)
|
||||
# [OPTIONAL METHOD]
|
||||
def training_epoch_end(self, outputs: List[Any]) -> None:
|
||||
# log best so far train acc and train loss
|
||||
self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
|
||||
self.metric_hist["train/loss"].append(
|
||||
self.trainer.callback_metrics["train/loss"]
|
||||
)
|
||||
self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
|
||||
self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
|
||||
|
||||
def validation_epoch_end(self, outputs):
|
||||
self.val_acc_hist.append(self.trainer.callback_metrics["val/acc"])
|
||||
self.val_loss_hist.append(self.trainer.callback_metrics["val/loss"])
|
||||
self.log("val/acc_best", max(self.val_acc_hist), prog_bar=False)
|
||||
self.log("val/loss_best", min(self.val_loss_hist), prog_bar=False)
|
||||
# [OPTIONAL METHOD]
|
||||
def validation_epoch_end(self, outputs: List[Any]) -> None:
|
||||
# log best so far val acc and val loss
|
||||
self.metric_hist["val/acc"].append(self.trainer.callback_metrics["val/acc"])
|
||||
self.metric_hist["val/loss"].append(self.trainer.callback_metrics["val/loss"])
|
||||
self.log("val/acc_best", max(self.metric_hist["val/acc"]), prog_bar=False)
|
||||
self.log("val/loss_best", min(self.metric_hist["val/loss"]), prog_bar=False)
|
||||
|
||||
def configure_optimizers(self):
|
||||
if self.hparams.optimizer == "adam":
|
||||
return torch.optim.Adam(
|
||||
self.parameters(),
|
||||
lr=self.hparams.lr,
|
||||
weight_decay=self.hparams.weight_decay,
|
||||
)
|
||||
else:
|
||||
raise Exception("Invalid optimizer name")
|
||||
def configure_optimizers(
|
||||
self,
|
||||
) -> Union[Optimizer, Tuple[Sequence[Optimizer], Sequence[Any]]]:
|
||||
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
|
||||
Normally you'd need one. But in the case of GANs or similar you might have multiple.
|
||||
|
||||
See examples here:
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
|
||||
|
||||
"""
|
||||
optim = hydra.utils.instantiate(
|
||||
self.hparams.optimizer, params=self.parameters()
|
||||
)
|
||||
return optim
|
||||
@@ -1,6 +1,5 @@
|
||||
from torchvision import transforms
|
||||
|
||||
|
||||
mnist_train_transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
from PIL import Image
|
||||
|
||||
from src.models.mnist_model import LitModelMNIST
|
||||
from src.transforms import mnist_transforms
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def predict():
|
||||
"""
|
||||
This is example of inference with a trained model.
|
||||
It Loads trained image classification model from checkpoint.
|
||||
"""Example of inference with trained model.
|
||||
It loads trained image classification model from checkpoint.
|
||||
Then it loads example image and predicts its label.
|
||||
"""
|
||||
|
||||
|
||||
+10
-24
@@ -1,37 +1,23 @@
|
||||
# lightning imports
|
||||
import logging
|
||||
import warnings
|
||||
from typing import List
|
||||
|
||||
import pytorch_lightning as pl
|
||||
|
||||
# hydra imports
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from hydra.utils import get_original_cwd, to_absolute_path
|
||||
from hydra.utils import log
|
||||
|
||||
# logger imports
|
||||
import wandb
|
||||
from hydra.utils import get_original_cwd, log, to_absolute_path
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
|
||||
# from pytorch_lightning.loggers.neptune import NeptuneLogger
|
||||
# from pytorch_lightning.loggers.comet import CometLogger
|
||||
# from pytorch_lightning.loggers.mlflow import MLFlowLogger
|
||||
# from pytorch_lightning.loggers.tensorboard import TensorBoardLogger
|
||||
|
||||
# rich imports
|
||||
from rich import print
|
||||
from rich.syntax import Syntax
|
||||
from rich.tree import Tree
|
||||
from rich import print
|
||||
|
||||
# normal imports
|
||||
from typing import List
|
||||
import warnings
|
||||
import logging
|
||||
|
||||
|
||||
def extras(config: DictConfig):
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- disabling warnings
|
||||
- disabling lightning logs
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
"""
|
||||
@@ -48,7 +34,7 @@ def extras(config: DictConfig):
|
||||
if config.get("disable_lightning_logs"):
|
||||
log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>")
|
||||
logging.getLogger("lightning").setLevel(logging.ERROR)
|
||||
|
||||
|
||||
# [OPTIONAL] Set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
if config.get("debug"):
|
||||
log.info(f"Running in debug mode! <{config.debug=}>")
|
||||
|
||||
Reference in new issue
Block a user