1 parent
3586f355b9
commit
5f1c85e9bf
8 files changed
+179
-184
No files matched your search
@@ -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.
|
||||
|
||||
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?
|
||||
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.
|
||||
[PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research.
|
||||
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?
|
||||
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>
|
||||
@@ -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))
|
||||
- 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)
|
||||
- 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))
|
||||
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
|
||||
<br>
|
||||
|
||||
|
||||
@@ -150,7 +150,7 @@ When running `python train.py` you should see something like this:
|
||||
</div>
|
||||
|
||||
### Your Superpowers
|
||||
*(click to expand)*
|
||||
##### (click to expand)
|
||||
|
||||
<details>
|
||||
<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!*
|
||||
```yaml
|
||||
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>
|
||||
@@ -175,13 +180,13 @@ python train.py trainer.gpus=0
|
||||
python train.py trainer.gpus=1
|
||||
|
||||
# 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)
|
||||
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
|
||||
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>
|
||||
@@ -211,8 +216,8 @@ python train.py logger=wandb
|
||||
<details>
|
||||
<summary>Train model with chosen experiment config</summary>
|
||||
|
||||
> Experiment configurations are placed in folder `configs/experiment/`.
|
||||
```yaml
|
||||
# experiment configurations are placed in folder `configs/experiment/`
|
||||
python train.py +experiment=exp_example_simple
|
||||
```
|
||||
|
||||
@@ -222,9 +227,9 @@ python train.py +experiment=exp_example_simple
|
||||
<details>
|
||||
<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
|
||||
# callback set configurations are placed in `configs/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).*
|
||||
```yaml
|
||||
# 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
|
||||
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
|
||||
python train.py trainer.val_check_interval=0.25
|
||||
python train.py +trainer.val_check_interval=0.25
|
||||
|
||||
# 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"
|
||||
|
||||
# print execution time profiling after training ends
|
||||
python train.py trainer.profiler="simple"
|
||||
python train.py +trainer.profiler="simple"
|
||||
|
||||
# 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
|
||||
python train.py trainer.limit_train_batches=0.2 \
|
||||
trainer.limit_val_batches=0.2 trainer.limit_test_batches=0.2
|
||||
python train.py +trainer.limit_train_batches=0.2 \
|
||||
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -283,7 +288,7 @@ trainer.limit_val_batches=0.2 trainer.limit_test_batches=0.2
|
||||
```yaml
|
||||
# checkpoint can be either path or URL
|
||||
# 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.*
|
||||
|
||||
@@ -311,7 +316,7 @@ python train.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
|
||||
# over chosen experiment config
|
||||
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>
|
||||
|
||||
@@ -509,7 +514,7 @@ logger:
|
||||
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)
|
||||
4. Run training with chosen experiment config:<br>
|
||||
```bash
|
||||
```yaml
|
||||
python train.py +experiment=experiment_name
|
||||
```
|
||||
<br>
|
||||
@@ -588,10 +593,9 @@ To provide examples of logging custom visualisations with callbacks only:
|
||||
## Best Practices
|
||||
|
||||
### Miniconda
|
||||
Use miniconda for your python environments. Makes it easier to install cudatoolkit for GPU and PyTorch.<br>
|
||||
(I find it unnecessary to install full Anaconda environment, miniconda should be enough)<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>
|
||||
Example installation:
|
||||
```
|
||||
```yaml
|
||||
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
||||
bash Miniconda3-latest-Linux-x86_64.sh
|
||||
```
|
||||
@@ -603,17 +607,17 @@ Simply install pre-commit package with:
|
||||
```yaml
|
||||
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
|
||||
```
|
||||
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:
|
||||
```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
|
||||
@@ -630,10 +634,30 @@ bash tests/smoke_tests.sh
|
||||
<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
|
||||
(TODO)
|
||||
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup,
|
||||
k-fold cross validation, linter, faster tab completion import trick,
|
||||
<!-- PrettyErrors and Rich exception handling,
|
||||
k-fold cross validation, faster tab completion import trick,
|
||||
choosing metric names with '/' for wandb -->
|
||||
<br>
|
||||
|
||||
@@ -687,13 +711,13 @@ This template was inspired by:
|
||||
What it does
|
||||
|
||||
## How to run
|
||||
Install dependencies:
|
||||
Install dependencies
|
||||
```yaml
|
||||
# clone project
|
||||
git clone https://github.com/YourGithubName/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 activate your_env_name
|
||||
|
||||
@@ -701,40 +725,24 @@ conda activate your_env_name
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
Train model with default configuration:
|
||||
Train model with default configuration
|
||||
```yaml
|
||||
python train.py
|
||||
```
|
||||
|
||||
Train model with chosen experiment configuration:
|
||||
Train model with chosen experiment configuration
|
||||
```yaml
|
||||
# experiment configurations are placed in folder `configs/experiment/`
|
||||
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
|
||||
python train.py trainer.max_epochs=20 optimizer.lr=0.0005
|
||||
```
|
||||
|
||||
To train on GPU:
|
||||
Train on GPU
|
||||
```yaml
|
||||
python train.py trainer.gpus=1
|
||||
```
|
||||
<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
|
||||
```
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
wandb:
|
||||
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||
project: "env_tests"
|
||||
project: "template-tests"
|
||||
# entity: "" # set to name of your wandb team or just remove it
|
||||
# offline: False # set True to store all logs only locally
|
||||
job_type: "train"
|
||||
|
||||
@@ -2,51 +2,45 @@
|
||||
|
||||
_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
|
||||
|
||||
# overfit on 10 of the same training set batches
|
||||
# overfit_batches: 10
|
||||
# prints
|
||||
progress_bar_refresh_rate: null
|
||||
weights_summary: null
|
||||
profiler: null
|
||||
|
||||
# overfit on 5% of the training data
|
||||
# overfit_batches: 0.05
|
||||
# all of the parameters below are set to Lightning defaults
|
||||
|
||||
# run validation loop every 5 training epochs
|
||||
# check_val_every_n_epoch: 5
|
||||
# tricks
|
||||
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
|
||||
val_check_interval: 0.5
|
||||
|
||||
# run validation loop every 100 training batches
|
||||
# val_check_interval: 100
|
||||
|
||||
# run for 1 train, 1 val and 1 test batch
|
||||
# debug
|
||||
num_sanity_val_steps: 2
|
||||
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
|
||||
limit_train_batches: 0.2
|
||||
limit_val_batches: 0.2
|
||||
limit_test_batches: 0.2
|
||||
# others
|
||||
amp_backend: "native"
|
||||
amp_level: "02"
|
||||
precision: 32
|
||||
accelerator: null
|
||||
num_nodes: 1
|
||||
tpu_cores: null
|
||||
deterministic: False
|
||||
|
||||
# number of sanity validation steps
|
||||
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
|
||||
resume_from_checkpoint: null
|
||||
|
||||
# no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
|
||||
# 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
|
||||
# (requires calling trainer.tune(model=model, datamodule=datamodule))
|
||||
# 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'
|
||||
@@ -8,36 +8,35 @@ min_epochs: 1
|
||||
max_epochs: 10
|
||||
|
||||
# prints
|
||||
progress_bar_refresh_rate: null
|
||||
# progress_bar_refresh_rate: null
|
||||
weights_summary: null
|
||||
profiler: null
|
||||
# profiler: null
|
||||
|
||||
# all of the parameters below are set to Lightning defaults
|
||||
|
||||
# tricks
|
||||
gradient_clip_val: 0
|
||||
accumulate_grad_batches: 1
|
||||
val_check_interval: 1.0
|
||||
check_val_every_n_epoch: 1
|
||||
stochastic_weight_avg: False
|
||||
# gradient_clip_val: 0
|
||||
# accumulate_grad_batches: 1
|
||||
# val_check_interval: 1.0
|
||||
# check_val_every_n_epoch: 1
|
||||
# stochastic_weight_avg: False
|
||||
|
||||
# debug
|
||||
num_sanity_val_steps: 2
|
||||
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
|
||||
# num_sanity_val_steps: 2
|
||||
# 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
|
||||
|
||||
# others
|
||||
amp_backend: "native"
|
||||
amp_level: "02"
|
||||
precision: 32
|
||||
accelerator: null
|
||||
num_nodes: 1
|
||||
tpu_cores: null
|
||||
deterministic: False
|
||||
# amp_backend: "native"
|
||||
# amp_level: "02"
|
||||
# precision: 32
|
||||
# accelerator: null
|
||||
# num_nodes: 1
|
||||
# tpu_cores: null
|
||||
# deterministic: False
|
||||
|
||||
# resume
|
||||
resume_from_checkpoint: null
|
||||
# resume_from_checkpoint: null
|
||||
@@ -2,7 +2,7 @@
|
||||
from setuptools import find_packages, setup
|
||||
|
||||
setup(
|
||||
name="src",
|
||||
name="src", # you should probably change "src" to your project name
|
||||
version="0.0.0",
|
||||
description="Describe Your Cool Project",
|
||||
author="",
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
from typing import Optional, Sequence
|
||||
|
||||
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.transforms import transforms
|
||||
from typing import Optional, Sequence
|
||||
|
||||
|
||||
class MNISTDataModule(LightningDataModule):
|
||||
|
||||
+47
-48
@@ -1,10 +1,10 @@
|
||||
import logging
|
||||
import warnings
|
||||
from typing import List
|
||||
from typing import List, Sequence
|
||||
|
||||
import pytorch_lightning as pl
|
||||
import wandb
|
||||
from hydra.utils import get_original_cwd, log, to_absolute_path
|
||||
from hydra.utils import log
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
from rich import print
|
||||
@@ -12,7 +12,7 @@ from rich.syntax import Syntax
|
||||
from rich.tree import Tree
|
||||
|
||||
|
||||
def extras(config: DictConfig):
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
- disabling warnings
|
||||
- disabling lightning logs
|
||||
@@ -26,7 +26,7 @@ def extras(config: DictConfig):
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# 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
|
||||
|
||||
# [OPTIONAL] Disable python warnings if <config.disable_warnings=True>
|
||||
@@ -60,59 +60,59 @@ def extras(config: DictConfig):
|
||||
OmegaConf.set_struct(config, True)
|
||||
|
||||
|
||||
def print_config(config: DictConfig, resolve: bool = True):
|
||||
"""Prints content of Hydra config using Rich library.
|
||||
def print_config(
|
||||
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:
|
||||
config (DictConfig): [description]
|
||||
resolve (bool, optional): Whether to resolve reference fields in Hydra config.
|
||||
config (DictConfig): 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
|
||||
# directory = to_absolute_path("configs/config.yaml")
|
||||
# print(f"Main config path: [link file://{directory}]{directory}")
|
||||
|
||||
#TODO make this method more general
|
||||
|
||||
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)
|
||||
trainer_branch = tree.add("Trainer", style=style, guide_style=style)
|
||||
trainer_branch.add(Syntax(trainer, "yaml"))
|
||||
for field in fields:
|
||||
branch = tree.add(field, style=style, guide_style=style)
|
||||
|
||||
model = OmegaConf.to_yaml(config["model"], resolve=resolve)
|
||||
model_branch = tree.add("Model", style=style, guide_style=style)
|
||||
model_branch.add(Syntax(model, "yaml"))
|
||||
config_section = config.get(field)
|
||||
|
||||
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=resolve)
|
||||
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style)
|
||||
datamodule_branch.add(Syntax(datamodule, "yaml"))
|
||||
if not config_section:
|
||||
# raise Exception(f"Field {field} not found in config!")
|
||||
branch.add("None")
|
||||
continue
|
||||
|
||||
optimizer = OmegaConf.to_yaml(config["optimizer"], resolve=resolve)
|
||||
optimizer_branch = tree.add("Optimizer", style=style, guide_style=style)
|
||||
optimizer_branch.add(Syntax(optimizer, "yaml"))
|
||||
|
||||
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=resolve), "yaml"))
|
||||
if field in extra_depth_fields:
|
||||
for nested_field in config_section:
|
||||
nested_config_section = config_section[nested_field]
|
||||
nested_branch = branch.add(nested_field, style=style, guide_style=style)
|
||||
cfg_str = OmegaConf.to_yaml(nested_config_section, resolve=resolve)
|
||||
nested_branch.add(Syntax(cfg_str, "yaml"))
|
||||
else:
|
||||
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():
|
||||
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")
|
||||
cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
|
||||
branch.add(Syntax(cfg_str, "yaml"))
|
||||
|
||||
print(tree)
|
||||
|
||||
@@ -124,7 +124,7 @@ def log_hyperparameters(
|
||||
trainer: pl.Trainer,
|
||||
callbacks: List[pl.Callback],
|
||||
logger: List[pl.loggers.LightningLoggerBase],
|
||||
):
|
||||
) -> None:
|
||||
"""This method controls which parameters from Hydra config are saved by Lightning loggers.
|
||||
|
||||
Additionaly saves:
|
||||
@@ -173,9 +173,8 @@ def log_hyperparameters(
|
||||
trainer.logger.log_hyperparams(hparams)
|
||||
|
||||
# disable logging any more hyperparameters for all loggers
|
||||
# (this is just to prevent trainer logging hparams of model as we manage it ourselves)
|
||||
for lg in logger:
|
||||
lg.log_hyperparams = lambda x: None
|
||||
# (this is just a trick to prevent trainer from logging hparams of model, since we already did that above)
|
||||
trainer.logger.log_hyperparams = lambda params: None
|
||||
|
||||
|
||||
def finish(
|
||||
@@ -185,7 +184,7 @@ def finish(
|
||||
trainer: pl.Trainer,
|
||||
callbacks: List[pl.Callback],
|
||||
logger: List[pl.loggers.LightningLoggerBase],
|
||||
):
|
||||
) -> None:
|
||||
"""Makes sure everything closed properly.
|
||||
|
||||
Args:
|
||||
|
||||
+11
-11
@@ -17,59 +17,59 @@ export PYTHONWARNINGS="ignore"
|
||||
|
||||
echo "TEST 1"
|
||||
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
|
||||
|
||||
echo "TEST 2"
|
||||
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 \
|
||||
print_config=false
|
||||
|
||||
echo "TEST 3"
|
||||
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
|
||||
|
||||
echo "TEST 4"
|
||||
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 \
|
||||
print_config=false
|
||||
|
||||
echo "TEST 5"
|
||||
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 \
|
||||
print_config=false
|
||||
|
||||
echo "TEST 6"
|
||||
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
|
||||
|
||||
echo "TEST 7"
|
||||
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 \
|
||||
print_config=false
|
||||
|
||||
echo "TEST 8"
|
||||
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
|
||||
|
||||
echo "TEST 9"
|
||||
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
|
||||
|
||||
echo "TEST 10"
|
||||
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
|
||||
|
||||
echo "TEST 11"
|
||||
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
|
||||
Reference in new issue
Block a user