diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 22cb7de..d39e096 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,21 +4,21 @@ default_language_version: repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 - # supported hooks: https://pre-commit.com/hooks.html hooks: + # list of supported hooks: https://pre-commit.com/hooks.html - id: end-of-file-fixer - id: trailing-whitespace - - id: double-quote-string-fixer - id: debug-statements - id: detect-private-key - id: check-yaml - id: check-added-large-files - # - id: check-merge-conflict + - id: check-merge-conflict - # - repo: https://github.com/psf/black - # rev: 20.8b1 - # hooks: - # - id: black + - repo: https://github.com/psf/black + rev: 20.8b1 + hooks: + - id: black + # args: [--force-exclude, train.py] # - repo: https://github.com/PyCQA/isort # rev: 5.7.0 diff --git a/README.md b/README.md index 8da5753..2156d05 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -
+
-# PyTorch Lightning + Hydra Template +# PyTorch Lightning + Hydra Template A clean and scalable template to kickstart your deep learning project 🚀⚡🔥
Click on `Use this template` button above to initialize new repository. @@ -53,8 +53,8 @@ This template tries to be as generic as possible. You should be able to easily m ## Some Notes - ***Warning: this template currently uses development version of hydra which might be unstable (we wait until Hydra 1.1 is released).***
-- *Inspired by: -[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template), +- *Inspired by: +[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template), [drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science), [tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed), [Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest), @@ -68,7 +68,7 @@ This template tries to be as generic as possible. You should be able to easily m ## Project Structure -The directory structure of new project looks like this: +The directory structure of new project looks like this: ``` ├── configs <- Hydra configuration files │ ├── trainer <- Configurations of Lightning trainers @@ -77,7 +77,7 @@ The directory structure of new project looks like this: │ ├── callbacks <- Configurations of Lightning callbacks │ ├── logger <- Configurations of Lightning loggers │ ├── experiment <- Configurations of experiments -│ │ +│ │ │ ├── config.yaml <- Main project configuration file │ └── config_optuna.yaml <- Configuration of Optuna hyperparameter search │ @@ -100,7 +100,7 @@ The directory structure of new project looks like this: │ ├── models <- PyTorch Lightning models │ ├── transforms <- Data transformations │ └── utils <- Utility scripts -│ ├── inference_example.py <- Example of inference with trained model +│ ├── inference_example.py <- Example of inference with trained model │ └── template_utils.py <- Some extra template utilities │ ├── train.py <- Train model with chosen experiment configuration @@ -132,7 +132,7 @@ The directory structure of new project looks like this: - LogBestMetricScoresToWandb - LogF1PrecisionRecallHeatmapToWandb - LogConfusionMatrixToWandb -- ~~Validating correctness of config with Hydra schemas~~ (TODO) +- ~~Validating correctness of config with Hydra schemas~~ (TODO) - Method to pretty print configuration composed by Hydra at the start of the run, using [Rich](https://github.com/willmcgugan/rich/) library ([template_utils.py](src/utils/template_utils.py)) - Method to log chosen parts of Hydra config to all loggers ([template_utils.py](src/utils/template_utils.py)) - Example of hyperparameter search with Optuna sweeps ([config_optuna.yaml](configs/config_optuna.yaml)) @@ -151,7 +151,7 @@ Location: [configs/config.yaml](configs/config.yaml)
Main project config contains default training configuration.
It determines how config is composed when simply executing command: `python train.py` ```yaml -# to execute run with default training configuration simply run: +# to execute run with default training configuration simply run: # python train.py @@ -208,7 +208,7 @@ defaults: # all parameters below will be merged with parameters from default configurations set above # this allows you to overwrite only specified parameters -seed: 12345 +seed: 12345 trainer: max_epochs: 10 @@ -234,12 +234,12 @@ More advanced experiment configuration: defaults: - override /trainer: null - override /model: null - - override /datamodule: null + - override /datamodule: null - override /callbacks: null - override /logger: null # we override default configurations with nulls to prevent them from loading at all -# instead we define all modules and their paths directly in this config, +# instead we define all modules and their paths directly in this config, # so everything is stored in one place for more readibility seed: 12345 @@ -323,7 +323,7 @@ By default, logs have the following structure: │ │ └── ... │ ├── ... │ └── ... -│ +│ ``` You can change this structure by modifying paths in [config.yaml](configs/config.yaml).

