Multiple pipelines - training and evaluation (#250)
- introduce best practice for multiple pipelines - Implement evaluation pipeline - allow for using relative ckpt paths - general refactoring - update README.md
This commit is contained in:
1 parent
02d3b65aaa
commit
fe4e61edc1
25 files changed
+347
-185
No files matched your search
@@ -0,0 +1,57 @@
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
import hydra
|
||||
from omegaconf import DictConfig
|
||||
from pytorch_lightning import LightningDataModule, LightningModule, Trainer, seed_everything
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
|
||||
from src import utils
|
||||
|
||||
log = utils.get_logger(__name__)
|
||||
|
||||
|
||||
def test(config: DictConfig) -> None:
|
||||
"""Contains minimal example of the testing pipeline.
|
||||
Evaluates given checkpoint on a testset.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
|
||||
Returns:
|
||||
None
|
||||
"""
|
||||
|
||||
# Set seed for random number generators in pytorch, numpy and python.random
|
||||
if config.get("seed"):
|
||||
seed_everything(config.seed, workers=True)
|
||||
|
||||
# Convert relative ckpt path to absolute path if necessary
|
||||
if not os.path.isabs(config.ckpt_path):
|
||||
config.ckpt_path = os.path.join(hydra.utils.get_original_cwd(), config.ckpt_path)
|
||||
|
||||
# Init lightning datamodule
|
||||
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
|
||||
|
||||
# Init lightning model
|
||||
log.info(f"Instantiating model <{config.model._target_}>")
|
||||
model: LightningModule = hydra.utils.instantiate(config.model)
|
||||
|
||||
# Init lightning loggers
|
||||
logger: List[LightningLoggerBase] = []
|
||||
if "logger" in config:
|
||||
for _, lg_conf in config.logger.items():
|
||||
if "_target_" in lg_conf:
|
||||
log.info(f"Instantiating logger <{lg_conf._target_}>")
|
||||
logger.append(hydra.utils.instantiate(lg_conf))
|
||||
|
||||
# Init lightning trainer
|
||||
log.info(f"Instantiating trainer <{config.trainer._target_}>")
|
||||
trainer: Trainer = hydra.utils.instantiate(config.trainer, logger=logger)
|
||||
|
||||
# Log hyperparameters
|
||||
trainer.logger.log_hyperparams({"ckpt_path": config.ckpt_path})
|
||||
|
||||
log.info("Starting testing!")
|
||||
trainer.test(model=model, datamodule=datamodule, ckpt_path=config.ckpt_path)
|
||||
@@ -1,3 +1,4 @@
|
||||
import os
|
||||
from typing import List, Optional
|
||||
|
||||
import hydra
|
||||
@@ -17,8 +18,8 @@ log = utils.get_logger(__name__)
|
||||
|
||||
|
||||
def train(config: DictConfig) -> Optional[float]:
|
||||
"""Contains training pipeline.
|
||||
Instantiates all PyTorch Lightning objects from config.
|
||||
"""Contains the training pipeline.
|
||||
Can additionally evaluate model on a testset, using best weights achieved during training.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
@@ -31,6 +32,13 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
if config.get("seed"):
|
||||
seed_everything(config.seed, workers=True)
|
||||
|
||||
# Convert relative ckpt path to absolute path if necessary
|
||||
ckpt_path = config.trainer.get("resume_from_checkpoint")
|
||||
if ckpt_path and not os.path.isabs(ckpt_path):
|
||||
config.trainer.resume_from_checkpoint = os.path.join(
|
||||
hydra.utils.get_original_cwd(), ckpt_path
|
||||
)
|
||||
|
||||
# Init lightning datamodule
|
||||
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
|
||||
@@ -87,9 +95,11 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
score = trainer.callback_metrics.get(optimized_metric)
|
||||
|
||||
# Test the model
|
||||
if config.get("test_after_training") and not config.trainer.get("fast_dev_run"):
|
||||
if config.get("test"):
|
||||
ckpt_path = "best"
|
||||
if not config.get("train") or config.trainer.get("fast_dev_run"):
|
||||
ckpt_path = None
|
||||
log.info("Starting testing!")
|
||||
ckpt_path = None if not config.get("train") else "best"
|
||||
trainer.test(model=model, datamodule=datamodule, ckpt_path=ckpt_path)
|
||||
|
||||
# Make sure everything closed properly
|
||||
@@ -104,7 +114,7 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
)
|
||||
|
||||
# Print path to best checkpoint
|
||||
if not config.trainer.get("fast_dev_run"):
|
||||
if not config.trainer.get("fast_dev_run") and config.trainer.get("train"):
|
||||
log.info(f"Best model ckpt at {trainer.checkpoint_callback.best_model_path}")
|
||||
|
||||
# Return metric score for hyperparameter optimization
|
||||
+13
-7
@@ -34,10 +34,11 @@ log = get_logger(__name__)
|
||||
|
||||
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""Optional utilities, controlled by hydra config.
|
||||
"""Applies optional utilities, controlled by config flags.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
Utilities:
|
||||
- Ignoring python warnings
|
||||
- Rich config printing
|
||||
"""
|
||||
|
||||
# disable python warnings if <config.ignore_warnings=True>
|
||||
@@ -45,6 +46,11 @@ def extras(config: DictConfig) -> None:
|
||||
log.info("Disabling python warnings! <config.ignore_warnings=True>")
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# pretty print config tree using Rich library if <config.print_config=True>
|
||||
if config.get("print_config"):
|
||||
log.info("Printing config tree with Rich! <config.print_config=True>")
|
||||
print_config(config, resolve=True)
|
||||
|
||||
|
||||
@rank_zero_only
|
||||
def print_config(
|
||||
@@ -91,8 +97,8 @@ def print_config(
|
||||
|
||||
rich.print(tree)
|
||||
|
||||
with open("config_tree.log", "w") as fp:
|
||||
rich.print(tree, file=fp)
|
||||
with open("config_tree.log", "w") as file:
|
||||
rich.print(tree, file=file)
|
||||
|
||||
|
||||
@rank_zero_only
|
||||
@@ -104,10 +110,10 @@ def log_hyperparameters(
|
||||
callbacks: List[pl.Callback],
|
||||
logger: List[pl.loggers.LightningLoggerBase],
|
||||
) -> None:
|
||||
"""Controls which hyperparameters are saved by Lightning loggers.
|
||||
"""Controls which config parts are saved by Lightning loggers.
|
||||
|
||||
Additionaly saves:
|
||||
- number of model parameters
|
||||
- number of model parameters
|
||||
"""
|
||||
|
||||
hparams = {}
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
# use this folder for storing third party code that cannot be installed using pip/conda
|
||||
Reference in new issue
Block a user