Dev (#118)
* update readme * remove optimizer * make parameters more explicit * add .autoenv * update dockerfile * fix paths * update configs * update train.py * fix test
This commit is contained in:
1 parent
42f8acddd0
commit
2dcbdcdaf9
27 files changed
+253
-165
No files matched your search
@@ -36,7 +36,7 @@ class WatchModelWithWandb(Callback):
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
|
||||
class UploadCodeToWandbAsArtifact(Callback):
|
||||
"""Upload all *.py files to wandb as an artifact, at the beginning of the run."""
|
||||
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
from typing import Callable, Optional
|
||||
|
||||
from PIL import Image
|
||||
from torch.utils.data import Dataset
|
||||
@@ -7,11 +8,11 @@ from torch.utils.data import Dataset
|
||||
class TestDataset(Dataset):
|
||||
"""Example dataset class for loading images from folder."""
|
||||
|
||||
def __init__(self, dir: str, transform):
|
||||
def __init__(self, dir: str, transform: Optional[Callable] = None):
|
||||
self.transform = transform
|
||||
self.images = [os.path.join(dir, fname) for fname in os.listdir(dir)]
|
||||
|
||||
def __getitem__(self, idx):
|
||||
def __getitem__(self, idx: int):
|
||||
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||
# image = Image.open(self.images[idx]).convert("RGB")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from typing import Optional
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
|
||||
@@ -19,18 +19,18 @@ class MNISTDataModule(LightningDataModule):
|
||||
|
||||
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,
|
||||
data_dir: str = "data/",
|
||||
train_val_test_split: Tuple[int, int, int] = (55_000, 5_000, 10_000),
|
||||
batch_size: int = 64,
|
||||
num_workers: int = 0,
|
||||
pin_memory: bool = False,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__()
|
||||
|
||||
self.data_dir = data_dir
|
||||
self.batch_size = batch_size
|
||||
self.train_val_test_split = train_val_test_split
|
||||
self.batch_size = batch_size
|
||||
self.num_workers = num_workers
|
||||
self.pin_memory = pin_memory
|
||||
|
||||
@@ -51,7 +51,7 @@ class MNISTDataModule(LightningDataModule):
|
||||
MNIST(self.data_dir, train=True, download=True)
|
||||
MNIST(self.data_dir, train=False, download=True)
|
||||
|
||||
def setup(self, stage=None):
|
||||
def setup(self, stage: Optional[str] = None):
|
||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
||||
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
|
||||
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
|
||||
@@ -1,12 +1,10 @@
|
||||
from typing import Any, Dict, List, Sequence, Tuple, Union
|
||||
from typing import Any, List
|
||||
|
||||
import hydra
|
||||
import torch
|
||||
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
|
||||
from src.models.modules.simple_dense_net import SimpleDenseNet
|
||||
|
||||
|
||||
class MNISTLitModel(LightningModule):
|
||||
@@ -26,12 +24,13 @@ class MNISTLitModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
optimizer,
|
||||
input_size=784,
|
||||
lin1_size=256,
|
||||
lin2_size=256,
|
||||
lin3_size=256,
|
||||
output_size=10,
|
||||
input_size: int = 784,
|
||||
lin1_size: int = 256,
|
||||
lin2_size: int = 256,
|
||||
lin3_size: int = 256,
|
||||
output_size: int = 10,
|
||||
lr: float = 0.001,
|
||||
weight_decay: float = 0.0005,
|
||||
**kwargs
|
||||
):
|
||||
super().__init__()
|
||||
@@ -58,17 +57,17 @@ class MNISTLitModel(LightningModule):
|
||||
"val/loss": [],
|
||||
}
|
||||
|
||||
def forward(self, x) -> torch.Tensor:
|
||||
def forward(self, x):
|
||||
return self.model(x)
|
||||
|
||||
def step(self, batch) -> Dict[str, torch.Tensor]:
|
||||
def step(self, batch):
|
||||
x, y = batch
|
||||
logits = self.forward(x)
|
||||
loss = self.criterion(logits, y)
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
return loss, preds, y
|
||||
|
||||
def training_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
def training_step(self, batch: Any, batch_idx: int):
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log train metrics
|
||||
@@ -81,7 +80,14 @@ class MNISTLitModel(LightningModule):
|
||||
# remember to always return loss from training_step, or else backpropagation will fail!
|
||||
return {"loss": loss, "preds": preds, "targets": targets}
|
||||
|
||||
def validation_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
def training_epoch_end(self, outputs: List[Any]):
|
||||
# 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_step(self, batch: Any, batch_idx: int):
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log val metrics
|
||||
@@ -91,7 +97,14 @@ class MNISTLitModel(LightningModule):
|
||||
|
||||
return {"loss": loss, "preds": preds, "targets": targets}
|
||||
|
||||
def test_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||
def validation_epoch_end(self, outputs: List[Any]):
|
||||
# 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 test_step(self, batch: Any, batch_idx: int):
|
||||
loss, preds, targets = self.step(batch)
|
||||
|
||||
# log test metrics
|
||||
@@ -99,31 +112,12 @@ class MNISTLitModel(LightningModule):
|
||||
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, "preds": preds, "targets": targets}
|
||||
|
||||
# [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)
|
||||
|
||||
# [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)
|
||||
|
||||
# [OPTIONAL METHOD]
|
||||
def test_epoch_end(self, outputs: List[Any]) -> None:
|
||||
def test_epoch_end(self, outputs: List[Any]):
|
||||
pass
|
||||
|
||||
def configure_optimizers(
|
||||
self,
|
||||
) -> Union[Optimizer, Tuple[Sequence[Optimizer], Sequence[Any]]]:
|
||||
def configure_optimizers(self):
|
||||
"""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.
|
||||
|
||||
@@ -131,5 +125,6 @@ class MNISTLitModel(LightningModule):
|
||||
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
|
||||
return torch.optim.Adam(
|
||||
params=self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay
|
||||
)
|
||||
File renamed without changes.
+1
-3
@@ -34,9 +34,7 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
|
||||
# Init Lightning model
|
||||
log.info(f"Instantiating model <{config.model._target_}>")
|
||||
model: LightningModule = hydra.utils.instantiate(
|
||||
config.model, optimizer=config.optimizer, _recursive_=False
|
||||
)
|
||||
model: LightningModule = hydra.utils.instantiate(config.model)
|
||||
|
||||
# Init Lightning callbacks
|
||||
callbacks: List[Callback] = []
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from PIL import Image
|
||||
from torchvision import transforms
|
||||
|
||||
from src.pl_models.mnist_model import MNISTLitModel
|
||||
from src.models.mnist_model import MNISTLitModel
|
||||
|
||||
|
||||
def predict():
|
||||
|
||||
@@ -44,7 +44,7 @@ def extras(config: DictConfig) -> None:
|
||||
config.trainer.gpus = 0
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
|
||||
|
||||
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
|
||||
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>")
|
||||
|
||||
Reference in new issue
Block a user