Dev (#82)
* fix code formatting * add module init logging * general improvements
This commit is contained in:
1 parent
caa566dfd8
commit
b45d3b31ec
13 files changed
+226
-162
No files matched your search
@@ -4,21 +4,21 @@ default_language_version:
|
|||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v3.2.0
|
rev: v3.2.0
|
||||||
# supported hooks: https://pre-commit.com/hooks.html
|
|
||||||
hooks:
|
hooks:
|
||||||
|
# list of supported hooks: https://pre-commit.com/hooks.html
|
||||||
- id: end-of-file-fixer
|
- id: end-of-file-fixer
|
||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
- id: double-quote-string-fixer
|
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- id: detect-private-key
|
- id: detect-private-key
|
||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
# - id: check-merge-conflict
|
- id: check-merge-conflict
|
||||||
|
|
||||||
# - repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
# rev: 20.8b1
|
rev: 20.8b1
|
||||||
# hooks:
|
hooks:
|
||||||
# - id: black
|
- id: black
|
||||||
|
# args: [--force-exclude, train.py]
|
||||||
|
|
||||||
# - repo: https://github.com/PyCQA/isort
|
# - repo: https://github.com/PyCQA/isort
|
||||||
# rev: 5.7.0
|
# rev: 5.7.0
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# PyTorch Lightning + Hydra Template
|
# PyTorch Lightning + Hydra Template
|
||||||
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
|
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
|
||||||
Click on <b>`Use this template`</b> button above to initialize new repository.
|
Click on <b>`Use this template`</b> 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
|
## Some Notes
|
||||||
- ***Warning: this template currently uses development version of hydra which might be unstable (we wait until Hydra 1.1 is released).*** <br>
|
- ***Warning: this template currently uses development version of hydra which might be unstable (we wait until Hydra 1.1 is released).*** <br>
|
||||||
- *Inspired by:
|
- *Inspired by:
|
||||||
[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),
|
[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),
|
||||||
[drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),
|
[drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),
|
||||||
[tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),
|
[tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),
|
||||||
[Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest),
|
[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
|
## Project Structure
|
||||||
The directory structure of new project looks like this:
|
The directory structure of new project looks like this:
|
||||||
```
|
```
|
||||||
├── configs <- Hydra configuration files
|
├── configs <- Hydra configuration files
|
||||||
│ ├── trainer <- Configurations of Lightning trainers
|
│ ├── trainer <- Configurations of Lightning trainers
|
||||||
@@ -77,7 +77,7 @@ The directory structure of new project looks like this:
|
|||||||
│ ├── callbacks <- Configurations of Lightning callbacks
|
│ ├── callbacks <- Configurations of Lightning callbacks
|
||||||
│ ├── logger <- Configurations of Lightning loggers
|
│ ├── logger <- Configurations of Lightning loggers
|
||||||
│ ├── experiment <- Configurations of experiments
|
│ ├── experiment <- Configurations of experiments
|
||||||
│ │
|
│ │
|
||||||
│ ├── config.yaml <- Main project configuration file
|
│ ├── config.yaml <- Main project configuration file
|
||||||
│ └── config_optuna.yaml <- Configuration of Optuna hyperparameter search
|
│ └── 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
|
│ ├── models <- PyTorch Lightning models
|
||||||
│ ├── transforms <- Data transformations
|
│ ├── transforms <- Data transformations
|
||||||
│ └── utils <- Utility scripts
|
│ └── 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
|
│ └── template_utils.py <- Some extra template utilities
|
||||||
│
|
│
|
||||||
├── train.py <- Train model with chosen experiment configuration
|
├── train.py <- Train model with chosen experiment configuration
|
||||||
@@ -132,7 +132,7 @@ The directory structure of new project looks like this:
|
|||||||
- LogBestMetricScoresToWandb
|
- LogBestMetricScoresToWandb
|
||||||
- LogF1PrecisionRecallHeatmapToWandb
|
- LogF1PrecisionRecallHeatmapToWandb
|
||||||
- LogConfusionMatrixToWandb
|
- 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 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))
|
- 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))
|
- 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)<br>
|
|||||||
Main project config contains default training configuration.<br>
|
Main project config contains default training configuration.<br>
|
||||||
It determines how config is composed when simply executing command: `python train.py`
|
It determines how config is composed when simply executing command: `python train.py`
|
||||||
```yaml
|
```yaml
|
||||||
# to execute run with default training configuration simply run:
|
# to execute run with default training configuration simply run:
|
||||||
# python train.py
|
# python train.py
|
||||||
|
|
||||||
|
|
||||||
@@ -208,7 +208,7 @@ defaults:
|
|||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
@@ -234,12 +234,12 @@ More advanced experiment configuration:
|
|||||||
defaults:
|
defaults:
|
||||||
- override /trainer: null
|
- override /trainer: null
|
||||||
- override /model: null
|
- override /model: null
|
||||||
- override /datamodule: null
|
- override /datamodule: null
|
||||||
- override /callbacks: null
|
- override /callbacks: null
|
||||||
- override /logger: null
|
- override /logger: null
|
||||||
|
|
||||||
# we override default configurations with nulls to prevent them from loading at all
|
# 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
|
# so everything is stored in one place for more readibility
|
||||||
|
|
||||||
seed: 12345
|
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).
|
You can change this structure by modifying paths in [config.yaml](configs/config.yaml).
|
||||||
<br><br>
|
<br><br>
|
||||||
@@ -350,8 +350,8 @@ You can use many of them at once (see [configs/logger/many_loggers.yaml](configs
|
|||||||
|
|
||||||
## Tricks
|
## Tricks
|
||||||
(TODO)
|
(TODO)
|
||||||
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup,
|
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup,
|
||||||
k-fold cross validation, linter, faster tab completion import trick,
|
k-fold cross validation, linter, faster tab completion import trick,
|
||||||
choosing metric names with '/' for wandb -->
|
choosing metric names with '/' for wandb -->
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
@@ -361,13 +361,13 @@ choosing metric names with '/' for wandb -->
|
|||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
### DELETE EVERYTHING ABOVE FOR YOUR PROJECT
|
### DELETE EVERYTHING ABOVE FOR YOUR PROJECT
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# Your Project Name
|
# Your Project Name
|
||||||
Some short description.
|
Some short description.
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
@@ -443,7 +443,7 @@ python train.py -m '+experiment=glob(*)' trainer.max_epochs=10 logger=wandb
|
|||||||
|
|
||||||
To create a sweep over some hyperparameters run:
|
To create a sweep over some hyperparameters run:
|
||||||
```yaml
|
```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
|
# 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
|
python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
# @package _global_
|
# @package _global_
|
||||||
|
|
||||||
# example hyperparameter optimization of some experiment with optuna:
|
# 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:
|
defaults:
|
||||||
# load everything from main config file
|
# load everything from main config file
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ defaults:
|
|||||||
- override /logger: null
|
- override /logger: null
|
||||||
|
|
||||||
# we override default configurations with nulls to prevent them from loading at all
|
# 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
|
# so everything is stored in one place for more readibility
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ defaults:
|
|||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
min_epochs: 1
|
min_epochs: 1
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
_target_: pytorch_lightning.Trainer
|
_target_: pytorch_lightning.Trainer
|
||||||
|
|
||||||
# set -1 to train on all GPUs available, set 0 to train on CPU only
|
# set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||||
gpus: 0
|
gpus: 0
|
||||||
# auto_select_gpus: True
|
# auto_select_gpus: True
|
||||||
|
|
||||||
min_epochs: 3
|
min_epochs: 3
|
||||||
@@ -13,7 +13,7 @@ max_epochs: 3
|
|||||||
# overfit_batches: 10
|
# overfit_batches: 10
|
||||||
|
|
||||||
# overfit on 5% of the training data
|
# overfit on 5% of the training data
|
||||||
# overfit_batches: 0.05
|
# overfit_batches: 0.05
|
||||||
|
|
||||||
# run validation loop every 5 training epochs
|
# run validation loop every 5 training epochs
|
||||||
# check_val_every_n_epoch: 5
|
# check_val_every_n_epoch: 5
|
||||||
@@ -25,7 +25,7 @@ val_check_interval: 0.5
|
|||||||
# val_check_interval: 100
|
# val_check_interval: 100
|
||||||
|
|
||||||
# run for 1 train, 1 val and 1 test batch
|
# run for 1 train, 1 val and 1 test batch
|
||||||
# fast_dev_run: True
|
fast_dev_run: False
|
||||||
|
|
||||||
# use only 20% of the data
|
# use only 20% of the data
|
||||||
limit_train_batches: 0.2
|
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
|
# no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
|
||||||
# accumulate_grad_batches: {5: 3, 10: 20}
|
# 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))
|
# (requires calling trainer.tune(model=model, datamodule=datamodule))
|
||||||
# auto_scale_batch_size:'power'
|
# auto_scale_batch_size:'power'
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ min_epochs: 1
|
|||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
num_sanity_val_steps: 2
|
num_sanity_val_steps: 2
|
||||||
progress_bar_refresh_rate: 20
|
progress_bar_refresh_rate: 10
|
||||||
weights_summary: null
|
weights_summary: null
|
||||||
default_root_dir: "lightning_logs/"
|
default_root_dir: "lightning_logs/"
|
||||||
|
fast_dev_run: False
|
||||||
@@ -22,7 +22,7 @@ def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
|||||||
|
|
||||||
if not logger:
|
if not logger:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
"You're using wandb related callback, "
|
"You are using wandb related callback,"
|
||||||
"but WandbLogger was not found for some reason..."
|
"but WandbLogger was not found for some reason..."
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
+79
-40
@@ -4,6 +4,7 @@ import pytorch_lightning as pl
|
|||||||
# hydra imports
|
# hydra imports
|
||||||
from omegaconf import DictConfig, OmegaConf
|
from omegaconf import DictConfig, OmegaConf
|
||||||
from hydra.utils import get_original_cwd, to_absolute_path
|
from hydra.utils import get_original_cwd, to_absolute_path
|
||||||
|
from hydra.utils import log
|
||||||
|
|
||||||
# logger imports
|
# logger imports
|
||||||
import wandb
|
import wandb
|
||||||
@@ -21,6 +22,44 @@ from rich import print
|
|||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List
|
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 <disable_warnings=True>
|
||||||
|
if config.get("disable_warnings"):
|
||||||
|
log.info(f"Disabling python warnings! <{config.disable_warnings=}>")
|
||||||
|
warnings.filterwarnings("ignore")
|
||||||
|
|
||||||
|
# [OPTIONAL] Disable Lightning logs if <disable_lightning_logs=True>
|
||||||
|
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 <trainer.fast_dev_run=True>
|
||||||
|
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 <print_config=True>
|
||||||
|
if config.get("print_config"):
|
||||||
|
log.info(f"Pretty printing config with Rich! <{config.print_config=}>")
|
||||||
|
print_config(config)
|
||||||
|
|
||||||
|
|
||||||
def print_config(config: DictConfig):
|
def print_config(config: DictConfig):
|
||||||
@@ -34,41 +73,41 @@ def print_config(config: DictConfig):
|
|||||||
# directory = to_absolute_path("configs/config.yaml")
|
# directory = to_absolute_path("configs/config.yaml")
|
||||||
# print(f"Main config path: [link file://{directory}]{directory}")
|
# 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 = OmegaConf.to_yaml(config["trainer"], resolve=True)
|
||||||
trainer_branch = tree.add('Trainer', style=style, guide_style=style)
|
trainer_branch = tree.add("Trainer", style=style, guide_style=style)
|
||||||
trainer_branch.add(Syntax(trainer, 'yaml'))
|
trainer_branch.add(Syntax(trainer, "yaml"))
|
||||||
|
|
||||||
model = OmegaConf.to_yaml(config['model'], resolve=True)
|
model = OmegaConf.to_yaml(config["model"], resolve=True)
|
||||||
model_branch = tree.add('Model', style=style, guide_style=style)
|
model_branch = tree.add("Model", style=style, guide_style=style)
|
||||||
model_branch.add(Syntax(model, 'yaml'))
|
model_branch.add(Syntax(model, "yaml"))
|
||||||
|
|
||||||
datamodule = OmegaConf.to_yaml(config['datamodule'], resolve=True)
|
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=True)
|
||||||
datamodule_branch = tree.add('Datamodule', style=style, guide_style=style)
|
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style)
|
||||||
datamodule_branch.add(Syntax(datamodule, 'yaml'))
|
datamodule_branch.add(Syntax(datamodule, "yaml"))
|
||||||
|
|
||||||
callbacks_branch = tree.add('Callbacks', style=style, guide_style=style)
|
callbacks_branch = tree.add("Callbacks", style=style, guide_style=style)
|
||||||
if 'callbacks' in config:
|
if "callbacks" in config:
|
||||||
for cb_name, cb_conf in config['callbacks'].items():
|
for cb_name, cb_conf in config["callbacks"].items():
|
||||||
cb = callbacks_branch.add(cb_name, style=style, guide_style=style)
|
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:
|
else:
|
||||||
callbacks_branch.add('None')
|
callbacks_branch.add("None")
|
||||||
|
|
||||||
logger_branch = tree.add('Logger', style=style, guide_style=style)
|
logger_branch = tree.add("Logger", style=style, guide_style=style)
|
||||||
if 'logger' in config:
|
if "logger" in config:
|
||||||
for lg_name, lg_conf in config['logger'].items():
|
for lg_name, lg_conf in config["logger"].items():
|
||||||
lg = logger_branch.add(lg_name, style=style, guide_style=style)
|
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:
|
else:
|
||||||
logger_branch.add('None')
|
logger_branch.add("None")
|
||||||
|
|
||||||
seed = config.get('seed', 'None')
|
seed = config.get("seed", "None")
|
||||||
seed_branch = tree.add(f'Seed', style=style, guide_style=style)
|
seed_branch = tree.add(f"Seed", style=style, guide_style=style)
|
||||||
seed_branch.add(str(seed) + '\n')
|
seed_branch.add(str(seed) + "\n")
|
||||||
|
|
||||||
print(tree)
|
print(tree)
|
||||||
|
|
||||||
@@ -95,32 +134,32 @@ def log_hparams_to_all_loggers(
|
|||||||
hparams = {}
|
hparams = {}
|
||||||
|
|
||||||
# save all params of model, datamodule and trainer
|
# save all params of model, datamodule and trainer
|
||||||
hparams.update(config['model'])
|
hparams.update(config["model"])
|
||||||
hparams.update(config['datamodule'])
|
hparams.update(config["datamodule"])
|
||||||
hparams.update(config['trainer'])
|
hparams.update(config["trainer"])
|
||||||
hparams.pop('_target_')
|
hparams.pop("_target_")
|
||||||
|
|
||||||
# save seed
|
# save seed
|
||||||
hparams['seed'] = config.get('seed', 'None')
|
hparams["seed"] = config.get("seed", "None")
|
||||||
|
|
||||||
# save targets
|
# save targets
|
||||||
hparams['_class_model'] = config['model']['_target_']
|
hparams["_class_model"] = config["model"]["_target_"]
|
||||||
hparams['_class_datamodule'] = config['datamodule']['_target_']
|
hparams["_class_datamodule"] = config["datamodule"]["_target_"]
|
||||||
|
|
||||||
# save sizes of each dataset
|
# save sizes of each dataset
|
||||||
if hasattr(datamodule, 'data_train') and datamodule.data_train:
|
if hasattr(datamodule, "data_train") and datamodule.data_train:
|
||||||
hparams['train_size'] = len(datamodule.data_train)
|
hparams["train_size"] = len(datamodule.data_train)
|
||||||
if hasattr(datamodule, 'data_val') and datamodule.data_val:
|
if hasattr(datamodule, "data_val") and datamodule.data_val:
|
||||||
hparams['val_size'] = len(datamodule.data_val)
|
hparams["val_size"] = len(datamodule.data_val)
|
||||||
if hasattr(datamodule, 'data_test') and datamodule.data_test:
|
if hasattr(datamodule, "data_test") and datamodule.data_test:
|
||||||
hparams['test_size'] = len(datamodule.data_test)
|
hparams["test_size"] = len(datamodule.data_test)
|
||||||
|
|
||||||
# save number of model parameters
|
# save number of model parameters
|
||||||
hparams['#params_total'] = sum(p.numel() for p in model.parameters())
|
hparams["#params_total"] = sum(p.numel() for p in model.parameters())
|
||||||
hparams['#params_trainable'] = sum(
|
hparams["#params_trainable"] = sum(
|
||||||
p.numel() for p in model.parameters() if p.requires_grad
|
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
|
p.numel() for p in model.parameters() if not p.requires_grad
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
+29
-46
@@ -15,83 +15,66 @@ echo() {
|
|||||||
export PYTHONWARNINGS="ignore"
|
export PYTHONWARNINGS="ignore"
|
||||||
|
|
||||||
|
|
||||||
# Test fast_dev_run (runs for 1 train, 1 val and 1 test batch)
|
|
||||||
echo "TEST 1"
|
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
|
print_config=false
|
||||||
|
|
||||||
# Overfit to 10 bathes
|
|
||||||
echo "TEST 2"
|
echo "TEST 2"
|
||||||
|
echo "Overfit to 10 bathes"
|
||||||
python train.py +trainer.overfit_batches=10 \
|
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
|
print_config=false
|
||||||
|
|
||||||
# Test 1 epoch on CPU
|
|
||||||
echo "TEST 3"
|
echo "TEST 3"
|
||||||
|
echo "Train 1 epoch on CPU"
|
||||||
python train.py trainer.gpus=0 trainer.max_epochs=1 \
|
python train.py trainer.gpus=0 trainer.max_epochs=1 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
# Test 1 epoch on GPU
|
|
||||||
echo "TEST 4"
|
echo "TEST 4"
|
||||||
python train.py trainer.gpus=1 trainer.max_epochs=1 \
|
echo "Train on 25% of data"
|
||||||
print_config=false
|
|
||||||
|
|
||||||
# Test on 25% of data
|
|
||||||
echo "TEST 5"
|
|
||||||
python train.py trainer.max_epochs=1 \
|
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 \
|
+trainer.limit_train_batches=0.25 +trainer.limit_val_batches=0.25 +trainer.limit_test_batches=0.25 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
# Test on 15 train batches, 10 val batches, 5 test batches
|
echo "TEST 5"
|
||||||
echo "TEST 6"
|
echo "Train on 15 train batches, 10 val batches, 5 test batches"
|
||||||
python train.py trainer.max_epochs=1 \
|
python train.py trainer.max_epochs=1 \
|
||||||
+trainer.limit_train_batches=15 +trainer.limit_val_batches=10 +trainer.limit_test_batches=5 \
|
+trainer.limit_train_batches=15 +trainer.limit_val_batches=10 +trainer.limit_test_batches=5 \
|
||||||
print_config=false
|
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"
|
echo "TEST 7"
|
||||||
python train.py -m '+experiment=glob(*)' trainer.gpus=1 trainer.max_epochs=2 \
|
echo "Run default hydra sweep (executes 4 different combinations with fast_dev_run=True)"
|
||||||
print_config=false
|
|
||||||
|
|
||||||
# Test default hydra sweep over hyperparameters (runs 4 different combinations with fast_dev_run)
|
|
||||||
echo "TEST 8"
|
|
||||||
python train.py -m datamodule.batch_size=32,64 model.lr=0.001,0.003 \
|
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
|
print_config=false
|
||||||
|
|
||||||
# Test multiple workers and cuda pinned memory
|
|
||||||
echo "TEST 9"
|
echo "TEST 9"
|
||||||
python train.py trainer.gpus=1 trainer.max_epochs=2 \
|
echo "Run with gradient accumulation"
|
||||||
datamodule.num_workers=4 datamodule.pin_memory=True \
|
python train.py trainer.max_epochs=1 +trainer.accumulate_grad_batches=10 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
# Test 16 bit precision
|
|
||||||
echo "TEST 10"
|
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
|
print_config=false
|
||||||
|
|
||||||
# Test gradient accumulation
|
|
||||||
echo "TEST 11"
|
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
|
print_config=false
|
||||||
|
|
||||||
# Test running validation loop twice per epoch
|
|
||||||
echo "TEST 12"
|
echo "TEST 12"
|
||||||
python train.py trainer.gpus=1 trainer.max_epochs=2 val_check_interval=0.5 \
|
echo "Run with TensorBoardLogger (2 epochs)"
|
||||||
print_config=false
|
python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \
|
||||||
|
|
||||||
# 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' \
|
|
||||||
print_config=false
|
print_config=false
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
# To execute:
|
# To execute:
|
||||||
# bash tests/sweep_tests.sh
|
# bash tests/sweep_tests.sh
|
||||||
|
|
||||||
|
# Method for printing test name
|
||||||
echo() {
|
echo() {
|
||||||
termwidth="$(tput cols)"
|
termwidth="$(tput cols)"
|
||||||
padding="$(printf '%0.1s' ={1..500})"
|
padding="$(printf '%0.1s' ={1..500})"
|
||||||
@@ -13,18 +14,19 @@ echo() {
|
|||||||
# Make python hide warnings
|
# Make python hide warnings
|
||||||
export PYTHONWARNINGS="ignore"
|
export PYTHONWARNINGS="ignore"
|
||||||
|
|
||||||
# Test default hydra sweep with wandb logging
|
|
||||||
echo "TEST 1"
|
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 \
|
python train.py -m datamodule.batch_size=64,128 model.lr=0.001,0.003 \
|
||||||
+experiment=exp_example_simple \
|
+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 \
|
datamodule.num_workers=12 datamodule.pin_memory=True \
|
||||||
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"
|
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"
|
||||||
|
|
||||||
# Test optuna sweep with wandb logging
|
|
||||||
echo "TEST 2"
|
echo "TEST 2"
|
||||||
|
echo "Optuna sweep with wandb logging"
|
||||||
python train.py -m --config-name config_optuna.yaml \
|
python train.py -m --config-name config_optuna.yaml \
|
||||||
+experiment=exp_example_simple \
|
+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 \
|
datamodule.num_workers=12 datamodule.pin_memory=True \
|
||||||
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="Optuna_MNIST_SimpleDenseNet"
|
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="Optuna_MNIST_SimpleDenseNet"
|
||||||
@@ -5,6 +5,7 @@ from pytorch_lightning import seed_everything
|
|||||||
|
|
||||||
# hydra imports
|
# hydra imports
|
||||||
from omegaconf import DictConfig
|
from omegaconf import DictConfig
|
||||||
|
from hydra.utils import log
|
||||||
import hydra
|
import hydra
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
@@ -18,50 +19,49 @@ from src.utils import template_utils as utils
|
|||||||
|
|
||||||
def train(config: DictConfig):
|
def train(config: DictConfig):
|
||||||
|
|
||||||
# Disable python warnings
|
# A couple of optional utilities:
|
||||||
if config['disable_warnings']:
|
# - disabling warnings,
|
||||||
warnings.filterwarnings('ignore')
|
# - printing config with Rich,
|
||||||
|
# - forcing debug friendly configuration
|
||||||
# Disable PyTorch Lightning logs
|
# You can safely get rid of this line if you don't want those
|
||||||
if config['disable_lightning_logs']:
|
utils.extras(config)
|
||||||
logging.getLogger('lightning').setLevel(logging.ERROR)
|
|
||||||
|
|
||||||
# Pretty print config using Rich library
|
|
||||||
if config['print_config']:
|
|
||||||
utils.print_config(config)
|
|
||||||
|
|
||||||
# Set seed for random number generators in pytorch, numpy and python.random
|
# Set seed for random number generators in pytorch, numpy and python.random
|
||||||
if 'seed' in config:
|
if "seed" in config:
|
||||||
seed_everything(config['seed'])
|
seed_everything(config.seed)
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init Lightning model ⚡
|
||||||
model: LightningModule = hydra.utils.instantiate(config['model'])
|
log.info(f"Instantiating model <{config.model._target_}>")
|
||||||
|
model: LightningModule = hydra.utils.instantiate(config.model)
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init Lightning datamodule ⚡
|
||||||
datamodule: LightningDataModule = hydra.utils.instantiate(config['datamodule'])
|
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||||
datamodule.prepare_data()
|
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
|
||||||
datamodule.setup()
|
|
||||||
|
|
||||||
# Init PyTorch Lightning callbacks
|
# Init Lightning callbacks
|
||||||
callbacks: List[Callback] = []
|
callbacks: List[Callback] = []
|
||||||
if 'callbacks' in config:
|
if "callbacks" in config:
|
||||||
for _, cb_conf in config['callbacks'].items():
|
for _, cb_conf in config["callbacks"].items():
|
||||||
if '_target_' in cb_conf:
|
if "_target_" in cb_conf:
|
||||||
|
log.info(f"Instantiating callback <{cb_conf._target_}>")
|
||||||
callbacks.append(hydra.utils.instantiate(cb_conf))
|
callbacks.append(hydra.utils.instantiate(cb_conf))
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers
|
# Init Lightning loggers
|
||||||
logger: List[LightningLoggerBase] = []
|
logger: List[LightningLoggerBase] = []
|
||||||
if 'logger' in config:
|
if "logger" in config:
|
||||||
for _, lg_conf in config['logger'].items():
|
for _, lg_conf in config["logger"].items():
|
||||||
if '_target_' in lg_conf:
|
if "_target_" in lg_conf:
|
||||||
|
log.info(f"Instantiating logger <{lg_conf._target_}>")
|
||||||
logger.append(hydra.utils.instantiate(lg_conf))
|
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(
|
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
|
# Send some parameters from config to all lightning loggers
|
||||||
|
log.info(f"Logging hyperparameters!")
|
||||||
utils.log_hparams_to_all_loggers(
|
utils.log_hparams_to_all_loggers(
|
||||||
config=config,
|
config=config,
|
||||||
model=model,
|
model=model,
|
||||||
@@ -72,12 +72,16 @@ def train(config: DictConfig):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Train the model ⚡
|
# Train the model ⚡
|
||||||
|
log.info(f"Starting training!")
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
# Evaluate model on test set after training
|
# 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
|
# Make sure everything closed properly
|
||||||
|
log.info(f"Finalizing!")
|
||||||
utils.finish(
|
utils.finish(
|
||||||
config=config,
|
config=config,
|
||||||
model=model,
|
model=model,
|
||||||
@@ -87,16 +91,18 @@ def train(config: DictConfig):
|
|||||||
logger=logger,
|
logger=logger,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Return metric score for optuna optimization
|
# Return metric score for Optuna optimization
|
||||||
optimized_metric = config.get('optimized_metric', None)
|
optimized_metric = config.get("optimized_metric")
|
||||||
if 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):
|
def main(config: DictConfig):
|
||||||
return train(config)
|
return train(config)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in new issue
Block a user