* update readme

* make Rich printing more general
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-03-12 18:40:24 +01:00
1 parent 3586f355b9
commit 5f1c85e9bf
8 files changed
+179 -184

No files matched your search

+64 -56
View File
@@ -47,17 +47,17 @@ This template tries to be as general as possible - you can easily delete any unw
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended. > Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
Why you should use it: it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most, if not the most convenient all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility. **Why you should use it:** it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most, if not the most convenient all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility.
Why you shouldn't use it: Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. **Why you shouldn't use it:** Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task.
### Why PyTorch Lightning? ### Why PyTorch Lightning?
PyTorch Lightning is a lightweight PyTorch wrapper for high-performance AI research. [PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research.
Makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU. It makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.
### Why Hydra? ### Why Hydra?
Hydra is an open-source Python framework that simplifies the development of research and other complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line. It provides convenient ways to manage experiments and advanced features like overriding any config parameter from command line or sweeping over hyperparameters. [Hydra](https://github.com/facebookresearch/hydra) is an open-source Python framework that simplifies the development of research and other complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line. It allows you to conveniently manage experiments and provides many useful plugins, like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) for hyperparameter search, or [Ray Launcher](https://hydra.cc/docs/next/plugins/ray_launcher) for running jobs on a cluster.
<br> <br>
<br> <br>
<br> <br>
@@ -72,8 +72,8 @@ Hydra is an open-source Python framework that simplifies the development of rese
- Experiment Tracking: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking)) - Experiment Tracking: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))
- Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))
- Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) - Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper)
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
- Best Practices: a couple of recommended tools, practices and standards (see [#Best Practices](#best-practices)) - Best Practices: a couple of recommended tools, practices and standards (see [#Best Practices](#best-practices))
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
<br> <br>
@@ -150,7 +150,7 @@ When running `python train.py` you should see something like this:
</div> </div>
### Your Superpowers ### Your Superpowers
*(click to expand)* ##### (click to expand)
<details> <details>
<summary>Override any config parameter from command line</summary> <summary>Override any config parameter from command line</summary>
@@ -158,6 +158,11 @@ When running `python train.py` you should see something like this:
> *Hydra allows you to overwrite any parameter defined in your config, without writing any code!* > *Hydra allows you to overwrite any parameter defined in your config, without writing any code!*
```yaml ```yaml
python train.py trainer.max_epochs=20 optimizer.lr=1e-4 python train.py trainer.max_epochs=20 optimizer.lr=1e-4
```
> *You can also add new parameters with `+` sign.*
```yaml
python train.py +trainer.new_param="uwu"
``` ```
</details> </details>
@@ -175,13 +180,13 @@ python train.py trainer.gpus=0
python train.py trainer.gpus=1 python train.py trainer.gpus=1
# train on TPU # train on TPU
python train.py trainer.tpu_cores=8 python train.py +trainer.tpu_cores=8
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes) # train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python train.py trainer.gpus=4 trainer.num_nodes=2 trainer.accelerator='ddp' python train.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
# train with mixed precision # train with mixed precision
python train.py trainer.amp_backend="apex" trainer.amp_level="O1" trainer.precision=16 python train.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16
``` ```
</details> </details>
@@ -211,8 +216,8 @@ python train.py logger=wandb
<details> <details>
<summary>Train model with chosen experiment config</summary> <summary>Train model with chosen experiment config</summary>
> Experiment configurations are placed in folder `configs/experiment/`.
```yaml ```yaml
# experiment configurations are placed in folder `configs/experiment/`
python train.py +experiment=exp_example_simple python train.py +experiment=exp_example_simple
``` ```
@@ -222,9 +227,9 @@ python train.py +experiment=exp_example_simple
<details> <details>
<summary>Attach some callbacks to run</summary> <summary>Attach some callbacks to run</summary>
> *Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).* > *Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br>
Callbacks configurations are placed in `configs/callbacks/`.*
```yaml ```yaml
# callback set configurations are placed in `configs/callbacks/`
python train.py callbacks=default_callbacks python train.py callbacks=default_callbacks
``` ```
@@ -237,16 +242,16 @@ python train.py callbacks=default_callbacks
> *PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).* > *PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).*
```yaml ```yaml
# gradient clipping may be enabled to avoid exploding gradients # gradient clipping may be enabled to avoid exploding gradients
python train.py trainer.gradient_clip_val=0.5 python train.py +trainer.gradient_clip_val=0.5
# stochastic weight averaging can make your models generalize better # stochastic weight averaging can make your models generalize better
python train.py trainer.stochastic_weight_avg=True python train.py +trainer.stochastic_weight_avg=True
# run validation loop 4 times during a training epoch # run validation loop 4 times during a training epoch
python train.py trainer.val_check_interval=0.25 python train.py +trainer.val_check_interval=0.25
# accumulate gradients # accumulate gradients
python train.py trainer.accumulate_grad_batches=10 python train.py +trainer.accumulate_grad_batches=10
``` ```
@@ -264,14 +269,14 @@ python train.py debug=true
python train.py trainer.weights_summary="full" python train.py trainer.weights_summary="full"
# print execution time profiling after training ends # print execution time profiling after training ends
python train.py trainer.profiler="simple" python train.py +trainer.profiler="simple"
# try overfitting to 1 batch # try overfitting to 1 batch
python train.py trainer.overfit_batches=1 trainer.max_epochs=20 python train.py +trainer.overfit_batches=1 trainer.max_epochs=20
# use only 20% of the data # use only 20% of the data
python train.py trainer.limit_train_batches=0.2 \ python train.py +trainer.limit_train_batches=0.2 \
trainer.limit_val_batches=0.2 trainer.limit_test_batches=0.2 +trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
``` ```
</details> </details>
@@ -283,7 +288,7 @@ trainer.limit_val_batches=0.2 trainer.limit_test_batches=0.2
```yaml ```yaml
# checkpoint can be either path or URL # checkpoint can be either path or URL
# path should be absolute! # path should be absolute!
python train.py trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt" python train.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
``` ```
> *Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.* > *Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.*
@@ -311,7 +316,7 @@ python train.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
# over chosen experiment config # over chosen experiment config
python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
``` ```
> *Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file.* > *Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file!*
</details> </details>
@@ -509,7 +514,7 @@ logger:
2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example) 2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
3. Write your experiment config, containing paths to your model and datamodule (see [configs/experiment](configs/experiment) for examples) 3. Write your experiment config, containing paths to your model and datamodule (see [configs/experiment](configs/experiment) for examples)
4. Run training with chosen experiment config:<br> 4. Run training with chosen experiment config:<br>
```bash ```yaml
python train.py +experiment=experiment_name python train.py +experiment=experiment_name
``` ```
<br> <br>
@@ -588,10 +593,9 @@ To provide examples of logging custom visualisations with callbacks only:
## Best Practices ## Best Practices
### Miniconda ### Miniconda
Use miniconda for your python environments. Makes it easier to install cudatoolkit for GPU and PyTorch.<br> Use miniconda for your python environments. Makes it easier to install some dependencies, like GPU support for PyTorch (it's usually unnecessary to install full Anaconda environment, miniconda should be enough).<br>
(I find it unnecessary to install full Anaconda environment, miniconda should be enough)<br>
Example installation: Example installation:
``` ```yaml
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh
``` ```
@@ -603,17 +607,17 @@ Simply install pre-commit package with:
```yaml ```yaml
pip install pre-commit pip install pre-commit
``` ```
Next, install hooks from `.pre-commit-config.yaml`: Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
``` ```yaml
pre-commit install pre-commit install
``` ```
After that your code will be automatically reformatted on every new commit.<br> After that your code will be automatically reformatted on every new commit.<br>
Currently `.pre-commit-config.yaml` contains configurations of **Black** (python code formatting) and **Isort** (python import sorting). Currently [.pre-commit-config.yaml](.pre-commit-config.yaml) contains configurations of **Black** (python code formatting) and **Isort** (python import sorting).
To format all files in the project use command: To format all files in the project use command:
```yaml ```yaml
pre-commit run --all-files pre-commit run --all-filess
``` ```
You can exclude chosen files from automatic formatting, by modifying config (see [.pre-commit-config.yaml](.pre-commit-config.yaml)) You can exclude chosen files from automatic formatting, by modifying [.pre-commit-config.yaml](.pre-commit-config.yaml).
### Tests ### Tests
@@ -630,10 +634,30 @@ bash tests/smoke_tests.sh
<br><br> <br><br>
### Support Installing Project As a Package
It allows other people to easily use your modules in their own projects.
Change name of the `src` folder to your project name and modify configuration in `setup.py`.
Now your project can be installed from local files:
```yaml
pip install -e .
```
Or directly from git repository:
```yaml
pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade
```
So any file can be easily imported into any other file like so:
```python
from project_name.models.mnist_model import LitModelMNIST
from project_name.datamodules.mnist_datamodule import MNISTDataModule
```
<br><br>
## Tricks ## Tricks
(TODO) (TODO)
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup, <!-- PrettyErrors and Rich exception handling,
k-fold cross validation, linter, faster tab completion import trick, k-fold cross validation, faster tab completion import trick,
choosing metric names with '/' for wandb --> choosing metric names with '/' for wandb -->
<br> <br>
@@ -687,13 +711,13 @@ This template was inspired by:
What it does What it does
## How to run ## How to run
Install dependencies: Install dependencies
```yaml ```yaml
# clone project # clone project
git clone https://github.com/YourGithubName/your-repo-name git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name cd your-repo-name
# optionally create conda environment # [OPTIONAL] create conda environment
conda env create -f conda_env_gpu.yaml -n your_env_name conda env create -f conda_env_gpu.yaml -n your_env_name
conda activate your_env_name conda activate your_env_name
@@ -701,40 +725,24 @@ conda activate your_env_name
pip install -r requirements.txt pip install -r requirements.txt
``` ```
Train model with default configuration: Train model with default configuration
```yaml ```yaml
python train.py python train.py
``` ```
Train model with chosen experiment configuration: Train model with chosen experiment configuration
```yaml ```yaml
# experiment configurations are placed in folder `configs/experiment/` # experiment configurations are placed in folder `configs/experiment/`
python train.py +experiment=exp_example_simple python train.py +experiment=exp_example_simple
``` ```
You can override any parameter from command line like this: You can override any parameter from command line like this
```yaml ```yaml
python train.py trainer.max_epochs=20 optimizer.lr=0.0005 python train.py trainer.max_epochs=20 optimizer.lr=0.0005
``` ```
To train on GPU: Train on GPU
```yaml ```yaml
python train.py trainer.gpus=1 python train.py trainer.gpus=1
``` ```
<br> <br>
## Installing project as a package
Optionally you can install project as a package with [setup.py](setup.py):
```yaml
# install from local files
pip install -e .
# or install from git repo
pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade
```
So you can easily import any file into any other file like so:
```python
from src.models.mnist_model import LitModelMNIST
from src.datamodules.mnist_datamodule import MNISTDataModule
```
+1 -1
View File
@@ -2,7 +2,7 @@
wandb: wandb:
_target_: pytorch_lightning.loggers.wandb.WandbLogger _target_: pytorch_lightning.loggers.wandb.WandbLogger
project: "env_tests" project: "template-tests"
# entity: "" # set to name of your wandb team or just remove it # entity: "" # set to name of your wandb team or just remove it
# offline: False # set True to store all logs only locally # offline: False # set True to store all logs only locally
job_type: "train" job_type: "train"
+30 -42
View File
@@ -2,51 +2,45 @@
_target_: pytorch_lightning.Trainer _target_: pytorch_lightning.Trainer
# set -1 to train on all GPUs available, set 0 to train on CPU only
gpus: 0
# auto_select_gpus: True
min_epochs: 3 gpus: 0
min_epochs: 1
max_epochs: 3 max_epochs: 3
# overfit on 10 of the same training set batches # prints
# overfit_batches: 10 progress_bar_refresh_rate: null
weights_summary: null
profiler: null
# overfit on 5% of the training data # all of the parameters below are set to Lightning defaults
# overfit_batches: 0.05
# run validation loop every 5 training epochs # tricks
# check_val_every_n_epoch: 5 gradient_clip_val: 0
accumulate_grad_batches: 1
val_check_interval: 1.0
check_val_every_n_epoch: 1
stochastic_weight_avg: False
# run validation loop 2 times during a training epoch # debug
val_check_interval: 0.5 num_sanity_val_steps: 2
# run validation loop every 100 training batches
# val_check_interval: 100
# run for 1 train, 1 val and 1 test batch
fast_dev_run: False fast_dev_run: False
overfit_batches: 0
limit_train_batches: 1.0
limit_val_batches: 1.0
limit_test_batches: 1.0
track_grad_norm: -1
# use only 20% of the data # others
limit_train_batches: 0.2 amp_backend: "native"
limit_val_batches: 0.2 amp_level: "02"
limit_test_batches: 0.2 precision: 32
accelerator: null
num_nodes: 1
tpu_cores: null
deterministic: False
# number of sanity validation steps resume_from_checkpoint: null
num_sanity_val_steps: 3
# print execution time profiling after training end
# profiler: "simple"
# print full weight summary of all modules and submodules
# weights_summary: "full"
# weights_summary: "top"
# use gradient clipping because why not
gradient_clip_val: 0.5
# perform optimisation after accumulating gradient from 5 batches
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}
@@ -54,9 +48,3 @@ accumulate_grad_batches: 5
# 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'
# set tensor precision to 16 (default is 32 bits)
# precision: 16
# apex backend for mixed precision training https://github.com/NVIDIA/apex
# amp_backend: 'apex'
+22 -23
View File
@@ -8,36 +8,35 @@ min_epochs: 1
max_epochs: 10 max_epochs: 10
# prints # prints
progress_bar_refresh_rate: null # progress_bar_refresh_rate: null
weights_summary: null weights_summary: null
profiler: null # profiler: null
# all of the parameters below are set to Lightning defaults # all of the parameters below are set to Lightning defaults
# tricks # tricks
gradient_clip_val: 0 # gradient_clip_val: 0
accumulate_grad_batches: 1 # accumulate_grad_batches: 1
val_check_interval: 1.0 # val_check_interval: 1.0
check_val_every_n_epoch: 1 # check_val_every_n_epoch: 1
stochastic_weight_avg: False # stochastic_weight_avg: False
# debug # debug
num_sanity_val_steps: 2 # num_sanity_val_steps: 2
fast_dev_run: False # fast_dev_run: False
overfit_batches: 0 # overfit_batches: 0
limit_train_batches: 1.0 # limit_train_batches: 1.0
limit_val_batches: 1.0 # limit_val_batches: 1.0
limit_test_batches: 1.0 # limit_test_batches: 1.0
track_grad_norm: -1 # track_grad_norm: -1
# others # others
amp_backend: "native" # amp_backend: "native"
amp_level: "02" # amp_level: "02"
precision: 32 # precision: 32
accelerator: null # accelerator: null
num_nodes: 1 # num_nodes: 1
tpu_cores: null # tpu_cores: null
deterministic: False # deterministic: False
# resume # resume_from_checkpoint: null
resume_from_checkpoint: null
+1 -1
View File
@@ -2,7 +2,7 @@
from setuptools import find_packages, setup from setuptools import find_packages, setup
setup( setup(
name="src", name="src", # you should probably change "src" to your project name
version="0.0.0", version="0.0.0",
description="Describe Your Cool Project", description="Describe Your Cool Project",
author="", author="",
+3 -2
View File
@@ -1,8 +1,9 @@
from typing import Optional, Sequence
from pytorch_lightning import LightningDataModule from pytorch_lightning import LightningDataModule
from torch.utils.data import ConcatDataset, DataLoader, random_split, Dataset from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
from torchvision.datasets import MNIST from torchvision.datasets import MNIST
from torchvision.transforms import transforms from torchvision.transforms import transforms
from typing import Optional, Sequence
class MNISTDataModule(LightningDataModule): class MNISTDataModule(LightningDataModule):
+47 -48
View File
@@ -1,10 +1,10 @@
import logging import logging
import warnings import warnings
from typing import List from typing import List, Sequence
import pytorch_lightning as pl import pytorch_lightning as pl
import wandb import wandb
from hydra.utils import get_original_cwd, log, to_absolute_path from hydra.utils import log
from omegaconf import DictConfig, OmegaConf from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.loggers.wandb import WandbLogger from pytorch_lightning.loggers.wandb import WandbLogger
from rich import print from rich import print
@@ -12,7 +12,7 @@ from rich.syntax import Syntax
from rich.tree import Tree from rich.tree import Tree
def extras(config: DictConfig): def extras(config: DictConfig) -> None:
"""A couple of optional utilities, controlled by main config file. """A couple of optional utilities, controlled by main config file.
- disabling warnings - disabling warnings
- disabling lightning logs - disabling lightning logs
@@ -26,7 +26,7 @@ def extras(config: DictConfig):
OmegaConf.set_struct(config, False) OmegaConf.set_struct(config, False)
# fix double logging bug (this will be removed when lightning releases patch) # fix double logging bug (this will be removed when lightning releases patch)
pl_logger = logging.getLogger('lightning') pl_logger = logging.getLogger("lightning")
pl_logger.propagate = False pl_logger.propagate = False
# [OPTIONAL] Disable python warnings if <config.disable_warnings=True> # [OPTIONAL] Disable python warnings if <config.disable_warnings=True>
@@ -60,59 +60,59 @@ def extras(config: DictConfig):
OmegaConf.set_struct(config, True) OmegaConf.set_struct(config, True)
def print_config(config: DictConfig, resolve: bool = True): def print_config(
"""Prints content of Hydra config using Rich library. config: DictConfig,
fields: Sequence[str] = (
"trainer",
"model",
"optimizer",
"datamodule",
"callbacks",
"logger",
"seed",
),
extra_depth_fields: Sequence[str] = (
"callbacks",
"logger",
),
resolve: bool = True,
) -> None:
"""Prints content of DictConfig using Rich library and its tree structure.
Args: Args:
config (DictConfig): [description] config (DictConfig): Config.
resolve (bool, optional): Whether to resolve reference fields in Hydra config. fields (Sequence[str], optional): Determines which main fields from config will be printed
and in what order.
extra_depth_fields (Sequence[str], optional): Fields which should be printed with extra tree depth.
resolve (bool, optional): Whether to resolve reference fields of DictConfig.
""" """
# TODO print main config path and experiment config path # TODO print main config path and experiment config path
# 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}")
#TODO make this method more general
style = "dim" style = "dim"
tree = Tree(f":gear: TRAINING CONFIG", style=style, guide_style=style) tree = Tree(f":gear: CONFIG", style=style, guide_style=style)
trainer = OmegaConf.to_yaml(config["trainer"], resolve=resolve) for field in fields:
trainer_branch = tree.add("Trainer", style=style, guide_style=style) branch = tree.add(field, style=style, guide_style=style)
trainer_branch.add(Syntax(trainer, "yaml"))
model = OmegaConf.to_yaml(config["model"], resolve=resolve) config_section = config.get(field)
model_branch = tree.add("Model", style=style, guide_style=style)
model_branch.add(Syntax(model, "yaml"))
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=resolve) if not config_section:
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style) # raise Exception(f"Field {field} not found in config!")
datamodule_branch.add(Syntax(datamodule, "yaml")) branch.add("None")
continue
optimizer = OmegaConf.to_yaml(config["optimizer"], resolve=resolve) if field in extra_depth_fields:
optimizer_branch = tree.add("Optimizer", style=style, guide_style=style) for nested_field in config_section:
optimizer_branch.add(Syntax(optimizer, "yaml")) nested_config_section = config_section[nested_field]
nested_branch = branch.add(nested_field, style=style, guide_style=style)
callbacks_branch = tree.add("Callbacks", style=style, guide_style=style) cfg_str = OmegaConf.to_yaml(nested_config_section, resolve=resolve)
if "callbacks" in config: nested_branch.add(Syntax(cfg_str, "yaml"))
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=resolve), "yaml"))
else: else:
callbacks_branch.add("None") cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
branch.add(Syntax(cfg_str, "yaml"))
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=resolve), "yaml"))
else:
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")
print(tree) print(tree)
@@ -124,7 +124,7 @@ def log_hyperparameters(
trainer: pl.Trainer, trainer: pl.Trainer,
callbacks: List[pl.Callback], callbacks: List[pl.Callback],
logger: List[pl.loggers.LightningLoggerBase], logger: List[pl.loggers.LightningLoggerBase],
): ) -> None:
"""This method controls which parameters from Hydra config are saved by Lightning loggers. """This method controls which parameters from Hydra config are saved by Lightning loggers.
Additionaly saves: Additionaly saves:
@@ -173,9 +173,8 @@ def log_hyperparameters(
trainer.logger.log_hyperparams(hparams) trainer.logger.log_hyperparams(hparams)
# disable logging any more hyperparameters for all loggers # disable logging any more hyperparameters for all loggers
# (this is just to prevent trainer logging hparams of model as we manage it ourselves) # (this is just a trick to prevent trainer from logging hparams of model, since we already did that above)
for lg in logger: trainer.logger.log_hyperparams = lambda params: None
lg.log_hyperparams = lambda x: None
def finish( def finish(
@@ -185,7 +184,7 @@ def finish(
trainer: pl.Trainer, trainer: pl.Trainer,
callbacks: List[pl.Callback], callbacks: List[pl.Callback],
logger: List[pl.loggers.LightningLoggerBase], logger: List[pl.loggers.LightningLoggerBase],
): ) -> None:
"""Makes sure everything closed properly. """Makes sure everything closed properly.
Args: Args:
+11 -11
View File
@@ -17,59 +17,59 @@ export PYTHONWARNINGS="ignore"
echo "TEST 1" echo "TEST 1"
echo "Debug mode (run 1 train, val and test loop using 1 batch)" echo "Debug mode (run 1 train, val and test loop using 1 batch)"
python train.py debug=True \ python train.py trainer=debug_trainer debug=True \
print_config=false print_config=false
echo "TEST 2" echo "TEST 2"
echo "Overfit to 10 batches (10 epochs)" echo "Overfit to 10 batches (10 epochs)"
python train.py trainer.overfit_batches=10 \ python train.py trainer=debug_trainer trainer.overfit_batches=10 \
trainer.min_epochs=10 trainer.max_epochs=10 \ trainer.min_epochs=10 trainer.max_epochs=10 \
print_config=false print_config=false
echo "TEST 3" echo "TEST 3"
echo "Train on CPU (1 epoch)" echo "Train on CPU (1 epoch)"
python train.py trainer.gpus=0 trainer.max_epochs=1 \ python train.py trainer=debug_trainer trainer.gpus=0 trainer.max_epochs=1 \
print_config=false print_config=false
echo "TEST 4" echo "TEST 4"
echo "Train on 25% of data (1 epoch)" echo "Train on 25% of data (1 epoch)"
python train.py trainer.max_epochs=1 \ python train.py trainer=debug_trainer 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
echo "TEST 5" echo "TEST 5"
echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)" echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)"
python train.py trainer.max_epochs=1 \ python train.py trainer=debug_trainer 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
echo "TEST 6" echo "TEST 6"
echo "Run all experiment configs (2 epochs)" echo "Run all experiment configs (2 epochs)"
python train.py -m '+experiment=glob(*)' trainer.max_epochs=2 \ python train.py -m trainer=debug_trainer '+experiment=glob(*)' trainer.max_epochs=2 \
print_config=false print_config=false
echo "TEST 7" echo "TEST 7"
echo "Run default hydra sweep (executes 4 different combinations in debug mode)" echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
python train.py -m datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \ python train.py -m trainer=debug_trainer datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \
debug=True \ debug=True \
print_config=false print_config=false
echo "TEST 8" echo "TEST 8"
echo "Run with gradient accumulation (1 epoch)" echo "Run with gradient accumulation (1 epoch)"
python train.py trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \ python train.py trainer=debug_trainer trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \
print_config=false print_config=false
echo "TEST 9" echo "TEST 9"
echo "Run validation loop twice per epoch (2 epochs)" echo "Run validation loop twice per epoch (2 epochs)"
python train.py trainer.max_epochs=2 trainer.val_check_interval=0.5 \ python train.py trainer=debug_trainer trainer.max_epochs=2 trainer.val_check_interval=0.5 \
print_config=false print_config=false
echo "TEST 10" echo "TEST 10"
echo "Run with CSVLogger (2 epochs)" echo "Run with CSVLogger (2 epochs)"
python train.py logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \ python train.py trainer=debug_trainer logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false print_config=false
echo "TEST 11" echo "TEST 11"
echo "Run with TensorBoardLogger (2 epochs)" echo "Run with TensorBoardLogger (2 epochs)"
python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \ python train.py trainer=debug_trainer logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false print_config=false