2021-03-06 21:43:48 +03:00
< div align = "center" >
2021-02-03 15:13:06 +03:00
2021-03-10 17:33:14 +03:00
# Lightning-Hydra-Template
2021-03-07 01:16:26 +03:00
2021-04-07 18:15:09 +03:00
<!--
2021-04-06 16:02:21 +03:00
< a href = "https://pytorch.org/get-started/locally/" > < img alt = "PyTorch" src = "https://img.shields.io/badge/python-3.6%20%7C%203.7%20%7C%203.8-blue?logo=python&logoColor=white&style=for-the-badge" > < / a >
-->
2021-04-04 03:22:26 +03:00
< a href = "https://pytorch.org/get-started/locally/" > < img alt = "PyTorch" src = "https://img.shields.io/badge/-PyTorch-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white" > < / a >
2021-03-30 04:19:32 +03:00
< a href = "https://pytorchlightning.ai/" > < img alt = "Lightning" src = "https://img.shields.io/badge/-Lightning-792ee5?style=for-the-badge" > < / a >
2021-04-04 03:22:26 +03:00
< a href = "https://hydra.cc/" > < img alt = "Config: hydra" src = "https://img.shields.io/badge/config-hydra-89b8cd?style=for-the-badge" > < / a >
< a href = "https://hub.docker.com/r/ashlev/lightning-hydra" > < img alt = "Docker" src = "https://img.shields.io/badge/docker-257bd6?style=for-the-badge&logo=docker&logoColor=white" > < / a >
2021-03-07 01:35:56 +03:00
< a href = "https://black.readthedocs.io/en/stable/" > < img alt = "Code style: black" src = "https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge" > < / a >
2021-03-07 01:16:26 +03:00
2021-03-01 17:00:10 +03:00
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥< br >
2021-04-15 22:13:18 +03:00
Click on [<kbd>Use this template</kbd> ](https://github.com/ashleve/lightning-hydra-template/generate ) to initialize new repository.
2021-01-19 15:48:23 +03:00
2021-04-06 16:02:21 +03:00
*Currently uses dev version of Hydra.< br > Suggestions are always welcome!*
2021-03-04 15:30:51 +03:00
2021-03-01 17:00:10 +03:00
< / div >
2021-03-10 17:33:14 +03:00
< br > < br >
2021-04-07 01:00:32 +03:00
<!--
2021-03-07 01:16:26 +03:00
If you use this template please add < br >
2021-04-15 22:13:18 +03:00
[![ ](https://shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=303030 )](https://github.com/ashleve/lightning-hydra-template) < br >
2021-03-08 17:53:30 +03:00
to your `README.md` .
2021-03-30 04:19:32 +03:00
< br > < br >
2021-04-07 01:00:32 +03:00
-->
2021-02-03 15:13:06 +03:00
2021-04-28 21:02:03 +03:00
## 📌 Introduction
2021-03-15 18:55:06 +03:00
This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [src/train.py ](src/train.py ).
2021-03-10 17:33:14 +03:00
> 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.
2021-04-28 21:02:03 +03:00
**Why you should use it:** it allows you to rapidly iterate over new models/datasets and scale your projects from small single experiments to hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most convenient all-in-one technology stack for Deep Learning research. Good starting point for reproducing papers, kaggle competitions or small-team research projects. It's also a collection of best practices for efficient workflow and reproducibility.
2021-03-10 17:33:14 +03:00
2021-03-12 20:40:24 +03:00
**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.
2021-03-10 17:33:14 +03:00
### Why PyTorch Lightning?
2021-03-12 20:40:24 +03:00
[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.
2021-03-10 17:33:14 +03:00
### Why Hydra?
2021-03-12 20:40:24 +03:00
[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.
2021-03-10 17:33:14 +03:00
< br >
< br >
2021-03-04 15:30:51 +03:00
< br >
2021-03-10 17:33:14 +03:00
## Main Ideas Of This Template
2021-04-04 03:22:26 +03:00
- **Predefined Structure**: clean and scalable so that work can easily be extended and replicated (see [#Project Structure ](#project-structure ))
2021-04-28 21:02:03 +03:00
- **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers (see [#Your Superpowers ](#your-superpowers ))
2021-04-04 03:22:26 +03:00
- **Little Boilerplate**: so pipeline can be easily modified (see [src/train.py ](src/train.py ))
- **Main Configuration**: main config file specifies default training configuration (see [#Main Project Configuration ](#main-project-configuration ))
- **Experiment Configurations**: stored in a separate folder, they can be composed out of smaller configs, override chosen parameters or define everything from scratch (see [#Experiment Configuration ](#experiment-configuration ))
2021-04-28 21:02:03 +03:00
- **Workflow**: comes down to 4 simple steps (see [#Workflow ](#workflow ))
2021-04-04 03:22:26 +03:00
- **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 ))
2021-04-28 21:02:03 +03:00
- **Hyperparameter Search**: made easier with Hydra built in plugins like [Optuna Sweeper ](https://hydra.cc/docs/next/plugins/optuna_sweeper ) (see [#Hyperparameter Search ](#hyperparameter-search ))
2021-04-27 21:13:09 +03:00
- **Tests**: unit tests and smoke tests (see [#Tests ](#tests ))
2021-04-28 21:02:03 +03:00
- **Extra Features**: optional utilities to make your life easier (see [#Extra Features ](#extra-features ))
- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices ](#best-practices ))
2021-03-01 17:00:10 +03:00
< br >
2021-02-03 15:13:06 +03:00
2021-01-19 05:09:52 +03:00
2021-03-01 17:00:10 +03:00
## Project Structure
2021-03-06 21:43:48 +03:00
The directory structure of new project looks like this:
2021-01-13 02:53:16 +03:00
```
2021-03-01 17:00:10 +03:00
├── configs < - Hydra configuration files
2021-04-05 20:39:56 +03:00
│ ├── callbacks < - Callbacks configs
│ ├── datamodule < - Datamodule configs
│ ├── experiment < - Experiment configs
2021-04-15 22:13:18 +03:00
│ ├── hparams_search < - Hyperparameter search configs
2021-04-28 21:02:03 +03:00
│ ├── hydra < - Hydra related configs
2021-04-05 20:39:56 +03:00
│ ├── logger < - Logger configs
│ ├── model < - Model configs
│ ├── trainer < - Trainer configs
2021-03-06 21:43:48 +03:00
│ │
2021-04-15 22:13:18 +03:00
│ └── config.yaml < - Main project configuration file
2021-03-01 17:00:10 +03:00
│
├── data < - Project data
│
├── logs < - Logs generated by Hydra and PyTorch Lightning loggers
│
2021-04-05 20:39:56 +03:00
├── notebooks < - Jupyter notebooks . Naming convention is a number ( for ordering ) ,
│ the creator's initials, and a short `-` delimited description, e.g.
│ `1.0-jqp-initial-data-exploration.ipynb` .
2021-03-01 17:00:10 +03:00
│
├── tests < - Tests of any kind
2021-04-27 00:06:50 +03:00
│ ├── smoke_tests
│ └── unit_tests
2021-03-01 17:00:10 +03:00
│
├── src
2021-04-05 20:39:56 +03:00
│ ├── callbacks < - Lightning callbacks
│ ├── datamodules < - Lightning datamodules
│ ├── models < - Lightning models
2021-03-15 18:55:06 +03:00
│ ├── utils < - Utility scripts
│ │ ├── inference_example.py < - Example of inference with trained model
2021-04-05 20:39:56 +03:00
│ │ └── template_utils.py < - Extra features for the template
2021-03-15 18:55:06 +03:00
│ │
2021-04-05 20:39:56 +03:00
│ └── train.py < - Training pipeline
2021-03-01 17:00:10 +03:00
│
2021-04-05 22:14:23 +03:00
├── run.py < - Run any pipeline with chosen experiment configuration
2021-01-13 02:53:16 +03:00
│
2021-04-05 20:39:56 +03:00
├── .env.template < - Template of file for storing private environment variables
2021-03-15 18:55:06 +03:00
├── .gitignore < - List of files / folders ignored by git
2021-04-04 03:22:26 +03:00
├── .pre-commit-config.yaml < - Configuration of automatic code formatting
2021-03-15 18:55:06 +03:00
├── conda_env_gpu.yaml < - File for installing conda environment
2021-01-14 22:04:54 +03:00
├── requirements.txt < - File for installing python dependencies
2021-03-15 18:55:06 +03:00
├── LICENSE
└── README.md
2021-01-13 02:53:16 +03:00
```
< br >
2021-04-28 21:02:03 +03:00
## 🚀 Quickstart
2021-03-07 04:32:10 +03:00
```yaml
# clone project
2021-04-07 18:15:09 +03:00
git clone https://github.com/ashleve/lightning-hydra-template
2021-03-07 04:32:10 +03:00
cd lightning-hydra-template
2021-03-08 17:53:30 +03:00
# [OPTIONAL] create conda environment
2021-04-05 20:39:56 +03:00
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
2021-03-07 04:32:10 +03:00
# install requirements
pip install -r requirements.txt
```
2021-03-15 18:55:06 +03:00
Template contains example with MNIST classification.< br >
When running `python run.py` you should see something like this:
2021-03-07 04:32:10 +03:00
< div align = "center" >
2021-03-08 17:53:30 +03:00
2021-04-15 22:13:18 +03:00
![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png)
2021-03-07 04:32:10 +03:00
< / div >
2021-04-28 21:02:03 +03:00
### ⚡ Your Superpowers
2021-04-04 03:22:26 +03:00
(click to expand)
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Override any config parameter from command line< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-04-04 03:22:26 +03:00
> Hydra allows you to easily overwrite any parameter defined in your config.
2021-03-07 04:32:10 +03:00
```yaml
2021-04-27 00:06:50 +03:00
python run.py trainer.max_epochs=20 model.lr=1e-4
2021-03-12 20:40:24 +03:00
```
2021-03-30 04:19:32 +03:00
> You can also add new parameters with `+` sign.
2021-03-12 20:40:24 +03:00
```yaml
2021-03-25 03:31:52 +03:00
python run.py +model.new_param="uwu"
2021-03-12 20:40:24 +03:00
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-28 21:02:03 +03:00
< summary > < b > Train on CPU, GPU, multi-GPU and TPU< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-04-04 03:22:26 +03:00
> PyTorch Lightning makes it easy to train your models on different hardware.
2021-03-07 04:32:10 +03:00
```yaml
2021-03-10 17:33:14 +03:00
# train on CPU
2021-03-15 18:55:06 +03:00
python run.py trainer.gpus=0
2021-03-10 17:33:14 +03:00
# train on 1 GPU
2021-03-15 18:55:06 +03:00
python run.py trainer.gpus=1
2021-03-10 17:33:14 +03:00
# train on TPU
2021-03-15 18:55:06 +03:00
python run.py +trainer.tpu_cores=8
2021-03-10 17:33:14 +03:00
2021-03-30 04:19:32 +03:00
# train with DDP (Distributed Data Parallel) (4 GPUs)
python run.py trainer.gpus=4 +trainer.accelerator='ddp'
2021-03-10 17:33:14 +03:00
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
2021-03-15 18:55:06 +03:00
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
2021-04-28 21:02:03 +03:00
```
< / details >
2021-03-10 17:33:14 +03:00
2021-04-28 21:02:03 +03:00
< details >
< summary > < b > Train with mixed precision< / b > < / summary >
```yaml
# train with mixed precision (Apex level O1)
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
+trainer.amp_level="O1"
# train with mixed precision (Apex level O2)
2021-03-30 04:19:32 +03:00
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
+trainer.amp_level="O2"
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Train model with any logger available in PyTorch Lightning, like Weights& Biases< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-04-04 03:22:26 +03:00
> PyTorch Lightning provides convenient integrations with most popular logging frameworks. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below.<br>
**Click [here ](https://wandb.ai/hobglob/template-dashboard/ ) to see example wandb dashboard generated with this template.**
2021-03-07 04:32:10 +03:00
```yaml
2021-03-10 17:33:14 +03:00
# set project and entity names in `configs/logger/wandb`
2021-03-07 04:32:10 +03:00
wandb:
project: "your_project_name"
entity: "your_wandb_team_name"
```
```yaml
# train model with Weights&Biases
2021-03-10 17:33:14 +03:00
# link to wandb dashboard should appear in the terminal
2021-03-15 18:55:06 +03:00
python run.py logger=wandb
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Train model with chosen experiment config< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-03-30 04:19:32 +03:00
> Experiment configurations are placed in [configs/experiment/](configs/experiment/).
2021-03-07 04:32:10 +03:00
```yaml
2021-04-27 00:06:50 +03:00
python run.py experiment=example_simple
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Attach some callbacks to run< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-03-30 04:19:32 +03:00
> 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/ ](configs/callbacks/ ).
2021-03-07 04:32:10 +03:00
```yaml
2021-04-27 00:06:50 +03:00
python run.py callbacks=default
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Use different tricks available in Pytorch Lightning< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-03-30 04:19:32 +03:00
> PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).
2021-03-07 04:32:10 +03:00
```yaml
2021-03-10 17:33:14 +03:00
# gradient clipping may be enabled to avoid exploding gradients
2021-03-15 18:55:06 +03:00
python run.py +trainer.gradient_clip_val=0.5
2021-03-10 17:33:14 +03:00
# stochastic weight averaging can make your models generalize better
2021-04-07 18:15:09 +03:00
python run.py +trainer.stochastic_weight_avg=true
2021-03-10 17:33:14 +03:00
# run validation loop 4 times during a training epoch
2021-03-15 18:55:06 +03:00
python run.py +trainer.val_check_interval=0.25
2021-03-10 19:48:23 +03:00
# accumulate gradients
2021-03-15 18:55:06 +03:00
python run.py +trainer.accumulate_grad_batches=10
2021-04-28 21:02:03 +03:00
# terminate training after 12 hours
python run.py +trainer.max_time="00:12:00:00"
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Easily debug< / b > < / summary >
2021-03-07 04:32:10 +03:00
```yaml
2021-03-08 17:53:30 +03:00
# run 1 train, val and test loop, using only 1 batch
2021-03-15 18:55:06 +03:00
python run.py debug=true
2021-03-10 17:33:14 +03:00
# print full weight summary of all PyTorch modules
2021-03-15 18:55:06 +03:00
python run.py trainer.weights_summary="full"
2021-03-10 17:33:14 +03:00
# print execution time profiling after training ends
2021-03-15 18:55:06 +03:00
python run.py +trainer.profiler="simple"
2021-03-10 17:33:14 +03:00
2021-04-07 18:15:09 +03:00
# raise exception, if any of the parameters or the loss are NaN or +/-inf
python run.py trainer.terminate_on_nan=true
2021-03-10 19:48:23 +03:00
# try overfitting to 1 batch
2021-03-15 18:55:06 +03:00
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
2021-03-10 17:33:14 +03:00
# use only 20% of the data
2021-03-15 18:55:06 +03:00
python run.py +trainer.limit_train_batches=0.2 \
2021-03-12 20:40:24 +03:00
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
2021-04-28 21:02:03 +03:00
# log second gradient norm of the model
python run.py +trainer.track_grad_norm=2
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Resume training from checkpoint< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-04-04 03:22:26 +03:00
> Checkpoint can be either path or URL. Path should be absolute!
2021-03-07 04:32:10 +03:00
```yaml
2021-03-15 18:55:06 +03:00
python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
2021-03-07 04:32:10 +03:00
```
2021-04-04 03:22:26 +03:00
> ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.
2021-03-07 04:32:10 +03:00
< / details >
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Create a sweep over hyperparameters< / b > < / summary >
2021-03-08 17:53:30 +03:00
2021-03-07 04:32:10 +03:00
```yaml
2021-03-08 17:53:30 +03:00
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
2021-04-27 00:06:50 +03:00
python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
2021-03-08 17:53:30 +03:00
```
2021-04-04 03:22:26 +03:00
> ⚠️ Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
2021-03-08 17:53:30 +03:00
< / details >
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Create a sweep over hyperparameters with Optuna< / b > < / summary >
2021-03-08 17:53:30 +03:00
2021-03-30 04:19:32 +03:00
> 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](configs/config_optuna.yaml)!
2021-03-08 17:53:30 +03:00
```yaml
2021-04-15 22:13:18 +03:00
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
2021-03-08 17:53:30 +03:00
# over chosen experiment config
2021-04-27 00:06:50 +03:00
python run.py -m hparams_search=mnist_optuna experiment=example_simple
2021-03-07 04:32:10 +03:00
```
< / details >
2021-03-10 17:33:14 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Execute all experiments from folder< / b > < / summary >
2021-03-10 17:33:14 +03:00
2021-03-30 04:19:32 +03:00
> Hydra provides special syntax for controlling behavior of multiruns. Learn more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run). The command below executes all experiments from folder [configs/experiment/](configs/experiment/).
2021-03-10 17:33:14 +03:00
```yaml
2021-04-15 22:13:18 +03:00
python run.py -m 'experiment=glob(*)'
2021-03-10 17:33:14 +03:00
```
2021-03-07 04:32:10 +03:00
2021-03-10 17:33:14 +03:00
< / details >
2021-03-07 04:32:10 +03:00
2021-03-10 17:33:14 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Execute sweep on a remote AWS cluster< / b > < / summary >
2021-03-10 17:33:14 +03:00
2021-03-30 04:19:32 +03:00
> This should be achievable with simple config using [Ray AWS launcher for Hydra](https://hydra.cc/docs/next/plugins/ray_launcher). Example is not yet implemented in this template.
2021-03-10 17:33:14 +03:00
< / details >
2021-03-15 23:18:39 +03:00
< details >
2021-04-28 21:02:03 +03:00
< summary > < b > Execute sweep on a SLURM cluster< / b > < / summary >
2021-03-15 23:18:39 +03:00
2021-04-28 21:02:03 +03:00
> This should be achievable with either [the right lightning trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/clouds/cluster.html?highlight=SLURM#slurm-managed-cluster) or simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.
2021-03-15 23:18:39 +03:00
< / details >
2021-03-30 04:19:32 +03:00
2021-03-15 23:18:39 +03:00
< details >
2021-04-04 03:22:26 +03:00
< summary > < b > Use Hydra tab completion< / b > < / summary >
2021-03-15 23:18:39 +03:00
2021-03-30 04:19:32 +03:00
> Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Learn more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).
2021-03-23 00:53:55 +03:00
< / details >
2021-04-04 03:22:26 +03:00
< br >
2021-03-30 04:19:32 +03:00
2021-03-15 23:18:39 +03:00
2021-04-28 21:02:03 +03:00
## 🐳 Docker
2021-04-22 23:08:57 +03:00
I recommend the official [nvidia ngc pytorch container ](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags ) (size: 6GB, it comes with installed Apex for mixed-precision training), or "devel" version of [pytorch/pytorch ](https://hub.docker.com/r/pytorch/pytorch ).
2021-04-04 03:22:26 +03:00
2021-04-22 23:08:57 +03:00
Custom dockerfiles for the template are provided on branch [`dockerfiles` ](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles ). You can use them as a starting point for building your own images.
2021-04-04 03:22:26 +03:00
```yaml
# download image
2021-04-22 23:08:57 +03:00
docker pull nvcr.io/nvidia/pytorch:21.03-py3
2021-02-03 15:13:06 +03:00
2021-04-22 23:08:57 +03:00
# run container from image with GPUs enabled
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
2021-04-04 03:22:26 +03:00
```
2021-04-27 21:13:09 +03:00
<!--
# run container with mounted volume
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
-->
2021-04-22 23:08:57 +03:00
< br > < br >
2021-04-07 01:02:36 +03:00
2021-04-07 01:00:32 +03:00
2021-04-28 21:02:03 +03:00
## ❤️ Contributions
2021-04-15 22:13:18 +03:00
Have a question? Found a bug? Missing a specific feature? Ran into a problem? Feel free to file a new issue or PR with respective title and description. If you already found a solution to your problem, don't hesitate to share it. Suggestions for new best practices and tricks are always welcome!
2021-04-07 18:15:09 +03:00
< br > < br > < br > < br >
2021-03-15 23:18:39 +03:00
2021-04-04 03:22:26 +03:00
2021-04-07 01:02:36 +03:00
2021-04-28 21:02:03 +03:00
## ℹ ️ Guide
2021-03-10 17:33:14 +03:00
2021-04-27 00:06:50 +03:00
### How To Get Started
2021-03-10 17:33:14 +03:00
- First, you should probably get familiar with [PyTorch Lightning ](https://www.pytorchlightning.ai )
2021-03-11 02:13:52 +03:00
- Next, go through [Hydra quick start guide ](https://hydra.cc/docs/intro/ ), [basic Hydra tutorial ](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/ ) and [docs about instantiating objects with Hydra ](https://hydra.cc/docs/patterns/instantiate_objects/overview )
2021-03-10 17:33:14 +03:00
< br >
2021-04-05 20:39:56 +03:00
### How it works
2021-04-29 01:57:31 +03:00
By design, every run is initialized by [run.py ](run.py ) file. All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
2021-04-05 20:39:56 +03:00
```yaml
_target_: src.models.mnist_model.MNISTLitModel
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
lr: 0.001
```
2021-04-28 21:02:03 +03:00
Using this config we can instantiate the object with the following line:
```python
model = hydra.utils.instantiate(config.model)
```
This allows you to easily iterate over new models!< br >
2021-04-29 01:57:31 +03:00
Every time you create a new one, just specify its module path and parameters in appriopriate config file. < br >
2021-04-28 21:02:03 +03:00
The whole pipeline managing the instantiation logic is placed in [src/train.py ](src/train.py ).
2021-04-05 20:39:56 +03:00
< br >
2021-03-10 17:33:14 +03:00
### Main Project Configuration
2021-03-01 17:00:10 +03:00
Location: [configs/config.yaml ](configs/config.yaml )< br >
Main project config contains default training configuration.< br >
2021-03-15 18:55:06 +03:00
It determines how config is composed when simply executing command `python run.py` .< br >
2021-03-10 17:33:14 +03:00
It also specifies everything that shouldn't be managed by experiment configurations.
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Show main project configuration< / b > < / summary >
2021-01-13 02:53:16 +03:00
```yaml
# specify here default training configuration
defaults:
2021-04-27 00:06:50 +03:00
- trainer: minimal.yaml
2021-01-16 18:33:44 +03:00
- model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml
2021-04-27 00:06:50 +03:00
- callbacks: default.yaml # set this to null if you don't want to use callbacks
2021-03-15 18:55:06 +03:00
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb` )
2021-01-13 02:53:16 +03:00
2021-04-28 21:02:03 +03:00
- experiment: null
- hparams_search: null
- hydra: default.yaml
# enable color logging
- override hydra/hydra_logging: colorlog
- override hydra/job_logging: colorlog
2021-01-18 20:30:24 +03:00
2021-03-25 03:31:52 +03:00
# path to original working directory
2021-04-28 21:02:03 +03:00
# hydra hijacks working directory by changing it to the current log directory,
2021-03-25 03:31:52 +03:00
# so it's useful to have this path as a special variable
# learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
2021-03-01 17:00:10 +03:00
work_dir: ${hydra:runtime.cwd}
2021-01-18 20:30:24 +03:00
2021-01-13 02:53:16 +03:00
# path to folder with data
2021-03-01 17:00:10 +03:00
data_dir: ${work_dir}/data/
2021-03-15 18:55:06 +03:00
# use `python run.py debug=true` for easy debugging!
2021-04-28 21:02:03 +03:00
# this will run 1 train, val and test loop with only 1 batch
# equivalent to running `python run.py trainer.fast_dev_run=true`
# (this is placed here just for easier access from command line)
2021-03-08 17:53:30 +03:00
debug: False
2021-03-01 17:00:10 +03:00
# pretty print config at the start of the run using Rich library
print_config: True
2021-01-13 02:53:16 +03:00
2021-01-18 20:30:24 +03:00
2021-03-07 04:32:10 +03:00
# disable python warnings if they annoy you
2021-04-28 21:02:03 +03:00
ignore_warnings: True
2021-03-07 04:32:10 +03:00
2021-01-13 02:53:16 +03:00
```
2021-04-04 03:22:26 +03:00
< / details >
2021-01-13 02:53:16 +03:00
< br >
2021-04-04 03:22:26 +03:00
2021-03-10 17:33:14 +03:00
### Experiment Configuration
2021-03-01 17:00:10 +03:00
Location: [configs/experiment ](configs/experiment )< br >
2021-03-08 17:53:30 +03:00
You should store all your experiment configurations in this folder.< br >
2021-03-10 17:33:14 +03:00
Experiment configurations allow you to overwrite parameters from main project configuration.
2021-04-04 03:22:26 +03:00
**Simple example**
2021-01-13 02:53:16 +03:00
```yaml
2021-01-19 04:23:13 +03:00
# to execute this experiment run:
2021-04-27 21:13:09 +03:00
# python run.py experiment=example_simple
2021-01-19 04:23:13 +03:00
2021-01-13 02:53:16 +03:00
defaults:
2021-04-27 00:06:50 +03:00
- override /trainer: minimal.yaml
2021-01-19 05:09:52 +03:00
- override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml
2021-04-27 00:06:50 +03:00
- override /callbacks: default.yaml
2021-01-19 05:09:52 +03:00
- override /logger: null
2021-01-13 02:53:16 +03:00
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
2021-03-06 21:43:48 +03:00
seed: 12345
2021-01-13 02:53:16 +03:00
trainer:
2021-01-19 04:23:13 +03:00
max_epochs: 10
gradient_clip_val: 0.5
2021-01-13 02:53:16 +03:00
model:
2021-01-19 04:23:13 +03:00
lin1_size: 128
lin2_size: 256
lin3_size: 64
2021-03-10 17:33:14 +03:00
lr: 0.005
2021-01-13 02:53:16 +03:00
datamodule:
2021-01-19 04:23:13 +03:00
train_val_test_split: [55_000, 5_000, 10_000]
2021-04-05 22:14:23 +03:00
batch_size: 64
2021-01-13 02:53:16 +03:00
```
2021-04-04 03:22:26 +03:00
< / details >
2021-01-13 02:53:16 +03:00
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Advanced example< / b > < / summary >
2021-03-10 17:33:14 +03:00
2021-01-19 05:09:52 +03:00
```yaml
# to execute this experiment run:
2021-04-27 21:13:09 +03:00
# python run.py experiment=example_full
2021-01-19 05:09:52 +03:00
defaults:
- override /trainer: null
- override /model: null
2021-03-06 21:43:48 +03:00
- override /datamodule: null
2021-03-01 17:00:10 +03:00
- override /callbacks: null
2021-01-19 05:09:52 +03:00
- override /logger: null
2021-01-19 05:18:43 +03:00
# we override default configurations with nulls to prevent them from loading at all
2021-03-06 21:43:48 +03:00
# instead we define all modules and their paths directly in this config,
2021-04-27 00:06:50 +03:00
# so everything is stored in one place
2021-01-19 05:09:52 +03:00
2021-03-01 17:00:10 +03:00
seed: 12345
2021-01-19 05:09:52 +03:00
trainer:
_target_ : pytorch_lightning.Trainer
2021-03-01 17:00:10 +03:00
gpus: 0
2021-01-19 05:09:52 +03:00
min_epochs: 1
max_epochs: 10
gradient_clip_val: 0.5
model:
2021-04-05 22:14:23 +03:00
_target_ : src.models.mnist_model.MNISTLitModel
2021-04-05 20:39:56 +03:00
lr: 0.001
weight_decay: 0.00005
2021-01-19 05:09:52 +03:00
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 128
output_size: 10
datamodule:
2021-04-05 22:14:23 +03:00
_target_ : src.datamodules.mnist_datamodule.MNISTDataModule
2021-01-19 05:09:52 +03:00
data_dir: ${data_dir}
train_val_test_split: [55_000, 5_000, 10_000]
2021-04-05 22:14:23 +03:00
batch_size: 64
2021-03-01 17:00:10 +03:00
num_workers: 0
2021-01-19 05:09:52 +03:00
pin_memory: False
2021-03-01 17:00:10 +03:00
logger:
wandb:
2021-03-10 17:33:14 +03:00
_target_ : pytorch_lightning.loggers.wandb.WandbLogger
project: "lightning-hydra-template"
2021-03-01 17:00:10 +03:00
tags: ["best_model", "uwu"]
notes: "Description of this model."
2021-01-19 05:09:52 +03:00
```
2021-04-04 03:22:26 +03:00
< / details >
2021-02-03 15:13:06 +03:00
< br >
2021-01-19 05:09:52 +03:00
2021-03-10 17:33:14 +03:00
### Workflow
2021-04-06 16:02:21 +03:00
1. Write your PyTorch Lightning model (see [mnist_model.py ](src/models/mnist_model.py ) for example)
2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py ](src/datamodules/mnist_datamodule.py ) for example)
2021-04-04 03:22:26 +03:00
3. Write your experiment config, containing paths to your model and datamodule
2021-04-27 21:13:09 +03:00
4. Run training with chosen experiment config: `python run.py experiment=experiment_name`
2021-03-04 15:30:51 +03:00
< br >
2021-03-10 17:33:14 +03:00
### Logs
2021-03-01 17:00:10 +03:00
Hydra creates new working directory for every executed run. < br >
2021-02-03 15:13:06 +03:00
By default, logs have the following structure:
2021-01-13 02:53:16 +03:00
```
2021-03-01 17:00:10 +03:00
│
2021-01-13 02:53:16 +03:00
├── logs
2021-03-01 17:00:10 +03:00
│ ├── runs # Folder for logs generated from single runs
2021-01-13 02:53:16 +03:00
│ │ ├── 2021-02-15 # Date of executing run
│ │ │ ├── 16-50-49 # Hour of executing run
│ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ ├── wandb # Weights& Biases logs
2021-02-03 15:13:06 +03:00
│ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ └── ... # Any other thing saved during training
2021-01-13 02:53:16 +03:00
│ │ │ ├── ...
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
2021-03-01 17:00:10 +03:00
│ └── multiruns # Folder for logs generated from multiruns (sweeps)
│ ├── 2021-02-15_16-50-49 # Date and hour of executing sweep
│ │ ├── 0 # Job number
│ │ │ ├── .hydra # Hydra logs
│ │ │ ├── wandb # Weights& Biases logs
│ │ │ ├── checkpoints # Training checkpoints
│ │ │ └── ... # Any other thing saved during training
│ │ ├── 1
│ │ ├── 2
│ │ └── ...
│ ├── ...
│ └── ...
2021-03-06 21:43:48 +03:00
│
2021-01-13 02:53:16 +03:00
```
2021-04-04 03:22:26 +03:00
2021-04-28 21:02:03 +03:00
You can change this structure by modifying paths in [hydra configuration ](configs/hydra/default.yaml ).
2021-03-01 17:00:10 +03:00
< br > < br >
2021-03-10 17:33:14 +03:00
### Experiment Tracking
2021-04-04 03:22:26 +03:00
PyTorch Lightning supports the most popular logging frameworks:< br >
2021-04-06 16:02:21 +03:00
**[Weights& Biases](https://www.wandb.com/) · [Neptune ](https://neptune.ai/ ) · [Comet ](https://www.comet.ml/ ) · [MLFlow ](https://mlflow.org ) · [Aim ](https://github.com/aimhubio/aim ) · [Tensorboard ](https://www.tensorflow.org/tensorboard/ )**
2021-03-10 17:33:14 +03:00
These tools help you keep track of hyperparameters and output metrics and allow you to compare and visualize results. To use one of them simply complete its configuration in [configs/logger ](configs/logger ) and run:
```yaml
2021-03-15 18:55:06 +03:00
python run.py logger=logger_name
2021-03-04 15:30:51 +03:00
```
2021-03-10 17:33:14 +03:00
You can use many of them at once (see [configs/logger/many_loggers.yaml ](configs/logger/many_loggers.yaml ) for example).< br >
You can also write your own logger.< br >
2021-04-06 16:02:21 +03:00
Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs [here ](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging ) or take a look at [MNIST example ](src/models/mnist_model.py ).
2021-03-01 17:00:10 +03:00
< br > < br >
2021-03-15 18:55:06 +03:00
2021-04-28 21:02:03 +03:00
### Hyperparameter Search
Defining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search ](configs/hparams_search ).
< details >
2021-04-29 01:57:31 +03:00
< summary > < b > Show example< / b > < / summary >
2021-04-28 21:02:03 +03:00
```yaml
defaults:
- override /hydra/sweeper: optuna
# choose metric which will be optimized by Optuna
optimized_metric: "val/acc_best"
hydra:
# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra .main decorator
# learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper
sweeper:
_target_ : hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
storage: null
study_name: null
n_jobs: 1
# 'minimize' or 'maximize' the objective
direction: maximize
# number of experiments that will be executed
n_trials: 20
# choose Optuna hyperparameter sampler
# learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html
sampler:
_target_ : optuna.samplers.TPESampler
seed: 12345
consider_prior: true
prior_weight: 1.0
consider_magic_clip: true
consider_endpoints: false
n_startup_trials: 10
n_ei_candidates: 24
multivariate: false
warn_independent_sampling: true
# define range of hyperparameters
search_space:
datamodule.batch_size:
type: categorical
choices: [32, 64, 128]
model.lr:
type: float
low: 0.0001
high: 0.2
model.lin1_size:
type: categorical
choices: [32, 64, 128, 256, 512]
model.lin2_size:
type: categorical
choices: [32, 64, 128, 256, 512]
model.lin3_size:
type: categorical
choices: [32, 64, 128, 256, 512]
```
< / details >
2021-04-29 01:57:31 +03:00
Next, you can execute it with: `python run.py hparams_search=hparams_config_name` . < br >
2021-04-28 21:02:03 +03:00
Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file! You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.
< br > < br >
2021-03-15 18:55:06 +03:00
### Inference
2021-03-15 19:24:56 +03:00
Template contains simple example of loading model from checkpoint and running predictions.< br >
2021-03-15 18:55:06 +03:00
Take a look at [inference_example.py ](src/utils/inference_example.py ).
< br > < br >
2021-04-27 21:13:09 +03:00
### Tests
Template comes with example tests implemented with pytest library. < br >
To execute them simply run:
```yaml
# run all tests
pytest
# run tests from specific file
pytest tests/smoke_tests/test_commands.py
# run all tests except the ones using wandb
pytest -k "not wandb"
```
I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests ](tests/smoke_tests ) folder.
You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).
< br > < br >
2021-03-10 17:33:14 +03:00
### Callbacks
2021-04-06 16:02:21 +03:00
Template contains example callbacks enabling better Weights& Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py ](src/callbacks/wandb_callbacks.py )).< br >
2021-04-27 00:06:50 +03:00
To support reproducibility:
- **WatchModel**
- **UploadCodeAsArtifact**
- **UploadCheckpointsAsArtifact**
To provide examples of logging custom visualisations with callbacks only:
- **LogConfusionMatrix**
- **LogF1PrecRecHeatmap**
- **ImagePredictionLogger**
2021-03-30 04:19:32 +03:00
< br >
### Multi-GPU Training
Lightning supports multiple ways of doing distributed training.< br >
The most common one is DDP, which spawns separate process for each GPU and averages gradients between them. To learn about other approaches read [lightning docs ](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html ).
You can run DDP on mnist example with 4 GPUs like this:
```yaml
python run.py trainer.gpus=4 +trainer.accelerator="ddp"
```
2021-04-04 03:22:26 +03:00
⚠️ When using DDP you have to be careful how you write your models - learn more [here ](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html ).
2021-04-05 20:39:56 +03:00
<!--
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Use metrics api objects< / b > < / summary >
Use metrics api objects, e.g. `pytorch_lightning.metrics.classification.Accuracy` when logging metrics in `LightningModule` , to ensure proper reduction over multiple GPUs. You can also use `sync_dist` parameter instead with `self.log(..., sync_dist=True)` . Learn more [here ](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#synchronize-validation-and-test-logging ).
< / details >
2021-03-30 04:19:32 +03:00
3. Remember `outputs` parameters in hooks like `validation_epoch_end()` will contain only outputs from subset of data processed on given GPU.
4. Init tensors using `type_as` and `register_buffer` . Learn more [here ](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#init-tensors-using-type-as-and-register-buffer ).
5. Make sure your model is pickable. Learn more [here ](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#make-models-pickleable ).
2021-04-04 03:22:26 +03:00
-->
< br >
2021-03-10 17:33:14 +03:00
2021-03-30 04:19:32 +03:00
### Extra Features
List of extra utilities available in the template:
2021-04-05 22:14:23 +03:00
- loading environment variables from [.env ](.env.template ) file
2021-03-30 04:19:32 +03:00
- pretty printing config with [Rich ](https://github.com/willmcgugan/rich ) library
- disabling python warnings
- easier access to debug mode
- forcing debug friendly configuration
- forcing multi-gpu friendly configuration
- method for logging hyperparameters to loggers
2021-04-27 21:13:09 +03:00
<!-- - (TODO) resuming latest run -->
2021-03-30 04:19:32 +03:00
2021-04-15 22:13:18 +03:00
You can easily remove any of those by modifying [run.py ](run.py ) and [src/train.py ](src/train.py ).
2021-04-04 03:22:26 +03:00
< br > < br >
2021-04-27 21:13:09 +03:00
<!--
2021-04-04 03:22:26 +03:00
### Limitations
(TODO)
2021-03-30 04:19:32 +03:00
< br > < br > < br >
2021-04-27 21:13:09 +03:00
-->
2021-03-10 17:33:14 +03:00
## Best Practices
2021-04-27 21:13:09 +03:00
<!-- <details>
2021-04-27 00:06:50 +03:00
< summary > < b > Write unit tests and smoke tests< / b > < / summary >
Template comes with example tests implemented with pytest library. < br >
To execute them simply run:
```yaml
# run all tests
pytest
# run tests from specific file
pytest tests/smoke_tests/test_commands.py
# run all tests except the ones using wandb
pytest -k "not wandb"
```
2021-04-27 21:13:09 +03:00
I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exists to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests ](tests/smoke_tests ) folder.
2021-04-27 00:06:50 +03:00
You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).< br >
< / details >
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Use Docker< / b > < / summary >
2021-04-06 16:02:21 +03:00
Docker makes it easy to initialize the whole training environment, e.g. when you want to execute experiments in cloud or on some private computing cluster. You can extend [dockerfiles ](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles ) provided in the template with your own instructions for building the image.< br >
2021-04-04 03:22:26 +03:00
2021-04-27 21:13:09 +03:00
< / details > -->
2021-04-04 03:22:26 +03:00
< details >
2021-04-28 21:02:03 +03:00
< summary > < b > Use Miniconda for GPU environments< / b > < / summary >
2021-03-10 17:33:14 +03:00
2021-03-15 23:18:39 +03:00
Use miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough).
It makes it easier to install some dependencies, like cudatoolkit for GPU support.< br >
Example installation:
```yaml
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
2021-04-27 00:06:50 +03:00
Create environment from file provided in the template:
```yaml
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
```
2021-03-15 23:18:39 +03:00
2021-04-04 03:22:26 +03:00
< / details >
< details >
< summary > < b > Use automatic code formatting< / b > < / summary >
2021-03-15 23:18:39 +03:00
2021-03-10 17:33:14 +03:00
Use pre-commit hooks to standardize code formatting of your project and save mental energy.< br >
Simply install pre-commit package with:
```yaml
pip install pre-commit
```
2021-03-12 20:40:24 +03:00
Next, install hooks from [.pre-commit-config.yaml ](.pre-commit-config.yaml ):
```yaml
2021-03-10 17:33:14 +03:00
pre-commit install
```
After that your code will be automatically reformatted on every new commit.< br >
2021-03-15 18:55:06 +03:00
Currently template contains configurations of **Black** (python code formatting) and **Isort** (python import sorting). You can exclude chosen files from automatic formatting, by modifying [.pre-commit-config.yaml ](.pre-commit-config.yaml ).< br >
2021-04-04 03:22:26 +03:00
To reformat all files in the project use command:
2021-03-10 17:33:14 +03:00
```yaml
2021-03-30 04:19:32 +03:00
pre-commit run -a
2021-03-10 17:33:14 +03:00
```
2021-03-15 18:55:06 +03:00
2021-04-04 03:22:26 +03:00
< / details >
2021-03-15 18:55:06 +03:00
2021-04-04 03:22:26 +03:00
< details >
2021-04-05 20:39:56 +03:00
< summary > < b > Set private environment variables in .env file< / b > < / summary >
2021-03-15 18:55:06 +03:00
2021-04-05 20:39:56 +03:00
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.< br >
2021-03-15 18:55:06 +03:00
2021-04-05 20:39:56 +03:00
Template contains `.env.template` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore).
2021-03-23 00:53:55 +03:00
You should use it for storing environment variables like this:
2021-04-05 22:48:47 +03:00
```yaml
MY_VAR=/home/user/my_system_path
2021-03-15 18:55:06 +03:00
```
2021-03-15 23:18:39 +03:00
All variables from `.env` are loaded in `run.py` automatically.
Hydra allows you to reference any env variable in `.yaml` configs like this:
2021-03-15 18:55:06 +03:00
```yaml
2021-04-28 21:02:03 +03:00
path_to_data: ${oc.env:MY_VAR}
2021-03-15 18:55:06 +03:00
```
2021-04-04 03:22:26 +03:00
< / details >
< details >
< summary > < b > Name metrics using '/' character< / b > < / summary >
Depending on which logger you're using, it's often useful to define metric name with `/` character:
```python
self.log("train/loss", loss)
```
This way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.
< / details >
2021-04-28 21:02:03 +03:00
< details >
< summary > < b > Use torchmetrics< / b > < / summary >
Use official [torchmetrics ](https://github.com/PytorchLightning/metrics ) library to ensure proper calculation of metrics. This is especially important for multi-GPU training!
For example, instead of calculating accuracy by yourself, you should use the provided `Accuracy` class like this:
```python
from torchmetrics.classification.accuracy import Accuracy
class LitModel(LightningModule):
def __init__ (self)
self.train_acc = Accuracy()
self.val_acc = Accuracy()
def training_step(self, batch, batch_idx):
...
acc = self.train_acc(predictions, targets)
self.log("train/acc", acc)
...
def validation_step(self, batch, batch_idx):
...
acc = self.val_acc(predictions, targets)
self.log("val/acc", acc)
...
```
Make sure to use different metric instance for each step to ensure proper value reduction over all GPU processes.
Torchmetrics provides metrics for most use cases, like F1 score or confusion matrix. Read [documentation ](https://torchmetrics.readthedocs.io/en/latest/#more-reading ) for more.
< / details >
2021-04-05 20:39:56 +03:00
< details >
< summary > < b > Follow PyTorch Lightning style guide< / b > < / summary >
The style guide is available [here ](https://pytorch-lightning.readthedocs.io/en/latest/starter/style_guide.html ).< br >
1. Be explicit in your init. Try to define all the relevant defaults so that the user doesn’ t have to guess. Provide type hints. This way your module is reusable across projects!
```python
class LitModel(LightningModule):
def __init__ (self, layer_size: int = 256, lr: float = 0.001):
```
2. Preserve the recommended method order.
```python
class LitModel(LightningModule):
2021-04-28 21:02:03 +03:00
def __init__ ():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def forward():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def training_step():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def training_step_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def training_epoch_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def validation_step():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def validation_step_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def validation_epoch_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def test_step():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def test_step_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def test_epoch_end():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def configure_optimizers():
...
2021-04-05 20:39:56 +03:00
2021-04-28 21:02:03 +03:00
def any_extra_hook():
...
2021-04-05 20:39:56 +03:00
```
< / details >
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Version control your data and models with DVC< / b > < / summary >
2021-03-15 18:55:06 +03:00
Use [DVC ](https://dvc.org ) to version control big files, like your data or trained ML models.< br >
To initialize the dvc repository:
```yaml
dvc init
```
To start tracking a file or directory, use `dvc add` :
```yaml
dvc add data/MNIST
```
DVC stores information about the added file (or a directory) in a special .dvc file named data/MNIST.dvc, a small text file with a human-readable format. This file can be easily versioned like source code with Git, as a placeholder for the original data:
```yaml
git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data"
```
2021-03-01 17:00:10 +03:00
2021-04-04 03:22:26 +03:00
< / details >
< details >
< summary > < b > Support installing project as a package< / b > < / summary >
2021-03-01 17:00:10 +03:00
2021-03-12 20:40:24 +03:00
It allows other people to easily use your modules in their own projects.
2021-03-15 18:55:06 +03:00
Change name of the `src` folder to your project name and add `setup.py` file:
```python
from setuptools import find_packages, setup
setup(
name="src", # you should change "src" to your project name
version="0.0.0",
description="Describe Your Cool Project",
author="",
author_email="",
# replace with your own github project link
2021-04-15 22:13:18 +03:00
url="https://github.com/ashleve/lightning-hydra-template",
2021-03-15 18:55:06 +03:00
install_requires=["pytorch-lightning>=1.2.0", "hydra-core>=1.0.6"],
packages=find_packages(),
)
```
2021-03-12 20:40:24 +03:00
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
2021-04-06 16:02:21 +03:00
from project_name.models.mnist_model import MNISTLitModel
from project_name.datamodules.mnist_datamodule import MNISTDataModule
2021-03-12 20:40:24 +03:00
```
2021-03-15 23:18:39 +03:00
2021-04-04 03:22:26 +03:00
< / details >
2021-04-05 20:39:56 +03:00
< br >
2021-04-27 00:06:50 +03:00
2021-04-05 20:39:56 +03:00
## Tricks
< details >
2021-04-27 00:06:50 +03:00
< summary > < b > Automatic activation of virtual environment and tab completion when entering folder< / b > < / summary >
2021-04-05 20:39:56 +03:00
2021-04-27 21:13:09 +03:00
2021-04-28 21:02:03 +03:00
Create a new file called `.autoenv` (this name is excluded from version control in `.gitignore` ). < br >
2021-04-27 21:13:09 +03:00
You can use it to automatically execute shell commands when entering folder.
To setup this automation for bash, execute the following line:
```bash
echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
```
Now you can add any commands to your `.autoenv` file, e.g. activation of virual environment and hydra tab completion:
2021-04-05 20:39:56 +03:00
```bash
# activate conda environment
conda activate myenv
# initialize hydra tab completion for bash
eval "$(python run.py -sc install=bash)"
```
2021-04-27 21:13:09 +03:00
(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
2021-04-05 20:39:56 +03:00
2021-04-27 21:13:09 +03:00
Lastly add execution previliges to your `.autoenv` file:
```
chmod +x .autoenv
2021-04-05 20:39:56 +03:00
```
2021-04-27 00:06:50 +03:00
2021-04-05 20:39:56 +03:00
**Explanation**< br >
2021-04-27 21:13:09 +03:00
The mentioned line appends your `.bashrc` file with 2 commands:
1. `autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir and has execution previligies
2. `cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal or open new terminal
2021-04-05 20:39:56 +03:00
< / details >
< / details >
2021-03-12 20:40:24 +03:00
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Accessing datamodule attributes in model< / b > < / summary >
2021-03-30 04:19:32 +03:00
2021-03-15 23:18:39 +03:00
The simplest way is to pass datamodule attribute directly to model on initialization:
```python
datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
```
2021-04-05 20:39:56 +03:00
This is not a robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).
2021-03-15 23:18:39 +03:00
A better solution is to add Omegaconf resolver to your datamodule:
```python
from omegaconf import OmegaConf
# you can place this snippet in your datamodule __init__()
resolver_name = "datamodule"
2021-04-28 21:02:03 +03:00
OmegaConf.register_resolver(
2021-03-15 23:18:39 +03:00
resolver_name,
lambda name: getattr(self, name),
use_cache=False
)
```
This way you can reference any datamodule attribute from your config like this:
```yaml
# this will get 'datamodule.some_param' field
2021-03-23 00:53:55 +03:00
some_parameter: ${datamodule: some_param}
2021-03-15 23:18:39 +03:00
```
When later accessing this field, say in your lightning model, it will get automatically resolved based on all resolvers that are registered. Remember not to access this field before datamodule is initialized. **You also need to set resolve to false in print_config() in [run.py](run.py) method or it will throw errors!**
```python
template_utils.print_config(config, resolve=False)
```
2021-04-04 03:22:26 +03:00
< / details >
2021-03-15 23:18:39 +03:00
2021-04-05 20:39:56 +03:00
<!--
2021-03-15 23:18:39 +03:00
PrettyErrors and Rich exception handling,
2021-04-04 03:22:26 +03:00
-->
< br >
2021-03-10 17:33:14 +03:00
## Other Repositories
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > Inspirations< / b > < / summary >
2021-03-10 17:33:14 +03:00
This template was inspired by:
[PyTorchLightning/deep-learninig-project-template ](https://github.com/PyTorchLightning/deep-learning-project-template ),
[drivendata/cookiecutter-data-science ](https://github.com/drivendata/cookiecutter-data-science ),
[tchaton/lightning-hydra-seed ](https://github.com/tchaton/lightning-hydra-seed ),
[Erlemar/pytorch_tempest ](https://github.com/Erlemar/pytorch_tempest ),
[lucmos/nn-template ](https://github.com/lucmos/nn-template ).
2021-04-04 03:22:26 +03:00
< / details >
< details >
< summary > < b > Useful repositories< / b > < / summary >
2021-01-13 02:53:16 +03:00
2021-03-10 17:33:14 +03:00
- [pytorch/hydra-torch ](https://github.com/pytorch/hydra-torch ) - resources for configuring PyTorch classes with Hydra,
- [romesco/hydra-lightning ](https://github.com/romesco/hydra-lightning ) - resources for configuring PyTorch Lightning classes with Hydra
2021-04-27 00:06:50 +03:00
- [lucmos/nn-template ](https://github.com/lucmos/nn-template ) - similar template
- [PyTorchLightning/lightning-transformers ](https://github.com/PyTorchLightning/lightning-transformers ) - official Lightning Transformers repo built with Hydra
2021-01-13 02:53:16 +03:00
2021-04-04 03:22:26 +03:00
< / details >
2021-03-07 04:32:10 +03:00
2021-04-04 03:22:26 +03:00
< details >
< summary > < b > List of repositories using this template< / b > < / summary >
2021-03-07 04:32:10 +03:00
2021-04-05 22:14:23 +03:00
- [ashleve/graph_classification ](https://github.com/ashleve/graph_classification ) - benchmarking graph neural network architectures on graph classification datasets (Open Graph Benchmarks and image classification from superpixels)
2021-04-07 01:00:32 +03:00
> if you'd like to share your project and add it to the list, feel free to make a PR!
2021-03-15 18:55:06 +03:00
2021-04-04 03:22:26 +03:00
< / details >
2021-03-15 18:55:06 +03:00
2021-04-27 00:06:50 +03:00
<!-- ## :star: Stargazers Over Time
[![Stargazers over time ](https://starchart.cc/ashleve/lightning-hydra-template.svg )](https://starchart.cc/ashleve/lightning-hydra-template) -->
2021-03-01 17:00:10 +03:00
< br >
< br >
< br >
2021-03-10 17:33:14 +03:00
< br >
2021-03-01 17:00:10 +03:00
2021-03-30 04:19:32 +03:00
**DELETE EVERYTHING ABOVE FOR YOUR PROJECT**
2021-03-06 21:43:48 +03:00
2021-01-13 02:53:16 +03:00
---
2021-03-06 21:43:48 +03:00
< div align = "center" >
# Your Project Name
2021-03-07 01:16:26 +03:00
2021-04-04 03:22:26 +03:00
< a href = "https://pytorch.org/get-started/locally/" > < img alt = "PyTorch" src = "https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white" > < / a >
2021-03-30 04:19:32 +03:00
< a href = "https://pytorchlightning.ai/" > < img alt = "Lightning" src = "https://img.shields.io/badge/-Lightning-792ee5" > < / a >
2021-04-04 03:22:26 +03:00
< a href = "https://hydra.cc/" > < img alt = "Config: Hydra" src = "https://img.shields.io/badge/Config-Hydra-89b8cd" > < / a >
2021-04-15 22:13:18 +03:00
< a href = "https://github.com/ashleve/lightning-hydra-template" > < img alt = "Template" src = "https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=gray" > < / a > < br >
[![Paper ](http://img.shields.io/badge/paper-arxiv.1001.2234-B31B1B.svg )](https://www.nature.com/articles/nature14539)
[![Conference ](http://img.shields.io/badge/AnyConference-year-4b44ce.svg )](https://papers.nips.cc/paper/2020)
2021-01-13 02:53:16 +03:00
< / div >
## Description
What it does
## How to run
2021-03-12 20:40:24 +03:00
Install dependencies
2021-01-26 20:13:39 +03:00
```yaml
2021-01-13 02:53:16 +03:00
# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name
2021-03-12 20:40:24 +03:00
# [OPTIONAL] create conda environment
2021-04-06 16:02:21 +03:00
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
2021-01-13 02:53:16 +03:00
# install requirements
pip install -r requirements.txt
```
2021-03-12 20:40:24 +03:00
Train model with default configuration
2021-01-26 20:13:39 +03:00
```yaml
2021-03-25 03:31:52 +03:00
# default
2021-03-15 18:55:06 +03:00
python run.py
2021-03-25 03:31:52 +03:00
# train on CPU
python run.py trainer.gpus=0
# train on GPU
python run.py trainer.gpus=1
2021-01-13 02:53:16 +03:00
```
2021-03-25 03:31:52 +03:00
Train model with chosen experiment configuration from [configs/experiment/ ](configs/experiment/ )
2021-01-26 20:13:39 +03:00
```yaml
2021-04-27 00:06:50 +03:00
python run.py experiment=experiment_name
2021-01-13 02:53:16 +03:00
```
2021-03-12 20:40:24 +03:00
You can override any parameter from command line like this
2021-01-26 20:13:39 +03:00
```yaml
2021-03-25 03:31:52 +03:00
python run.py trainer.max_epochs=20 datamodule.batch_size=64
2021-01-19 04:23:13 +03:00
```
2021-03-04 15:30:51 +03:00
< br >