diff --git a/README.md b/README.md
index bf4e99a..84e2aaf 100644
--- a/README.md
+++ b/README.md
@@ -3,27 +3,19 @@
# Lightning-Hydra-Template
-
+
-
-
A clean and scalable template to kickstart your deep learning project đâĄđĨ
Click on [Use this template](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.
-_Suggestions are always welcome!_
+*Suggestions are always welcome!*
-
-
## đ Introduction
@@ -43,26 +35,27 @@ It makes your code neatly organized and provides lots of useful features, like a
### Why Hydra?
[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.
-
-
+
## Main Ideas Of This Template
-- **Predefined Structure**: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure))
-- **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers (see [#Your Superpowers](#your-superpowers))
-- **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))
-- **Workflow**: comes down to 4 simple steps (see [#Workflow](#workflow))
-- **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) (see [#Hyperparameter Search](#hyperparameter-search))
-- **Tests**: unit tests and command based tests (see [#Tests](#tests))
-- **Extra Features**: optional utilities to make your life easier
-
-- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices))
-
+- **Predefined Structure**: clean and scalable so that work can easily be extended and replicated | [#Project Structure](#project-structure)
+- **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers | [#Your Superpowers](#your-superpowers)
+- **Reproducibility**: obtaining similar results is supported in multiple ways | [#Reproducibility](#reproducibility)
+- **Little Boilerplate**: so pipeline can be easily modified | [#How It Works](#how-it-works)
+- **Main Configuration**: main config file specifies default training configuration | [#Main Project Configuration](#main-project-configuration)
+- **Experiment Configurations**: can be composed out of smaller configs and override chosen hyperparameters | [#Experiment Configuration](#experiment-configuration)
+- **Workflow**: comes down to 4 simple steps | [#Workflow](#workflow)
+- **Experiment Tracking**: many logging frameworks can be easily integrated, like Tensorboard, MLFlow or W&B | [#Experiment Tracking](#experiment-tracking)
+- **Logs**: all logs (checkpoints, data from loggers, hparams, etc.) are stored in a convenient folder structure imposed by Hydra | [#Logs](#logs)
+- **Hyperparameter Search**: made easier with Hydra built-in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) | [#Hyperparameter Search](#hyperparameter-search)
+- **Tests**: unit tests and shell/command based tests for speeding up the development | [#Tests](#tests)
+- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility | [#Best Practices](#best-practices)
+
+
+
+
## Project Structure
@@ -119,7 +112,7 @@ The directory structure of new project looks like this:
## đ Quickstart
-```yaml
+```bash
# clone project
git clone https://github.com/ashleve/lightning-hydra-template
cd lightning-hydra-template
@@ -153,13 +146,13 @@ When running `python run.py` you should see something like this:
> Hydra allows you to easily overwrite any parameter defined in your config.
-```yaml
+```bash
python run.py trainer.max_epochs=20 model.lr=1e-4
```
> You can also add new parameters with `+` sign.
-```yaml
+```bash
python run.py +model.new_param="uwu"
```
@@ -170,7 +163,7 @@ python run.py +model.new_param="uwu"
> PyTorch Lightning makes it easy to train your models on different hardware.
-```yaml
+```bash
# train on CPU
python run.py trainer.gpus=0
@@ -192,7 +185,7 @@ python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator=ddp
Train with mixed precision
-```yaml
+```bash
# train with pytorch native automatic mixed precision (AMP)
python run.py trainer.gpus=1 +trainer.precision=16
```
@@ -203,7 +196,7 @@ python run.py trainer.gpus=1 +trainer.precision=16
Optimize large scale models on multiple GPUs with Deepspeed
-```yaml
+```bash
python run.py +trainer.
```
@@ -215,14 +208,14 @@ python run.py +trainer.
> PyTorch Lightning provides convenient integrations with most popular logging frameworks, like Tensorboard, Neptune or simple csv files. 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.
> **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
-```yaml
+```bash
# set project and entity names in `configs/logger/wandb`
wandb:
project: "your_project_name"
entity: "your_wandb_team_name"
```
-```yaml
+```bash
# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
python run.py logger=wandb
```
@@ -232,7 +225,7 @@ python run.py logger=wandb
Use different running modes
-```yaml
+```bash
# debug mode changes logging folder to `logs/debug/`
# also enables default trainer debugging options from `configs/trainer/debug.yaml`
# also sets level of all command line loggers to 'DEBUG'
@@ -250,7 +243,7 @@ python run.py mode=exp name='my_new_experiment_253'
> Experiment configurations are placed in [configs/experiment/](configs/experiment/).
-```yaml
+```bash
python run.py experiment=example_simple
```
@@ -262,7 +255,7 @@ python run.py experiment=example_simple
> 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 configurations are placed in [configs/callbacks/](configs/callbacks/).
-```yaml
+```bash
python run.py callbacks=default
```
@@ -295,7 +288,7 @@ python run.py +trainer.max_time="00:12:00:00"
Easily debug
-```yaml
+```bash
# run in debug mode
# changes logging folder to `logs/debug/...`
# enables trainer debugging options specified in `configs/trainer/debug.yaml`
@@ -346,7 +339,7 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
Create a sweep over hyperparameters
-```yaml
+```bash
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
@@ -361,7 +354,7 @@ python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
> 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/hparams_search/mnist_optuna.yaml)!
-```yaml
+```bash
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python run.py -m hparams_search=mnist_optuna experiment=example_simple
@@ -376,7 +369,7 @@ python run.py -m hparams_search=mnist_optuna experiment=example_simple
> 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/).
-```yaml
+```bash
python run.py -m 'experiment=glob(*)'
```
@@ -402,11 +395,12 @@ python run.py -m 'experiment=glob(*)'
> 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).
+
## đŗ Docker
-First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
+First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder.
@@ -422,12 +416,13 @@ To mount the project to the container use:
docker run -v $(pwd):/workspace/project --gpus all -it --rm
```
-
+
## â¤ī¸ Contributions
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!
-
+
+
## âšī¸ Guide
@@ -435,11 +430,12 @@ Have a question? Found a bug? Missing a specific feature? Ran into a problem? Fe
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)
- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/) and [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/)
-
-### How it works
+
-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:
+### How It Works
+
+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:
```yaml
_target_: src.models.mnist_model.MNISTLitModel
@@ -504,6 +500,7 @@ ignore_warnings: True
```
+
### Experiment Configuration
@@ -624,7 +621,7 @@ logger:
### Logs
**Hydra creates new working directory for every executed run.**
-By default, logs have the following structure:
+This means your working directory is different for every run, which might not be compatible with some libraries and workflows. By default, logs have the following structure:
```
â
@@ -669,7 +666,8 @@ By default, logs have the following structure:
```
You can change this structure by modifying paths in [hydra configuration](configs/mode).
-
+
+
### Experiment Tracking
@@ -678,7 +676,7 @@ PyTorch Lightning supports the most popular logging frameworks:
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
+```bash
python run.py logger=logger_name
```
@@ -687,7 +685,8 @@ You can use many of them at once (see [configs/logger/many_loggers.yaml](configs
You can also write your own logger.
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).
-
+
+
### Hyperparameter Search
@@ -757,14 +756,15 @@ hydra:
Next, you can execute it with: `python run.py -m hparams_search=mnist_optuna`
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. The `optimization_results.yaml` will be available under `logs/multirun` folder.
-
+
+
### Inference
-The following is example of loading model from checkpoint and running predictions.
+The following code is an example of loading model from checkpoint and running predictions.
-Show inference example
+Show example
```python
from PIL import Image
@@ -820,6 +820,7 @@ if __name__ == "__main__":
```
+
### Tests
@@ -827,7 +828,7 @@ if __name__ == "__main__":
Template comes with example tests implemented with pytest library.
To execute them simply run:
-```yaml
+```bash
# run all tests
pytest
@@ -838,10 +839,11 @@ pytest tests/shell/test_basic_commands.py
pytest -k "not slow"
```
-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/shell](tests/shell) folder.
+To speed up the development, you can once in a while execute tests that run a couple of quick experiments, like training 1 epoch on 25% of data, executing single train/val/test step, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some bash commands doesn't end up in throwing exceptions. You can find them implemented in [tests/shell](tests/shell) 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).
-
+You can easily modify the commands in the scripts for your use case. If 1 epoch is too much for your model, then make it run for a couple of batches instead (by using the right trainer flags).
+
+
### Callbacks
@@ -860,12 +862,13 @@ To provide examples of logging custom visualisations with callbacks only:
To try all of the callbacks at once, use:
-```yaml
+```bash
python run.py logger=wandb callbacks=wandb
```
To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).
-
+
+
### Multi-GPU Training
@@ -874,33 +877,48 @@ The most common one is DDP, which spawns separate process for each GPU and avera
You can run DDP on mnist example with 4 GPUs like this:
-```yaml
+```bash
python run.py trainer.gpus=4 +trainer.accelerator="ddp"
```
â ī¸ 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).
-
-
-
+
### Limitations
- Currently, template doesn't support k-fold cross validation, but it's possible to achieve it with Lightning Loop interface. See the [official example](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/loop_examples/kfold.py). Implementing it requires rewriting the training pipeline.
-- Pytorch Lightning might not the best choice for scalable reinforcement learning, it's probably better to use something like [Ray](https://github.com/ray-project/ray).
+- Pytorch Lightning might not be the best choice for scalable reinforcement learning, it's probably better to use something like [Ray](https://github.com/ray-project/ray).
- Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.
+- Hydra changes working directory to new logging folder for every executed run, which might not be compatible with the way some libraries work.
-
+
## Useful Tricks
@@ -1029,29 +1047,24 @@ TODO
## Best Practices
-
-
Use Miniconda for GPU environments
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.
+It makes it easier to install some dependencies, like cudatoolkit for GPU support. It also allows you to acccess your environments globally.
+
Example installation:
-```yaml
+```bash
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
-Create environment using bash script provided in the template:
+Create new conda environment:
-```yaml
-bash bash/setup_conda.sh
+```bash
+conda create -n myenv python=3.8
+conda activate myenv
```
@@ -1062,13 +1075,13 @@ bash bash/setup_conda.sh
Use pre-commit hooks to standardize code formatting of your project and save mental energy.
Simply install pre-commit package with:
-```yaml
+```bash
pip install pre-commit
```
Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
-```yaml
+```bash
pre-commit install
```
@@ -1077,7 +1090,7 @@ Currently template contains configurations of **black** (python code formatting)
To reformat all files in the project use command:
-```yaml
+```bash
pre-commit run -a
```
@@ -1091,7 +1104,7 @@ System specific variables (e.g. absolute paths to datasets) should not be under
Template contains `.env.example` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore).
You should use it for storing environment variables like this:
-```yaml
+```
MY_VAR=/home/user/my_system_path
```
@@ -1218,19 +1231,19 @@ The style guide is available [here](https://pytorch-lightning.readthedocs.io/en/
Use [DVC](https://dvc.org) to version control big files, like your data or trained ML models.
To initialize the dvc repository:
-```yaml
+```bash
dvc init
```
To start tracking a file or directory, use `dvc add`:
-```yaml
+```bash
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
+```bash
git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data"
```
@@ -1265,13 +1278,13 @@ setup(
Now your project can be installed from local files:
-```yaml
+```bash
pip install -e .
```
Or directly from git repository:
-```yaml
+```bash
pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade
```
@@ -1291,6 +1304,13 @@ It's a good practice for jupyter notebooks to be portable. Try to make them inde
-->
+
+
## Other Repositories
@@ -1380,7 +1400,7 @@ What it does
Install dependencies
-```yaml
+```bash
# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name
@@ -1398,7 +1418,7 @@ pip install -r requirements.txt
Train model with default configuration
-```yaml
+```bash
# train on CPU
python run.py trainer.gpus=0
@@ -1408,14 +1428,12 @@ python run.py trainer.gpus=1
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/)
-```yaml
+```bash
python run.py experiment=experiment_name.yaml
```
You can override any parameter from command line like this
-```yaml
+```bash
python run.py trainer.max_epochs=20 datamodule.batch_size=64
```
-
-