Dev (#98)
* remove conda_env_cpu * remove setup.py * optimize tab completion by nesting imports * add .env * fix rich printing bug * general improvements * update readme
This commit is contained in:
1 parent
5f1c85e9bf
commit
d571a4e2c2
22 files changed
+253
-221
No files matched your search
@@ -1 +0,0 @@
|
||||
# makes 'src' a Python module
|
||||
@@ -0,0 +1,99 @@
|
||||
# lightning imports
|
||||
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
|
||||
|
||||
# normal imports
|
||||
from typing import List, Optional
|
||||
|
||||
# src imports
|
||||
from src.utils import template_utils
|
||||
|
||||
|
||||
def train(config: DictConfig) -> Optional[float]:
|
||||
"""Contains training pipeline.
|
||||
Instantiates all PyTorch Lightning objects from config.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
|
||||
Returns:
|
||||
Optional[float]: Metric score for hyperparameter optimization.
|
||||
"""
|
||||
|
||||
# Set seed for random number generators in pytorch, numpy and python.random
|
||||
if "seed" in config:
|
||||
seed_everything(config.seed)
|
||||
|
||||
# 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, optimizer=config.optimizer, _recursive_=False
|
||||
)
|
||||
|
||||
# Init Lightning callbacks
|
||||
callbacks: List[Callback] = []
|
||||
if "callbacks" in config:
|
||||
for _, cb_conf in config["callbacks"].items():
|
||||
if "_target_" in cb_conf:
|
||||
log.info(f"Instantiating callback <{cb_conf._target_}>")
|
||||
callbacks.append(hydra.utils.instantiate(cb_conf))
|
||||
|
||||
# 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, callbacks=callbacks, logger=logger
|
||||
)
|
||||
|
||||
# Send some parameters from config to all lightning loggers
|
||||
log.info("Logging hyperparameters!")
|
||||
template_utils.log_hyperparameters(
|
||||
config=config,
|
||||
model=model,
|
||||
datamodule=datamodule,
|
||||
trainer=trainer,
|
||||
callbacks=callbacks,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Train the model
|
||||
log.info("Starting training!")
|
||||
trainer.fit(model=model, datamodule=datamodule)
|
||||
|
||||
# Evaluate model on test set after training
|
||||
if not config.trainer.get("fast_dev_run"):
|
||||
log.info("Starting testing!")
|
||||
trainer.test()
|
||||
|
||||
# Make sure everything closed properly
|
||||
log.info("Finalizing!")
|
||||
template_utils.finish(
|
||||
config=config,
|
||||
model=model,
|
||||
datamodule=datamodule,
|
||||
trainer=trainer,
|
||||
callbacks=callbacks,
|
||||
logger=logger,
|
||||
)
|
||||
|
||||
# Return metric score for Optuna optimization
|
||||
optimized_metric = config.get("optimized_metric")
|
||||
if optimized_metric:
|
||||
return trainer.callback_metrics[optimized_metric]
|
||||
@@ -5,5 +5,5 @@ mnist_train_transforms = transforms.Compose(
|
||||
)
|
||||
|
||||
mnist_test_transforms = transforms.Compose(
|
||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
[transforms.ToTensor(), transforms.Resize((28, 28)), transforms.Normalize((0.1307,), (0.3081,))]
|
||||
)
|
||||
@@ -11,10 +11,15 @@ def predict():
|
||||
"""
|
||||
|
||||
# ckpt can be also a URL!
|
||||
CKPT_PATH = "epoch=0.ckpt"
|
||||
CKPT_PATH = "last.ckpt"
|
||||
|
||||
# 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)
|
||||
|
||||
# print model hyperparameters
|
||||
print(trained_model.hparams)
|
||||
|
||||
# switch to evaluation mode
|
||||
trained_model.eval()
|
||||
|
||||
@@ -89,7 +89,9 @@ def print_config(
|
||||
|
||||
# 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)
|
||||
@@ -111,7 +113,10 @@ def print_config(
|
||||
cfg_str = OmegaConf.to_yaml(nested_config_section, resolve=resolve)
|
||||
nested_branch.add(Syntax(cfg_str, "yaml"))
|
||||
else:
|
||||
cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
|
||||
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"))
|
||||
|
||||
print(tree)
|
||||
|
||||
Reference in new issue
Block a user