* update readme

* remove optimizer

* make parameters more explicit

* add .autoenv

* update dockerfile

* fix paths

* update configs

* update train.py

* fix test
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-04-05 19:39:56 +02:00
1 parent 42f8acddd0
commit 2dcbdcdaf9
27 files changed
+253 -165

No files matched your search

+143 -44
View File
@@ -30,7 +30,7 @@ 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/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. 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. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task.
@@ -65,13 +65,12 @@ It makes your code neatly organized and provides lots of useful features, like a
The directory structure of new project looks like this:
```
├── configs <- Hydra configuration files
│ ├── model <- Configurations of Lightning models
│ ├── datamodule <- Configurations of Lightning datamodules
│ ├── callbacks <- Configurations of Lightning callbacks
│ ├── logger <- Configurations of Lightning loggers
│ ├── trainer <- Configurations of Lightning trainers
│ ├── optimizer <- Configurations of optimizers
│ ├── experiment <- Configurations of experiments
│ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs
│ ├── experiment <- Experiment configs
│ ├── logger <- Logger configs
│ ├── model <- Model configs
│ ├── trainer <- Trainer configs
│ │
│ ├── config.yaml <- Main project configuration file
│ └── config_optuna.yaml <- Configuration of Optuna hyperparameter search
@@ -80,30 +79,31 @@ The directory structure of new project looks like this:
│
├── logs <- Logs generated by Hydra and PyTorch Lightning loggers
│
├── notebooks <- Jupyter notebooks
├── 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`.
│
├── tests <- Tests of any kind
│
├── src
│ ├── architectures <- PyTorch model architectures
│ ├── datasets <- PyTorch datasets
│ ├── pl_callbacks <- PyTorch Lightning callbacks
│ ├── pl_datamodules <- PyTorch Lightning datamodules
│ ├── pl_models <- PyTorch Lightning models
│ ├── callbacks <- Lightning callbacks
│ ├── datamodules <- Lightning datamodules
│ ├── models <- Lightning models
│ ├── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
│ │ └── template_utils.py <- Some extra template utilities
│ │ └── template_utils.py <- Extra features for the template
│ │
│ └── train.py <- Contains training pipeline
│ └── train.py <- Training pipeline
│
├── run.py <- Run training with chosen experiment configuration
├── run.py <- Run training pipeline with chosen experiment configuration
│
├── .env <- File for storing environment variables
├── .env.template <- Template of file for storing private environment variables
├── .autoenv.template <- Template of file for automatic virtual environment setup
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── Dockerfie <- File for building docker image
├── conda_env_gpu.yaml <- File for installing conda environment
├── requirements.txt <- File for installing python dependencies
├── Dockerfie <- File for building docker image
├── LICENSE
└── README.md
```
@@ -117,8 +117,8 @@ git clone https://github.com/hobogalaxy/lightning-hydra-template
cd lightning-hydra-template
# [OPTIONAL] create conda environment
conda env create -f conda_env_gpu.yaml -n testenv
conda activate testenv
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
# install requirements
pip install -r requirements.txt
@@ -352,16 +352,41 @@ docker run --gpus all -it --rm lightning-hydra
# you can also build image by yourself using Dockerfile
docker build -t lightning-hydra .
```
<br>
If you want to use some popular official image instead, I recommed the [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags), or [pytorch/pytorch](https://hub.docker.com/r/pytorch/pytorch) (this one doesn't have installed Apex for mixed precision training).
<br><br><br>
## :information_source:&nbsp; Guide
### How To Learn?
### How To Learn
- 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/), [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)
<br>
### How it works
By design, every pipeline should be initialized by [run.py](run.py) file. [train.py](src/train.py) contains training pipeline.
You can create different pipelines for different needs (e.g. for k-fold cross validation or for testing only).
All PyTorch Lightning modules are dynamically instantiated from module paths specified in config, e.g. the model can be instantiated with the following line:
```python
model = hydra.utils.instantiate(config.model)
```
This allows to easily iterate over new models!<br>
Every time you create a new one, you only need to specify its module path and parameters in appriopriate config file:
```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
```
<br>
### Main Project Configuration
Location: [configs/config.yaml](configs/config.yaml)<br>
Main project config contains default training configuration.<br>
@@ -375,7 +400,6 @@ It also specifies everything that shouldn't be managed by experiment configurati
defaults:
- trainer: default_trainer.yaml
- model: mnist_model.yaml
- optimizer: adam.yaml
- datamodule: mnist_datamodule.yaml
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
@@ -431,7 +455,6 @@ Experiment configurations allow you to overwrite parameters from main project co
defaults:
- override /trainer: default_trainer.yaml
- override /model: mnist_model.yaml
- override /optimizer: adam.yaml
- override /datamodule: mnist_datamodule.yaml
- override /callbacks: default_callbacks.yaml
- override /logger: null
@@ -449,8 +472,6 @@ model:
lin1_size: 128
lin2_size: 256
lin3_size: 64
optimizer:
lr: 0.005
datamodule:
@@ -470,7 +491,6 @@ datamodule:
defaults:
- override /trainer: null
- override /model: null
- override /optimizer: null
- override /datamodule: null
- override /callbacks: null
- override /logger: null
@@ -490,18 +510,14 @@ trainer:
model:
_target_: src.pl_models.mnist_model.MNISTLitModel
lr: 0.001
weight_decay: 0.00005
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 128
output_size: 10
optimizer:
_target_: torch.optim.Adam
lr: 0.001
eps: 1e-08
weight_decay: 0.0005
datamodule:
_target_: src.pl_datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir}
@@ -603,7 +619,7 @@ You can run DDP on mnist example with 4 GPUs like this:
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).
<!--
<!--
<details>
<summary><b>Use metrics api objects</b></summary>
@@ -648,7 +664,7 @@ You can easily remove all of those by modifying [run.py](run.py) and [src/train.
<details>
<summary><b>Use Docker</b></summary>
(TODO)
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 Dockerfile provided in the template with your own instructions for building the container image.<br>
</details>
@@ -662,7 +678,7 @@ Example installation:
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
Docker image provided in the template already has miniconda installed.
Docker image provided in the template already comes with initialized miniconda environment.
</details>
@@ -689,11 +705,11 @@ pre-commit run -a
</details>
<details>
<summary><b>Set environment variables in .env file</b></summary>
<summary><b>Set private environment variables in .env file</b></summary>
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users.<br>
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>
Template contains `.env.tmp` file. Change its name to `.env` (this name is excluded from version control in .gitignore).
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).
You should use it for storing environment variables like this:
```bash
export MY_VAR=/home/user/my_system_path
@@ -718,6 +734,50 @@ This way loggers will treat your metrics as belonging to different sections, whi
</details>
<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):
def __init__(...):
def forward(...):
def training_step(...)
def training_step_end(...)
def training_epoch_end(...)
def validation_step(...)
def validation_step_end(...)
def validation_epoch_end(...)
def test_step(...)
def test_step_end(...)
def test_epoch_end(...)
def configure_optimizers(...)
def any_extra_hook(...)
```
</details>
<details>
<summary><b>Version control your data and models with DVC</b></summary>
@@ -774,7 +834,14 @@ from project_name.pl_datamodules.mnist_datamodule import MNISTDataModule
</details>
<!--
<details>
<summary><b>Write tests</b></summary>
(TODO)
</details>
<!--
<details>
<summary><b>Use Miniconda</b></summary>
@@ -788,6 +855,39 @@ bash tests/smoke_tests.sh
</details>
-->
<br>
## Tricks
<details>
<summary><b>Automatic activation of virtual environment and tab completion</b></summary>
Template contains `.autoenv.template` file, which serves as an example. Create a new file called `.autoenv` (this name is excluded from version control in .gitignore).
You can use it to automatically execute shell commands when entering folder:
```bash
# activate conda environment
conda activate myenv
# initialize hydra tab completion for bash
eval "$(python run.py -sc install=bash)"
```
To setup this automation for bash, execute the following line:
```bash
echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
```
**Explanation**<br>
This line appends your `.bashrc` file with 3 commands:
1. `autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir
2. `cd() { builtin cd \"\$@\" ; autoenv ; }` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal
3. `autoenv` this is just to ensure the function will also be called when directly openning terminal in any folder
</details>
</details>
<details>
<summary><b>Accessing datamodule attributes in model</b></summary>
@@ -798,8 +898,7 @@ datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
```
This is not a robust solution, since when you have many datamodules in your project, it will make them incompatible if this same parameter is not defined in each of them.
This is not a robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).
A better solution is to add Omegaconf resolver to your datamodule:
```python
from omegaconf import OmegaConf
@@ -824,7 +923,7 @@ template_utils.print_config(config, resolve=False)
</details>
<!--
<!--
PrettyErrors and Rich exception handling,
-->
<br>