Dev (#107)
* refactor folder names * define python logger correctly * refactor rich printing method * specify model parameters explicitly * specify datamodule params explicitly * refactor * update readme
This commit is contained in:
1 parent
fca999f527
commit
381b5844ed
18 files changed
+133
-168
No files matched your search
@@ -9,23 +9,19 @@ class SimpleDenseNet(nn.Module):
|
||||
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
|
||||
nn.BatchNorm1d(hparams["lin1_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout1"]),
|
||||
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
|
||||
nn.BatchNorm1d(hparams["lin2_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout2"]),
|
||||
nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
|
||||
nn.BatchNorm1d(hparams["lin3_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Dropout(p=hparams["dropout3"]),
|
||||
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
batch_size, channels, width, height = x.size()
|
||||
|
||||
# mnist images are (1, 28, 28) (channels, width, height)
|
||||
# (b, 1, 28, 28) -> (b, 1*28*28)
|
||||
# (batch, 1, width, height) -> (batch, 1*width*height)
|
||||
x = x.view(batch_size, -1)
|
||||
|
||||
return self.model(x)
|
||||
@@ -7,15 +7,19 @@ import seaborn as sn
|
||||
import torch
|
||||
import wandb
|
||||
from pytorch_lightning import Callback, Trainer
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from pytorch_lightning.loggers import LoggerCollection, WandbLogger
|
||||
from sklearn import metrics
|
||||
from sklearn.metrics import f1_score, precision_score, recall_score
|
||||
|
||||
|
||||
def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||
for logger in trainer.logger:
|
||||
if isinstance(logger, WandbLogger):
|
||||
return logger
|
||||
if isinstance(trainer.logger, WandbLogger):
|
||||
return trainer.logger
|
||||
|
||||
if isinstance(trainer.logger, LoggerCollection):
|
||||
for logger in trainer.logger:
|
||||
if isinstance(logger, WandbLogger):
|
||||
return logger
|
||||
|
||||
raise Exception(
|
||||
"You are using wandb related callback,"
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Optional, Sequence
|
||||
from typing import Optional
|
||||
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
|
||||
@@ -10,21 +10,29 @@ class MNISTDataModule(LightningDataModule):
|
||||
"""
|
||||
Example of LightningDataModule for MNIST dataset.
|
||||
|
||||
A DataModule standardizes the training, val, test splits, data preparation and transforms.
|
||||
A DataModule standardizes the train, 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
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(
|
||||
self,
|
||||
data_dir="data/",
|
||||
batch_size=64,
|
||||
train_val_test_split=(55_000, 5_000, 10_000),
|
||||
num_workers=0,
|
||||
pin_memory=False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = kwargs["data_dir"]
|
||||
self.batch_size = kwargs["batch_size"]
|
||||
self.train_val_test_split = kwargs["train_val_test_split"]
|
||||
self.num_workers = kwargs["num_workers"]
|
||||
self.pin_memory = kwargs["pin_memory"]
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.train_val_test_split = train_val_test_split
|
||||
self.num_workers = num_workers
|
||||
self.pin_memory = pin_memory
|
||||
|
||||
self.transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
@@ -1,16 +1,15 @@
|
||||
from typing import Any, Dict, List, Sequence, Tuple, Union
|
||||
|
||||
import hydra
|
||||
import pytorch_lightning as pl
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from pytorch_lightning import LightningModule
|
||||
from pytorch_lightning.metrics.classification import Accuracy
|
||||
from torch.optim import Optimizer
|
||||
|
||||
from src.architectures.simple_dense_net import SimpleDenseNet
|
||||
|
||||
|
||||
class LitModelMNIST(pl.LightningModule):
|
||||
class MNISTLitModel(LightningModule):
|
||||
"""
|
||||
Example of LightningModule for MNIST classification.
|
||||
|
||||
@@ -25,14 +24,23 @@ class LitModelMNIST(pl.LightningModule):
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||
"""
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
def __init__(
|
||||
self,
|
||||
optimizer,
|
||||
input_size=784,
|
||||
lin1_size=256,
|
||||
lin2_size=256,
|
||||
lin3_size=256,
|
||||
output_size=10,
|
||||
**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.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||
self.model = SimpleDenseNet(hparams=self.hparams)
|
||||
|
||||
# loss function
|
||||
self.criterion = torch.nn.CrossEntropyLoss()
|
||||
@@ -51,7 +59,7 @@ class LitModelMNIST(pl.LightningModule):
|
||||
}
|
||||
|
||||
def forward(self, x) -> torch.Tensor:
|
||||
return self.architecture(x)
|
||||
return self.model(x)
|
||||
|
||||
def step(self, batch) -> Dict[str, torch.Tensor]:
|
||||
x, y = batch
|
||||
@@ -63,7 +71,7 @@ class LitModelMNIST(pl.LightningModule):
|
||||
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!
|
||||
# log train metrics
|
||||
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)
|
||||
@@ -76,19 +84,17 @@ class LitModelMNIST(pl.LightningModule):
|
||||
def validation_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log val metrics to your loggers!
|
||||
# log val metrics
|
||||
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 dict with any tensors
|
||||
# and then read it in some callback or in validation_epoch_end() below
|
||||
return {"loss": loss, "preds": preds, "targets": targets}
|
||||
|
||||
def test_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log test metrics to your loggers!
|
||||
# log test metrics
|
||||
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)
|
||||
@@ -113,6 +119,10 @@ class LitModelMNIST(pl.LightningModule):
|
||||
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)
|
||||
|
||||
# [OPTIONAL METHOD]
|
||||
def test_epoch_end(self, outputs: List[Any]) -> None:
|
||||
pass
|
||||
|
||||
def configure_optimizers(
|
||||
self,
|
||||
) -> Union[Optimizer, Tuple[Sequence[Optimizer], Sequence[Any]]]:
|
||||
+6
-8
@@ -1,19 +1,17 @@
|
||||
# lightning imports
|
||||
import logging
|
||||
from typing import List, Optional
|
||||
|
||||
from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
from pytorch_lightning import seed_everything
|
||||
|
||||
# hydra imports
|
||||
from omegaconf import DictConfig
|
||||
from hydra.utils import log
|
||||
import hydra
|
||||
from omegaconf import DictConfig
|
||||
|
||||
# normal imports
|
||||
from typing import List, Optional
|
||||
|
||||
# src imports
|
||||
from src.utils import template_utils
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def train(config: DictConfig) -> Optional[float]:
|
||||
"""Contains training pipeline.
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from torchvision import transforms
|
||||
|
||||
mnist_train_transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
|
||||
mnist_test_transforms = transforms.Compose(
|
||||
[
|
||||
transforms.ToTensor(),
|
||||
transforms.Resize((28, 28)),
|
||||
transforms.Normalize((0.1307,), (0.3081,)),
|
||||
]
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
from PIL import Image
|
||||
from torchvision import transforms
|
||||
|
||||
from src.models.mnist_model import LitModelMNIST
|
||||
from src.transforms import mnist_transforms
|
||||
from src.pl_models.mnist_model import MNISTLitModel
|
||||
|
||||
|
||||
def predict():
|
||||
@@ -16,7 +16,7 @@ def predict():
|
||||
# load model from checkpoint
|
||||
# model __init__ parameters will be loaded from ckpt automatically
|
||||
# you can also pass some parameter explicitly to override it
|
||||
trained_model = LitModelMNIST.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
trained_model = MNISTLitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||
|
||||
# print model hyperparameters
|
||||
print(trained_model.hparams)
|
||||
@@ -30,7 +30,14 @@ def predict():
|
||||
# img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
|
||||
|
||||
# preprocess
|
||||
img = mnist_transforms.mnist_test_transforms(img)
|
||||
mnist_transforms = transforms.Compose(
|
||||
[
|
||||
transforms.ToTensor(),
|
||||
transforms.Resize((28, 28)),
|
||||
transforms.Normalize((0.1307,), (0.3081,)),
|
||||
]
|
||||
)
|
||||
img = mnist_transforms(img)
|
||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||
|
||||
# inference
|
||||
|
||||
@@ -4,13 +4,14 @@ from typing import List, Sequence
|
||||
|
||||
import pytorch_lightning as pl
|
||||
import wandb
|
||||
from hydra.utils import log
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
from rich import print
|
||||
from rich.syntax import Syntax
|
||||
from rich.tree import Tree
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
@@ -22,10 +23,10 @@ def extras(config: DictConfig) -> None:
|
||||
config (DictConfig): [description]
|
||||
"""
|
||||
|
||||
# make it possible to add new keys to config
|
||||
# Enable adding new keys to config
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# fix double logging bug (this will be removed when lightning releases patch)
|
||||
# Fix double logging bug (this will be removed when lightning releases patch)
|
||||
pl_logger = logging.getLogger("lightning")
|
||||
pl_logger.propagate = False
|
||||
|
||||
@@ -56,7 +57,7 @@ def extras(config: DictConfig) -> None:
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
|
||||
# disable adding new keys to config
|
||||
# Disable adding new keys to config
|
||||
OmegaConf.set_struct(config, True)
|
||||
|
||||
|
||||
@@ -71,10 +72,6 @@ def print_config(
|
||||
"logger",
|
||||
"seed",
|
||||
),
|
||||
extra_depth_fields: Sequence[str] = (
|
||||
"callbacks",
|
||||
"logger",
|
||||
),
|
||||
resolve: bool = True,
|
||||
) -> None:
|
||||
"""Prints content of DictConfig using Rich library and its tree structure.
|
||||
@@ -83,41 +80,21 @@ def print_config(
|
||||
config (DictConfig): Config.
|
||||
fields (Sequence[str], optional): Determines which main fields from config will be printed
|
||||
and in what order.
|
||||
extra_depth_fields (Sequence[str], optional): Fields which should be printed with extra tree depth.
|
||||
resolve (bool, optional): Whether to resolve reference fields of DictConfig.
|
||||
"""
|
||||
|
||||
# TODO print main config path and experiment config path
|
||||
# print(f"Main config path: [link file://{directory}]{directory}")
|
||||
|
||||
# TODO refactor the whole method
|
||||
|
||||
style = "dim"
|
||||
|
||||
tree = Tree(f":gear: CONFIG", style=style, guide_style=style)
|
||||
|
||||
for field in fields:
|
||||
branch = tree.add(field, style=style, guide_style=style)
|
||||
|
||||
config_section = config.get(field)
|
||||
branch_content = str(config_section)
|
||||
if isinstance(config_section, DictConfig):
|
||||
branch_content = OmegaConf.to_yaml(config_section, resolve=resolve)
|
||||
|
||||
if not config_section:
|
||||
# raise Exception(f"Field {field} not found in config!")
|
||||
branch.add("None")
|
||||
continue
|
||||
|
||||
if field in extra_depth_fields:
|
||||
for nested_field in config_section:
|
||||
nested_config_section = config_section[nested_field]
|
||||
nested_branch = branch.add(nested_field, style=style, guide_style=style)
|
||||
cfg_str = OmegaConf.to_yaml(nested_config_section, resolve=resolve)
|
||||
nested_branch.add(Syntax(cfg_str, "yaml"))
|
||||
else:
|
||||
if isinstance(config_section, DictConfig):
|
||||
cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
|
||||
else:
|
||||
cfg_str = str(config_section)
|
||||
branch.add(Syntax(cfg_str, "yaml"))
|
||||
branch.add(Syntax(branch_content, "yaml"))
|
||||
|
||||
print(tree)
|
||||
|
||||
|
||||
Reference in new issue
Block a user