@@ -350,8 +350,8 @@ You can use many of them at once (see [configs/logger/many_loggers.yaml](configs ## Tricks (TODO) -

@@ -361,13 +361,13 @@ choosing metric names with '/' for wandb -->

-### DELETE EVERYTHING ABOVE FOR YOUR PROJECT - +### DELETE EVERYTHING ABOVE FOR YOUR PROJECT + --- -
- -# Your Project Name +
+ +# Your Project Name Some short description.
@@ -443,7 +443,7 @@ python train.py -m '+experiment=glob(*)' trainer.max_epochs=10 logger=wandb To create a sweep over some hyperparameters run: ```yaml -# this will run 6 experiments one after the other, +# this will run 6 experiments one after the other, # each with different combination of batch_size and learning rate python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005 ``` diff --git a/configs/config_optuna.yaml b/configs/config_optuna.yaml index cf9394a..17f2325 100644 --- a/configs/config_optuna.yaml +++ b/configs/config_optuna.yaml @@ -1,7 +1,7 @@ # @package _global_ # example hyperparameter optimization of some experiment with optuna: -# python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple logger=wandb +# python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple logger=wandb defaults: # load everything from main config file diff --git a/configs/experiment/exp_example_full.yaml b/configs/experiment/exp_example_full.yaml index a664cd9..9cd7406 100644 --- a/configs/experiment/exp_example_full.yaml +++ b/configs/experiment/exp_example_full.yaml @@ -11,7 +11,7 @@ defaults: - override /logger: null # we override default configurations with nulls to prevent them from loading at all -# instead we define all modules and their paths directly in this config, +# instead we define all modules and their paths directly in this config, # so everything is stored in one place for more readibility seed: 12345 diff --git a/configs/experiment/exp_example_simple.yaml b/configs/experiment/exp_example_simple.yaml index 32af6da..0cfe942 100644 --- a/configs/experiment/exp_example_simple.yaml +++ b/configs/experiment/exp_example_simple.yaml @@ -13,7 +13,7 @@ defaults: # all parameters below will be merged with parameters from default configurations set above # this allows you to overwrite only specified parameters -seed: 12345 +seed: 12345 trainer: min_epochs: 1 diff --git a/configs/trainer/debug_trainer.yaml b/configs/trainer/debug_trainer.yaml index f73b0d1..73d9083 100644 --- a/configs/trainer/debug_trainer.yaml +++ b/configs/trainer/debug_trainer.yaml @@ -3,7 +3,7 @@ _target_: pytorch_lightning.Trainer # set -1 to train on all GPUs available, set 0 to train on CPU only -gpus: 0 +gpus: 0 # auto_select_gpus: True min_epochs: 3 @@ -13,7 +13,7 @@ max_epochs: 3 # overfit_batches: 10 # overfit on 5% of the training data -# overfit_batches: 0.05 +# overfit_batches: 0.05 # run validation loop every 5 training epochs # check_val_every_n_epoch: 5 @@ -25,7 +25,7 @@ val_check_interval: 0.5 # val_check_interval: 100 # run for 1 train, 1 val and 1 test batch -# fast_dev_run: True +fast_dev_run: False # use only 20% of the data limit_train_batches: 0.2 @@ -51,7 +51,7 @@ accumulate_grad_batches: 5 # no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that # accumulate_grad_batches: {5: 3, 10: 20} -# automatically find the largest batch size that fits into memory and is power of 2 +# automatically find the largest batch size that fits into memory and is power of 2 # (requires calling trainer.tune(model=model, datamodule=datamodule)) # auto_scale_batch_size:'power' diff --git a/configs/trainer/default_trainer.yaml b/configs/trainer/default_trainer.yaml index c9b472d..ba3a3cd 100644 --- a/configs/trainer/default_trainer.yaml +++ b/configs/trainer/default_trainer.yaml @@ -4,6 +4,7 @@ min_epochs: 1 max_epochs: 10 gradient_clip_val: 0.5 num_sanity_val_steps: 2 -progress_bar_refresh_rate: 20 +progress_bar_refresh_rate: 10 weights_summary: null default_root_dir: "lightning_logs/" +fast_dev_run: False diff --git a/src/callbacks/wandb_callbacks.py b/src/callbacks/wandb_callbacks.py index 17de768..8e5eede 100644 --- a/src/callbacks/wandb_callbacks.py +++ b/src/callbacks/wandb_callbacks.py @@ -22,7 +22,7 @@ def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger: if not logger: raise Exception( - "You're using wandb related callback, " + "You are using wandb related callback," "but WandbLogger was not found for some reason..." ) diff --git a/src/utils/template_utils.py b/src/utils/template_utils.py index 325c627..b727218 100644 --- a/src/utils/template_utils.py +++ b/src/utils/template_utils.py @@ -4,6 +4,7 @@ import pytorch_lightning as pl # hydra imports from omegaconf import DictConfig, OmegaConf from hydra.utils import get_original_cwd, to_absolute_path +from hydra.utils import log # logger imports import wandb @@ -21,6 +22,44 @@ from rich import print # normal imports from typing import List +import warnings +import logging + + +def extras(config: DictConfig): + """A couple of optional utilities, controlled with variables in main config file. + Simply delete those if you don' want them. + + Args: + config (DictConfig): [description] + """ + + # [OPTIONAL] Disable python warnings if + if config.get("disable_warnings"): + log.info(f"Disabling python warnings! <{config.disable_warnings=}>") + warnings.filterwarnings("ignore") + + # [OPTIONAL] Disable Lightning logs if + if config.get("disable_lightning_logs"): + log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>") + logging.getLogger("lightning").setLevel(logging.ERROR) + + # [OPTIONAL] Force debugger friendly configuration if + if config.trainer.get("fast_dev_run"): + log.info( + f"Forcing debugger friendly configuration! " + f"<{config.trainer.fast_dev_run=}>" + ) + # Debuggers don't like GPUs or multiprocessing + if config.trainer.get("gpus"): + config.trainer.gpus = 0 + if config.datamodule.get("num_workers"): + config.datamodule.num_workers = 0 + + # [OPTIONAL] Pretty print config using Rich library if + if config.get("print_config"): + log.info(f"Pretty printing config with Rich! <{config.print_config=}>") + print_config(config) def print_config(config: DictConfig): @@ -34,41 +73,41 @@ def print_config(config: DictConfig): # directory = to_absolute_path("configs/config.yaml") # print(f"Main config path: [link file://{directory}]{directory}") - style = 'dim' + style = "dim" - tree = Tree(f':gear: HYDRA CONFIG', style=style, guide_style=style) + tree = Tree(f":gear: TRAINING CONFIG", style=style, guide_style=style) - trainer = OmegaConf.to_yaml(config['trainer'], resolve=True) - trainer_branch = tree.add('Trainer', style=style, guide_style=style) - trainer_branch.add(Syntax(trainer, 'yaml')) + trainer = OmegaConf.to_yaml(config["trainer"], resolve=True) + trainer_branch = tree.add("Trainer", style=style, guide_style=style) + trainer_branch.add(Syntax(trainer, "yaml")) - model = OmegaConf.to_yaml(config['model'], resolve=True) - model_branch = tree.add('Model', style=style, guide_style=style) - model_branch.add(Syntax(model, 'yaml')) + model = OmegaConf.to_yaml(config["model"], resolve=True) + model_branch = tree.add("Model", style=style, guide_style=style) + model_branch.add(Syntax(model, "yaml")) - datamodule = OmegaConf.to_yaml(config['datamodule'], resolve=True) - datamodule_branch = tree.add('Datamodule', style=style, guide_style=style) - datamodule_branch.add(Syntax(datamodule, 'yaml')) + datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=True) + datamodule_branch = tree.add("Datamodule", style=style, guide_style=style) + datamodule_branch.add(Syntax(datamodule, "yaml")) - callbacks_branch = tree.add('Callbacks', style=style, guide_style=style) - if 'callbacks' in config: - for cb_name, cb_conf in config['callbacks'].items(): + callbacks_branch = tree.add("Callbacks", style=style, guide_style=style) + if "callbacks" in config: + for cb_name, cb_conf in config["callbacks"].items(): cb = callbacks_branch.add(cb_name, style=style, guide_style=style) - cb.add(Syntax(OmegaConf.to_yaml(cb_conf, resolve=True), 'yaml')) + cb.add(Syntax(OmegaConf.to_yaml(cb_conf, resolve=True), "yaml")) else: - callbacks_branch.add('None') + callbacks_branch.add("None") - logger_branch = tree.add('Logger', style=style, guide_style=style) - if 'logger' in config: - for lg_name, lg_conf in config['logger'].items(): + logger_branch = tree.add("Logger", style=style, guide_style=style) + if "logger" in config: + for lg_name, lg_conf in config["logger"].items(): lg = logger_branch.add(lg_name, style=style, guide_style=style) - lg.add(Syntax(OmegaConf.to_yaml(lg_conf, resolve=True), 'yaml')) + lg.add(Syntax(OmegaConf.to_yaml(lg_conf, resolve=True), "yaml")) else: - logger_branch.add('None') + logger_branch.add("None") - seed = config.get('seed', 'None') - seed_branch = tree.add(f'Seed', style=style, guide_style=style) - seed_branch.add(str(seed) + '\n') + seed = config.get("seed", "None") + seed_branch = tree.add(f"Seed", style=style, guide_style=style) + seed_branch.add(str(seed) + "\n") print(tree) @@ -95,32 +134,32 @@ def log_hparams_to_all_loggers( hparams = {} # save all params of model, datamodule and trainer - hparams.update(config['model']) - hparams.update(config['datamodule']) - hparams.update(config['trainer']) - hparams.pop('_target_') + hparams.update(config["model"]) + hparams.update(config["datamodule"]) + hparams.update(config["trainer"]) + hparams.pop("_target_") # save seed - hparams['seed'] = config.get('seed', 'None') + hparams["seed"] = config.get("seed", "None") # save targets - hparams['_class_model'] = config['model']['_target_'] - hparams['_class_datamodule'] = config['datamodule']['_target_'] + hparams["_class_model"] = config["model"]["_target_"] + hparams["_class_datamodule"] = config["datamodule"]["_target_"] # save sizes of each dataset - if hasattr(datamodule, 'data_train') and datamodule.data_train: - hparams['train_size'] = len(datamodule.data_train) - if hasattr(datamodule, 'data_val') and datamodule.data_val: - hparams['val_size'] = len(datamodule.data_val) - if hasattr(datamodule, 'data_test') and datamodule.data_test: - hparams['test_size'] = len(datamodule.data_test) + if hasattr(datamodule, "data_train") and datamodule.data_train: + hparams["train_size"] = len(datamodule.data_train) + if hasattr(datamodule, "data_val") and datamodule.data_val: + hparams["val_size"] = len(datamodule.data_val) + if hasattr(datamodule, "data_test") and datamodule.data_test: + hparams["test_size"] = len(datamodule.data_test) # save number of model parameters - hparams['#params_total'] = sum(p.numel() for p in model.parameters()) - hparams['#params_trainable'] = sum( + hparams["#params_total"] = sum(p.numel() for p in model.parameters()) + hparams["#params_trainable"] = sum( p.numel() for p in model.parameters() if p.requires_grad ) - hparams['#params_not_trainable'] = sum( + hparams["#params_not_trainable"] = sum( p.numel() for p in model.parameters() if not p.requires_grad ) diff --git a/tests/gpu_tests.sh b/tests/gpu_tests.sh new file mode 100644 index 0000000..fe95560 --- /dev/null +++ b/tests/gpu_tests.sh @@ -0,0 +1,33 @@ +# !/bin/bash +# Quick tests for gpu + +# To execute: +# bash tests/gpu_tests.sh + +# Method for printing test name +echo() { + termwidth="$(tput cols)" + padding="$(printf '%0.1s' ={1..500})" + printf '\e[33m%*.*s %s %*.*s\n\e[0m' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding" +} + +# Make python hide warnings +export PYTHONWARNINGS="ignore" + + +echo "TEST 1" +echo "Train on GPU (2 epochs)" +python train.py trainer.gpus=-1 trainer.max_epochs=2 \ +print_config=false + +echo "TEST 2" +echo "Train with 4 workers and cuda pinned memory (2 epochs)" +python train.py trainer.gpus=-1 trainer.max_epochs=2 \ +datamodule.num_workers=4 datamodule.pin_memory=True \ +print_config=false + +echo "TEST 3" +echo "Train with mixed-precision (apex, 2 epochs)" +python train.py trainer.gpus=-1 trainer.max_epochs=2 \ ++trainer.amp_backend='apex' +trainer.amp_level='O2' \ +print_config=false diff --git a/tests/smoke_tests.sh b/tests/smoke_tests.sh index 09f600f..fb7585e 100644 --- a/tests/smoke_tests.sh +++ b/tests/smoke_tests.sh @@ -15,83 +15,66 @@ echo() { export PYTHONWARNINGS="ignore" -# Test fast_dev_run (runs for 1 train, 1 val and 1 test batch) echo "TEST 1" -python train.py +trainer.fast_dev_run=True \ +echo "fast_dev_run=true (run 1 train, val and test loop using 1 batch)" +python train.py trainer.fast_dev_run=True \ print_config=false -# Overfit to 10 bathes echo "TEST 2" +echo "Overfit to 10 bathes" python train.py +trainer.overfit_batches=10 \ -trainer.min_epochs=20 trainer.max_epochs=20 \ +trainer.min_epochs=10 trainer.max_epochs=10 \ print_config=false -# Test 1 epoch on CPU echo "TEST 3" +echo "Train 1 epoch on CPU" python train.py trainer.gpus=0 trainer.max_epochs=1 \ print_config=false -# Test 1 epoch on GPU echo "TEST 4" -python train.py trainer.gpus=1 trainer.max_epochs=1 \ -print_config=false - -# Test on 25% of data -echo "TEST 5" +echo "Train on 25% of data" python train.py trainer.max_epochs=1 \ +trainer.limit_train_batches=0.25 +trainer.limit_val_batches=0.25 +trainer.limit_test_batches=0.25 \ print_config=false -# Test on 15 train batches, 10 val batches, 5 test batches -echo "TEST 6" +echo "TEST 5" +echo "Train on 15 train batches, 10 val batches, 5 test batches" python train.py trainer.max_epochs=1 \ +trainer.limit_train_batches=15 +trainer.limit_val_batches=10 +trainer.limit_test_batches=5 \ print_config=false -# Test all experiment configs +echo "TEST 6" +echo "Run all experiment configs for 2 epochs" +python train.py -m '+experiment=glob(*)' trainer.max_epochs=2 \ +print_config=false + echo "TEST 7" -python train.py -m '+experiment=glob(*)' trainer.gpus=1 trainer.max_epochs=2 \ -print_config=false - -# Test default hydra sweep over hyperparameters (runs 4 different combinations with fast_dev_run) -echo "TEST 8" +echo "Run default hydra sweep (executes 4 different combinations with fast_dev_run=True)" python train.py -m datamodule.batch_size=32,64 model.lr=0.001,0.003 \ -+trainer.fast_dev_run=True \ +trainer.fast_dev_run=True \ +print_config=false + +echo "TEST 8" +echo "Run with 16 bit precision" +python train.py trainer.max_epochs=1 +trainer.precision=16 \ print_config=false -# Test multiple workers and cuda pinned memory echo "TEST 9" -python train.py trainer.gpus=1 trainer.max_epochs=2 \ -datamodule.num_workers=4 datamodule.pin_memory=True \ -print_config=false +echo "Run with gradient accumulation" +python train.py trainer.max_epochs=1 +trainer.accumulate_grad_batches=10 \ +print_config=false -# Test 16 bit precision echo "TEST 10" -python train.py trainer.gpus=1 trainer.max_epochs=1 precision=16 \ +echo "Run validation loop twice per epoch" +python train.py trainer.max_epochs=2 +trainer.val_check_interval=0.5 \ print_config=false -# Test gradient accumulation echo "TEST 11" -python train.py trainer.gpus=1 trainer.max_epochs=1 accumulate_grad_batches=10 \ +echo "Run with CSVLogger (2 epochs)" +python train.py logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \ print_config=false -# Test running validation loop twice per epoch echo "TEST 12" -python train.py trainer.gpus=1 trainer.max_epochs=2 val_check_interval=0.5 \ -print_config=false - -# Test CSV logger (5 epochs) -echo "TEST 13" -python train.py logger=csv_logger trainer.min_epochs=5 trainer.max_epochs=5 trainer.gpus=1 \ -print_config=false - -# Test TensorBoard logger (5 epochs) -echo "TEST 14" -python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=5 trainer.gpus=1 \ -print_config=false - -# Test mixed-precision training -echo "TEST 15" -python train.py trainer.gpus=1 trainer.max_epochs=3 \ -+amp_backend='apex' amp_level='O2' \ +echo "Run with TensorBoardLogger (2 epochs)" +python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \ print_config=false diff --git a/tests/sweep_tests.sh b/tests/sweep_tests.sh index f74b0be..95aa9bb 100644 --- a/tests/sweep_tests.sh +++ b/tests/sweep_tests.sh @@ -4,6 +4,7 @@ # To execute: # bash tests/sweep_tests.sh +# Method for printing test name echo() { termwidth="$(tput cols)" padding="$(printf '%0.1s' ={1..500})" @@ -13,18 +14,19 @@ echo() { # Make python hide warnings export PYTHONWARNINGS="ignore" -# Test default hydra sweep with wandb logging + echo "TEST 1" +echo "Default hydra sweep with wandb logging" python train.py -m datamodule.batch_size=64,128 model.lr=0.001,0.003 \ +experiment=exp_example_simple \ -trainer.gpus=1 trainer.max_epochs=2 seed=12345 \ +trainer.gpus=-1 trainer.max_epochs=2 \ datamodule.num_workers=12 datamodule.pin_memory=True \ logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet" -# Test optuna sweep with wandb logging echo "TEST 2" +echo "Optuna sweep with wandb logging" python train.py -m --config-name config_optuna.yaml \ +experiment=exp_example_simple \ -trainer.gpus=1 trainer.max_epochs=5 seed=12345 \ +trainer.gpus=-1 trainer.max_epochs=5 \ datamodule.num_workers=12 datamodule.pin_memory=True \ logger=wandb logger.wandb.project="env_tests" logger.wandb.group="Optuna_MNIST_SimpleDenseNet" diff --git a/train.py b/train.py index 51d452f..bea8245 100644 --- a/train.py +++ b/train.py @@ -5,6 +5,7 @@ from pytorch_lightning import seed_everything # hydra imports from omegaconf import DictConfig +from hydra.utils import log import hydra # normal imports @@ -18,50 +19,49 @@ from src.utils import template_utils as utils def train(config: DictConfig): - # Disable python warnings - if config['disable_warnings']: - warnings.filterwarnings('ignore') - - # Disable PyTorch Lightning logs - if config['disable_lightning_logs']: - logging.getLogger('lightning').setLevel(logging.ERROR) - - # Pretty print config using Rich library - if config['print_config']: - utils.print_config(config) + # A couple of optional utilities: + # - disabling warnings, + # - printing config with Rich, + # - forcing debug friendly configuration + # You can safely get rid of this line if you don't want those + utils.extras(config) # Set seed for random number generators in pytorch, numpy and python.random - if 'seed' in config: - seed_everything(config['seed']) + if "seed" in config: + seed_everything(config.seed) - # Init PyTorch Lightning model âš¡ - model: LightningModule = hydra.utils.instantiate(config['model']) + # Init Lightning model âš¡ + log.info(f"Instantiating model <{config.model._target_}>") + model: LightningModule = hydra.utils.instantiate(config.model) - # Init PyTorch Lightning datamodule âš¡ - datamodule: LightningDataModule = hydra.utils.instantiate(config['datamodule']) - datamodule.prepare_data() - datamodule.setup() + # Init Lightning datamodule âš¡ + log.info(f"Instantiating datamodule <{config.datamodule._target_}>") + datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule) - # Init PyTorch Lightning callbacks + # Init Lightning callbacks callbacks: List[Callback] = [] - if 'callbacks' in config: - for _, cb_conf in config['callbacks'].items(): - if '_target_' in cb_conf: + 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 PyTorch Lightning loggers + # Init Lightning loggers logger: List[LightningLoggerBase] = [] - if 'logger' in config: - for _, lg_conf in config['logger'].items(): - if '_target_' in lg_conf: + 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 PyTorch Lightning trainer âš¡ + # Init Lightning trainer âš¡ + log.info(f"Instantiating trainer <{config.trainer._target_}>") trainer: Trainer = hydra.utils.instantiate( - config['trainer'], callbacks=callbacks, logger=logger + config.trainer, callbacks=callbacks, logger=logger ) # Send some parameters from config to all lightning loggers + log.info(f"Logging hyperparameters!") utils.log_hparams_to_all_loggers( config=config, model=model, @@ -72,12 +72,16 @@ def train(config: DictConfig): ) # Train the model âš¡ + log.info(f"Starting training!") trainer.fit(model=model, datamodule=datamodule) # Evaluate model on test set after training - trainer.test() + if not config.trainer.get("fast_dev_run"): + log.info(f"Starting testing!") + trainer.test() # Make sure everything closed properly + log.info(f"Finalizing!") utils.finish( config=config, model=model, @@ -87,16 +91,18 @@ def train(config: DictConfig): logger=logger, ) - # Return metric score for optuna optimization - optimized_metric = config.get('optimized_metric', None) + # Return metric score for Optuna optimization + optimized_metric = config.get("optimized_metric") if optimized_metric: - return trainer.callback_metrics[optimized_metric] + result = trainer.callback_metrics[optimized_metric] + log.info(f"Returning metric for Optuna: <{optimized_metric}={result}>") + return result -@hydra.main(config_path='configs/', config_name='config.yaml') +@hydra.main(config_path="configs/", config_name="config.yaml") def main(config: DictConfig): return train(config) -if __name__ == '__main__': +if __name__ == "__main__": main()