Release/1.2 (#198)

* update template to pytorch 1.10+ and lightning 1.5+
* add experiment mode to all experiment configs and implement special logging paths for experiment mode
* add `MaxMetric` to model, for computation of best so far validation accuracy
* add RichProgressBar to default callbacks
* get rid of trick for preventing auto hparam logging, since lightning now supports it with `self.save_hyperparameters(logger=False)`
* add `self.save_hyperparameters()` to datamodule since lightinng now supports it
* deprecate Apex support
* deprecate bash script for conda setup
* change `terminate_on_nan` debug option to `detect_anomaly` for compatibility with lightning v1.5
* specify model and datamodule during `trainer.test()`, for compatibility with lightning v1.5
* remove `configs/trainer/all_params.yaml`
* make hyperparameter optimization compatible with lightning v1.5
* general documentation improvements
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-11-05 12:38:44 +01:00
1 parent 6159c413f2
commit 9468ef91c5
29 files changed
+278 -330

No files matched your search

+12 -12
View File
@@ -44,7 +44,7 @@ class WatchModel(Callback):
@rank_zero_only
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)
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq, log_graph=True)
class UploadCodeAsArtifact(Callback):
@@ -69,22 +69,22 @@ class UploadCodeAsArtifact(Callback):
code = wandb.Artifact("project-source", type="code")
if self.use_git:
# get .git folder
# https://alexwlchan.net/2020/11/a-python-function-to-ignore-a-path-with-git-info-exclude/
# get .git folder path
git_dir_path = Path(
subprocess.check_output(["git", "rev-parse", "--git-dir"]).strip().decode("utf8")
).resolve()
for path in Path(self.code_dir).resolve().rglob("*"):
if (
path.is_file()
# ignore files in .git
and not str(path).startswith(str(git_dir_path)) # noqa: W503
# ignore files ignored by git
and ( # noqa: W503
subprocess.run(["git", "check-ignore", "-q", str(path)]).returncode == 1
)
):
# don't upload files ignored by git
# https://alexwlchan.net/2020/11/a-python-function-to-ignore-a-path-with-git-info-exclude/
command = ["git", "check-ignore", "-q", str(path)]
not_ignored = subprocess.run(command).returncode == 1
# don't upload files from .git folder
not_git = not str(path).startswith(str(git_dir_path))
if path.is_file() and not_git and not_ignored:
code.add_file(str(path), name=str(path.relative_to(self.code_dir)))
else:
+25 -22
View File
@@ -35,12 +35,11 @@ class MNISTDataModule(LightningDataModule):
):
super().__init__()
self.data_dir = data_dir
self.train_val_test_split = train_val_test_split
self.batch_size = batch_size
self.num_workers = num_workers
self.pin_memory = pin_memory
# this line allows to access init params with 'self.hparams' attribute
# it also ensures init params will be stored in ckpt
self.save_hyperparameters(logger=False)
# data transformations
self.transforms = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
)
@@ -59,44 +58,48 @@ class MNISTDataModule(LightningDataModule):
def prepare_data(self):
"""Download data if needed. This method is called only from a single GPU.
Do not use it to assign state (self.x = y)."""
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
MNIST(self.hparams.data_dir, train=True, download=True)
MNIST(self.hparams.data_dir, train=False, download=True)
def setup(self, stage: Optional[str] = None):
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
This method is called by lightning separately when using `trainer.fit()` and `trainer.test()`!
The `stage` can be used to differentiate whether the `setup()` is called before trainer.fit()` or `trainer.test()`."""
if not self.data_train or not self.data_val or not self.data_test:
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
This method is called by lightning twice for `trainer.fit()` and `trainer.test()`, so be careful if you do a random split!
The `stage` can be used to differentiate whether it's called before trainer.fit()` or `trainer.test()`."""
# load datasets only if they're not loaded already
if not self.data_train and not self.data_val and not self.data_test:
trainset = MNIST(self.hparams.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.hparams.data_dir, train=False, transform=self.transforms)
dataset = ConcatDataset(datasets=[trainset, testset])
self.data_train, self.data_val, self.data_test = random_split(
dataset, self.train_val_test_split, generator=torch.Generator().manual_seed(42)
dataset=dataset,
lengths=self.hparams.train_val_test_split,
generator=torch.Generator().manual_seed(42),
)
def train_dataloader(self):
return DataLoader(
dataset=self.data_train,
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=True,
)
def val_dataloader(self):
return DataLoader(
dataset=self.data_val,
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=False,
)
def test_dataloader(self):
return DataLoader(
dataset=self.data_test,
batch_size=self.batch_size,
num_workers=self.num_workers,
pin_memory=self.pin_memory,
batch_size=self.hparams.batch_size,
num_workers=self.hparams.num_workers,
pin_memory=self.hparams.pin_memory,
shuffle=False,
)
+21 -12
View File
@@ -2,6 +2,7 @@ from typing import Any, List
import torch
from pytorch_lightning import LightningModule
from torchmetrics import MaxMetric
from torchmetrics.classification.accuracy import Accuracy
from src.models.modules.simple_dense_net import SimpleDenseNet
@@ -34,9 +35,9 @@ class MNISTLitModel(LightningModule):
):
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()
# this line allows to access init params with 'self.hparams' attribute
# it also ensures init params will be stored in ckpt
self.save_hyperparameters(logger=False)
self.model = SimpleDenseNet(hparams=self.hparams)
@@ -45,9 +46,12 @@ class MNISTLitModel(LightningModule):
# 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.train_acc = Accuracy()
self.val_acc = Accuracy()
self.test_acc = Accuracy()
# for logging best accuracy achieved so far
self.val_acc_best = MaxMetric()
def forward(self, x: torch.Tensor):
return self.model(x)
@@ -63,13 +67,13 @@ class MNISTLitModel(LightningModule):
loss, preds, targets = self.step(batch)
# log train metrics
acc = self.train_accuracy(preds, targets)
acc = self.train_acc(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 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!
# 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}
def training_epoch_end(self, outputs: List[Any]):
@@ -80,20 +84,25 @@ class MNISTLitModel(LightningModule):
loss, preds, targets = self.step(batch)
# log val metrics
acc = self.val_accuracy(preds, targets)
acc = self.val_acc(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)
return {"loss": loss, "preds": preds, "targets": targets}
def validation_epoch_end(self, outputs: List[Any]):
pass
acc = self.val_acc.compute() # get val accuracy from current epoch
self.val_acc.reset() # reset is necessary if you're using `num_sanity_val_steps` in trainer
# compute and log best so far val accuracy
self.val_acc_best.update(acc)
self.log("val/acc_best", self.val_acc_best.compute(), on_epoch=True, prog_bar=True)
def test_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log test metrics
acc = self.test_accuracy(preds, targets)
acc = self.test_acc(preds, targets)
self.log("test/loss", loss, on_step=False, on_epoch=True)
self.log("test/acc", acc, on_step=False, on_epoch=True)
+7 -6
View File
@@ -76,10 +76,13 @@ def train(config: DictConfig) -> Optional[float]:
log.info("Starting training!")
trainer.fit(model=model, datamodule=datamodule)
# Evaluate model on test set, using the best model achieved during training
# Get metric score for hyperparameter optimization
score = trainer.callback_metrics.get(config.get("optimized_metric"))
# Test the model
if config.get("test_after_training") and not config.trainer.get("fast_dev_run"):
log.info("Starting testing!")
trainer.test()
trainer.test(model=model, datamodule=datamodule, ckpt_path="best")
# Make sure everything closed properly
log.info("Finalizing!")
@@ -94,9 +97,7 @@ def train(config: DictConfig) -> Optional[float]:
# Print path to best checkpoint
if not config.trainer.get("fast_dev_run"):
log.info(f"Best model ckpt: {trainer.checkpoint_callback.best_model_path}")
log.info(f"Best model ckpt at {trainer.checkpoint_callback.best_model_path}")
# Return metric score for hyperparameter optimization
optimized_metric = config.get("optimized_metric")
if optimized_metric:
return trainer.callback_metrics[optimized_metric]
return score
+16 -16
View File
@@ -10,13 +10,21 @@ from pytorch_lightning.utilities import rank_zero_only
def get_logger(name=__name__) -> logging.Logger:
"""Initializes multi-GPU-friendly python logger."""
"""Initializes multi-GPU-friendly python command line logger."""
logger = logging.getLogger(name)
# this ensures all logging levels get marked with the rank zero decorator
# otherwise logs would get multiplied for each GPU process in multi-GPU setup
for level in ("debug", "info", "warning", "error", "exception", "fatal", "critical"):
for level in (
"debug",
"info",
"warning",
"error",
"exception",
"fatal",
"critical",
):
setattr(logger, level, rank_zero_only(getattr(logger, level)))
return logger
@@ -101,14 +109,10 @@ def print_config(
rich.print(tree)
with open("config_tree.txt", "w") as fp:
with open("config_tree.log", "w") as fp:
rich.print(tree, file=fp)
def empty(*args, **kwargs):
pass
@rank_zero_only
def log_hyperparameters(
config: DictConfig,
@@ -121,7 +125,7 @@ def log_hyperparameters(
"""This method controls which parameters from Hydra config are saved by Lightning loggers.
Additionaly saves:
- number of trainable model parameters
- number of model parameters
"""
hparams = {}
@@ -130,28 +134,24 @@ def log_hyperparameters(
hparams["trainer"] = config["trainer"]
hparams["model"] = config["model"]
hparams["datamodule"] = config["datamodule"]
if "seed" in config:
hparams["seed"] = config["seed"]
if "callbacks" in config:
hparams["callbacks"] = config["callbacks"]
# save number of model parameters
hparams["model/params_total"] = sum(p.numel() for p in model.parameters())
hparams["model/params_trainable"] = sum(
hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
hparams["model/params/trainable"] = sum(
p.numel() for p in model.parameters() if p.requires_grad
)
hparams["model/params_not_trainable"] = sum(
hparams["model/params/non_trainable"] = sum(
p.numel() for p in model.parameters() if not p.requires_grad
)
# send hparams to all loggers
trainer.logger.log_hyperparams(hparams)
# disable logging any more hyperparameters for all loggers
# this is just a trick to prevent trainer from logging hparams of model,
# since we already did that above
trainer.logger.log_hyperparams = empty
def finish(
config: DictConfig,