General documentation improvements (#193)

*add a new way for accessing datamodule attributes to the README
*general documentation improvements
This commit is contained in:
Eungbean Lee authored and GitHub committed 2021-10-25 21:58:13 +02:00
1 parent f212e617b1
commit 95d9f7a90d
1 file changed
+234 -153
+234 -153
View File
@@ -2,18 +2,18 @@
# Lightning-Hydra-Template # Lightning-Hydra-Template
<a href="https://www.python.org/"><img alt="Python" src="https://img.shields.io/badge/-Python 3.7--3.9-blue?style=for-the-badge&logo=python&logoColor=white"></a> <a href="https://www.python.org/"><img alt="Python" src="https://img.shields.io/badge/-Python 3.7--3.9-blue?style=for-the-badge&logo=python&logoColor=white"></a>
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch 1.8+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"></a> <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch 1.8+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"></a>
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning 1.3+-792ee5?style=for-the-badge&logo=pytorchlightning&logoColor=white"></a> <a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning 1.3+-792ee5?style=for-the-badge&logo=pytorchlightning&logoColor=white"></a>
<a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra 1.1-89b8cd?style=for-the-badge&labelColor=gray"></a> <a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra 1.1-89b8cd?style=for-the-badge&labelColor=gray"></a>
<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&labelColor=gray"></a> <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&labelColor=gray"></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> --> <!-- <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> -->
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br> A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository. Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.
*Suggestions are always welcome!* _Suggestions are always welcome!_
</div> </div>
<br><br> <br><br>
@@ -26,27 +26,29 @@ to your `README.md`.
--> -->
## 📌&nbsp;&nbsp;Introduction ## 📌&nbsp;&nbsp;Introduction
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). 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).
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended. > Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
**Why you should use it:** it allows you to rapidly iterate over new models/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. **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.
**Why you shouldn't use it:** Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task. **Why you shouldn't use it:** this template is not fitted to be a production environment, should be used more as a fast experimentation tool. Apart from that, Lightning and Hydra are not yet very mature, which means you might run into some bugs sooner or later. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task.
### Why PyTorch Lightning? ### Why PyTorch Lightning?
[PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research. [PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research.
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. It makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.
### Why Hydra? ### Why Hydra?
[Hydra](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. [Hydra](https://github.com/facebookresearch/hydra) is an open-source Python framework that simplifies the development of research and other complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line. It allows you to conveniently manage experiments and provides many useful plugins, like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) for hyperparameter search, or [Ray Launcher](https://hydra.cc/docs/next/plugins/ray_launcher) for running jobs on a cluster.
<br> <br>
<br> <br>
<br> <br>
## Main Ideas Of This Template ## Main Ideas Of This Template
- **Predefined Structure**: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure)) - **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)) - **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)) - **Little Boilerplate**: so pipeline can be easily modified (see [src/train.py](src/train.py))
@@ -57,13 +59,14 @@ It makes your code neatly organized and provides lots of useful features, like a
- **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))
- **Hyperparameter Search**: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) (see [#Hyperparameter Search](#hyperparameter-search)) - **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)) - **Tests**: unit tests and command based tests (see [#Tests](#tests))
- **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features)) - **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)) - **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices))
<br> <br>
## Project Structure ## Project Structure
The directory structure of new project looks like this: The directory structure of new project looks like this:
``` ```
├── bash <- Bash scripts ├── bash <- Bash scripts
│ ├── setup_conda.sh <- Setup conda environment │ ├── setup_conda.sh <- Setup conda environment
@@ -111,10 +114,11 @@ The directory structure of new project looks like this:
├── requirements.txt <- File for installing python dependencies ├── requirements.txt <- File for installing python dependencies
└── README.md └── README.md
``` ```
<br> <br>
## 🚀&nbsp;&nbsp;Quickstart ## 🚀&nbsp;&nbsp;Quickstart
```yaml ```yaml
# clone project # clone project
git clone https://github.com/ashleve/lightning-hydra-template git clone https://github.com/ashleve/lightning-hydra-template
@@ -129,6 +133,7 @@ pip install -r requirements.txt
Template contains example with MNIST classification.<br> Template contains example with MNIST classification.<br>
When running `python run.py` you should see something like this: When running `python run.py` you should see something like this:
<div align="center"> <div align="center">
![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png) ![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png)
@@ -136,27 +141,31 @@ When running `python run.py` you should see something like this:
</div> </div>
### ⚡&nbsp;&nbsp;Your Superpowers ### ⚡&nbsp;&nbsp;Your Superpowers
(click to expand) (click to expand)
<details> <details>
<summary><b>Override any config parameter from command line</b></summary> <summary><b>Override any config parameter from command line</b></summary>
> Hydra allows you to easily overwrite any parameter defined in your config. > Hydra allows you to easily overwrite any parameter defined in your config.
```yaml ```yaml
python run.py trainer.max_epochs=20 model.lr=1e-4 python run.py trainer.max_epochs=20 model.lr=1e-4
``` ```
> You can also add new parameters with `+` sign. > You can also add new parameters with `+` sign.
```yaml ```yaml
python run.py +model.new_param="uwu" python run.py +model.new_param="uwu"
``` ```
</details> </details>
<details> <details>
<summary><b>Train on CPU, GPU, multi-GPU and TPU</b></summary> <summary><b>Train on CPU, GPU, multi-GPU and TPU</b></summary>
> PyTorch Lightning makes it easy to train your models on different hardware. > PyTorch Lightning makes it easy to train your models on different hardware.
```yaml ```yaml
# train on CPU # train on CPU
python run.py trainer.gpus=0 python run.py trainer.gpus=0
@@ -176,7 +185,6 @@ python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
</details> </details>
<details> <details>
<summary><b>Train with mixed precision</b></summary> <summary><b>Train with mixed precision</b></summary>
@@ -192,12 +200,11 @@ python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
</details> </details>
<details> <details>
<summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases</b></summary> <summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases</b></summary>
> 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.<br> > 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.<br> > **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
**Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
```yaml ```yaml
# set project and entity names in `configs/logger/wandb` # set project and entity names in `configs/logger/wandb`
wandb: wandb:
@@ -212,7 +219,6 @@ python run.py logger=wandb
</details> </details>
<details> <details>
<summary><b>Use different running modes</b></summary> <summary><b>Use different running modes</b></summary>
@@ -229,34 +235,34 @@ python run.py mode=exp name='my_new_experiment_253'
</details> </details>
<details> <details>
<summary><b>Train model with chosen experiment config</b></summary> <summary><b>Train model with chosen experiment config</b></summary>
> Experiment configurations are placed in [configs/experiment/](configs/experiment/). > Experiment configurations are placed in [configs/experiment/](configs/experiment/).
```yaml ```yaml
python run.py experiment=example_simple python run.py experiment=example_simple
``` ```
</details> </details>
<details> <details>
<summary><b>Attach some callbacks to run</b></summary> <summary><b>Attach some callbacks to run</b></summary>
> Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br> > 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/). > Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
```yaml ```yaml
python run.py callbacks=default python run.py callbacks=default
``` ```
</details> </details>
<details> <details>
<summary><b>Use different tricks available in Pytorch Lightning</b></summary> <summary><b>Use different tricks available in Pytorch Lightning</b></summary>
> PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags). > PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).
```yaml ```yaml
# gradient clipping may be enabled to avoid exploding gradients # gradient clipping may be enabled to avoid exploding gradients
python run.py +trainer.gradient_clip_val=0.5 python run.py +trainer.gradient_clip_val=0.5
@@ -276,7 +282,6 @@ python run.py +trainer.max_time="00:12:00:00"
</details> </details>
<details> <details>
<summary><b>Easily debug</b></summary> <summary><b>Easily debug</b></summary>
@@ -310,19 +315,19 @@ python run.py +trainer.track_grad_norm=2
</details> </details>
<details> <details>
<summary><b>Resume training from checkpoint</b></summary> <summary><b>Resume training from checkpoint</b></summary>
> Checkpoint can be either path or URL. Path should be absolute! > Checkpoint can be either path or URL. Path should be absolute!
```yaml ```yaml
python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt" python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
``` ```
> ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release. > ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.
</details> </details>
<details> <details>
<summary><b>Create a sweep over hyperparameters</b></summary> <summary><b>Create a sweep over hyperparameters</b></summary>
@@ -331,27 +336,31 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
# each with different combination of batch_size and learning rate # 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 python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
``` ```
> ⚠️ Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
> ⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).
</details> </details>
<details> <details>
<summary><b>Create a sweep over hyperparameters with Optuna</b></summary> <summary><b>Create a sweep over hyperparameters with Optuna</b></summary>
> 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)! > 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 ```yaml
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml` # this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config # over chosen experiment config
python run.py -m hparams_search=mnist_optuna experiment=example_simple python run.py -m hparams_search=mnist_optuna experiment=example_simple
``` ```
> ⚠️ Currently this sweep is not failure resistant (if one job crashes than the whole sweep crashes). Might be supported in future Hydra release.
</details> </details>
<details> <details>
<summary><b>Execute all experiments from folder</b></summary> <summary><b>Execute all experiments from folder</b></summary>
> 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/). > 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 ```yaml
python run.py -m 'experiment=glob(*)' python run.py -m 'experiment=glob(*)'
``` ```
@@ -372,7 +381,6 @@ python run.py -m 'experiment=glob(*)'
</details> --> </details> -->
<details> <details>
<summary><b>Use Hydra tab completion</b></summary> <summary><b>Use Hydra tab completion</b></summary>
@@ -381,41 +389,44 @@ python run.py -m 'experiment=glob(*)'
</details> </details>
<br> <br>
## 🐳&nbsp;&nbsp;Docker ## 🐳&nbsp;&nbsp;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. <br> 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. <br>
The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder. The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder.
To build the container use: To build the container use:
```bash ```bash
docker build -t <project_name> . docker build -t <project_name> .
``` ```
To mount the project to the container use: To mount the project to the container use:
```bash ```bash
docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name> docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name>
``` ```
Uncomment Apex in Dockerfile for mixed-precision support. Uncomment Apex in Dockerfile for mixed-precision support.
<br><br><br> <br><br><br>
## ❤️&nbsp;&nbsp;Contributions ## ❤️&nbsp;&nbsp;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! 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!
<br><br><br><br> <br><br><br><br>
## ℹ️&nbsp;&nbsp;Guide ## ℹ️&nbsp;&nbsp;Guide
### How To Get Started ### How To Get Started
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) - 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/) - 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/)
<br> <br>
### How it works ### 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: 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:
```yaml ```yaml
_target_: src.models.mnist_model.MNISTLitModel _target_: src.models.mnist_model.MNISTLitModel
input_size: 784 input_size: 784
@@ -425,22 +436,26 @@ lin3_size: 256
output_size: 10 output_size: 10
lr: 0.001 lr: 0.001
``` ```
Using this config we can instantiate the object with the following line: Using this config we can instantiate the object with the following line:
```python ```python
model = hydra.utils.instantiate(config.model) model = hydra.utils.instantiate(config.model)
``` ```
This allows you to easily iterate over new models!<br> This allows you to easily iterate over new models!<br>
Every time you create a new one, just specify its module path and parameters in appriopriate config file. <br> Every time you create a new one, just specify its module path and parameters in appriopriate config file. <br>
The whole pipeline managing the instantiation logic is placed in [src/train.py](src/train.py). The whole pipeline managing the instantiation logic is placed in [src/train.py](src/train.py).
<br> <br>
### Main Project Configuration ### Main Project Configuration
Location: [configs/config.yaml](configs/config.yaml)<br> Location: [configs/config.yaml](configs/config.yaml)<br>
Main project config contains default training configuration.<br> Main project config contains default training configuration.<br>
It determines how config is composed when simply executing command `python run.py`.<br> It determines how config is composed when simply executing command `python run.py`.<br>
It also specifies everything that shouldn't be managed by experiment configurations. It also specifies everything that shouldn't be managed by experiment configurations.
<details> <details>
<summary><b>Show main project configuration</b></summary> <summary><b>Show main project configuration</b></summary>
@@ -458,22 +473,18 @@ defaults:
- experiment: null - experiment: null
- hparams_search: null - hparams_search: null
# path to original working directory # path to original working directory
# hydra hijacks working directory by changing it to the current log directory, # hydra hijacks working directory by changing it to the current log directory,
# so it's useful to have this path as a special variable # 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 # learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
work_dir: ${hydra:runtime.cwd} work_dir: ${hydra:runtime.cwd}
# path to folder with data # path to folder with data
data_dir: ${work_dir}/data/ data_dir: ${work_dir}/data/
# pretty print config at the start of the run using Rich library # pretty print config at the start of the run using Rich library
print_config: True print_config: True
# disable python warnings if they annoy you # disable python warnings if they annoy you
ignore_warnings: True ignore_warnings: True
``` ```
@@ -481,13 +492,14 @@ ignore_warnings: True
</details> </details>
<br> <br>
### Experiment Configuration ### Experiment Configuration
Location: [configs/experiment](configs/experiment)<br> Location: [configs/experiment](configs/experiment)<br>
You should store all your experiment configurations in this folder.<br> You should store all your experiment configurations in this folder.<br>
Experiment configurations allow you to overwrite parameters from main project configuration. Experiment configurations allow you to overwrite parameters from main project configuration.
**Simple example** **Simple example**
```yaml ```yaml
# to execute this experiment run: # to execute this experiment run:
# python run.py experiment=example_simple # python run.py experiment=example_simple
@@ -518,8 +530,8 @@ datamodule:
train_val_test_split: [55_000, 5_000, 10_000] train_val_test_split: [55_000, 5_000, 10_000]
batch_size: 64 batch_size: 64
``` ```
</details>
</details>
<details> <details>
<summary><b>Show advanced example</b></summary> <summary><b>Show advanced example</b></summary>
@@ -579,15 +591,18 @@ logger:
<br> <br>
### Workflow ### Workflow
1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example) 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) 2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
3. Write your experiment config, containing paths to your model and datamodule 3. Write your experiment config, containing paths to your model and datamodule
4. Run training with chosen experiment config: `python run.py experiment=experiment_name` 4. Run training with chosen experiment config: `python run.py experiment=experiment_name`
<br> <br>
### Logs ### Logs
Hydra creates new working directory for every executed run. <br> Hydra creates new working directory for every executed run. <br>
By default, logs have the following structure: By default, logs have the following structure:
``` ```
│ │
├── logs ├── logs
@@ -621,24 +636,26 @@ By default, logs have the following structure:
You can change this structure by modifying paths in [hydra configuration](configs/mode). You can change this structure by modifying paths in [hydra configuration](configs/mode).
<br><br> <br><br>
### Experiment Tracking ### Experiment Tracking
PyTorch Lightning supports the most popular logging frameworks:<br> PyTorch Lightning supports the most popular logging frameworks:<br>
**[Weights&Biases](https://www.wandb.com/) · [Neptune](https://neptune.ai/) · [Comet](https://www.comet.ml/) · [MLFlow](https://mlflow.org) · [Tensorboard](https://www.tensorflow.org/tensorboard/)** **[Weights&Biases](https://www.wandb.com/) · [Neptune](https://neptune.ai/) · [Comet](https://www.comet.ml/) · [MLFlow](https://mlflow.org) · [Tensorboard](https://www.tensorflow.org/tensorboard/)**
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: 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
python run.py logger=logger_name ```yaml
``` python run.py logger=logger_name
```
You can use many of them at once (see [configs/logger/many_loggers.yaml](configs/logger/many_loggers.yaml) for example).<br> 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> You can also write your own logger.<br>
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). 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).
<br><br> <br><br>
### Hyperparameter Search ### Hyperparameter Search
Defining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search](configs/hparams_search). Defining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search](configs/hparams_search).
<details> <details>
<summary><b>Show example</b></summary> <summary><b>Show example</b></summary>
@@ -646,11 +663,9 @@ Defining hyperparameter optimization is as easy as adding new config file to [co
defaults: defaults:
- override /hydra/sweeper: optuna - override /hydra/sweeper: optuna
# choose metric which will be optimized by Optuna # choose metric which will be optimized by Optuna
optimized_metric: "val/acc" optimized_metric: "val/acc"
hydra: hydra:
# here we define Optuna hyperparameter search # here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator # it optimizes for value returned from function with @hydra.main decorator
@@ -707,10 +722,10 @@ Next, you can execute it with: `python run.py -m hparams_search=mnist_optuna`<br
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. 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.
<br><br> <br><br>
### Inference ### Inference
The following is example of loading model from checkpoint and running predictions.<br> The following is example of loading model from checkpoint and running predictions.<br>
<details> <details>
<summary><b>Show inference example</b></summary> <summary><b>Show inference example</b></summary>
@@ -770,11 +785,11 @@ if __name__ == "__main__":
</details> </details>
<br> <br>
### Tests ### Tests
Template comes with example tests implemented with pytest library. <br> Template comes with example tests implemented with pytest library. <br>
To execute them simply run: To execute them simply run:
```yaml ```yaml
# run all tests # run all tests
pytest pytest
@@ -785,26 +800,29 @@ pytest tests/shell/test_basic_commands.py
# run all tests except the ones marked as slow # run all tests except the ones marked as slow
pytest -k "not slow" 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. 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.
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 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> <br><br>
### Callbacks ### Callbacks
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> 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>
To support reproducibility: To support reproducibility:
- **WatchModel** - **WatchModel**
- **UploadCodeAsArtifact** - **UploadCodeAsArtifact**
- **UploadCheckpointsAsArtifact** - **UploadCheckpointsAsArtifact**
To provide examples of logging custom visualisations with callbacks only: To provide examples of logging custom visualisations with callbacks only:
- **LogConfusionMatrix** - **LogConfusionMatrix**
- **LogF1PrecRecHeatmap** - **LogF1PrecRecHeatmap**
- **LogImagePredictions** - **LogImagePredictions**
To try all of the callbacks at once, use: To try all of the callbacks at once, use:
```yaml ```yaml
python run.py logger=wandb callbacks=wandb python run.py logger=wandb callbacks=wandb
``` ```
@@ -812,30 +830,149 @@ 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). To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).
<br><br> <br><br>
### Multi-GPU Training ### Multi-GPU Training
Lightning supports multiple ways of doing distributed training.<br> 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). 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: You can run DDP on mnist example with 4 GPUs like this:
```yaml ```yaml
python run.py trainer.gpus=4 +trainer.accelerator="ddp" 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). ⚠️ 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).
<br><br> <br><br>
### Reproducibility ### Reproducibility
To reproduce previous experiment, simply load its config from logs: To reproduce previous experiment, simply load its config from logs:
```yaml ```yaml
python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
``` ```
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections.
<br><br>
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections.
<br><br><br>
## Useful Tricks
<details>
<summary><b>Accessing datamodule attributes in model</b></summary>
1. The simplest way is to pass datamodule attribute directly to model on initialization:
```python
# ./src/train.py
datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
```
This is not a very robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).
2. If you only want to access datamodule config, you can simply pass it as an init parameter:
```python
# ./src/train.py
model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule)
```
Now you can access any datamodule config part like this:
```python
# ./src/models/my_model.py
class MyLitModel(LightningModule):
def __init__(self, dm_conf, param1, param2):
super().__init__()
batch_size = dm_conf.batch_size
```
3. If you need to access the datamodule object attributes, a little hacky solution is to add Omegaconf resolver to your datamodule:
```python
# ./src/datamodules/my_datamodule.py
from omegaconf import OmegaConf
class MyDataModule(LightningDataModule):
def __init__(self, param1, param2):
super().__init__()
self.param1 = param1
resolver_name = "datamodule"
OmegaConf.register_new_resolver(
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 return attribute 'param1' from datamodule object
param1: ${datamodule: param1}
```
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 or it will crash. **You also need to set `resolve=False` in `print_config()` in [run.py](run.py) or it will throw errors:**
```python
# ./src/run.py
utils.print_config(config, resolve=False)
```
</details>
<details>
<summary><b>Automatic activation of virtual environment and tab completion when entering folder</b></summary>
1. Create a new file called `.autoenv` (this name is excluded from version control in `.gitignore`). <br>
You can use it to automatically execute shell commands when entering folder. Add some commands to your `.autoenv` file, like in the example below:
```bash
# activate conda environment
conda activate myenv
# activate hydra tab completion for bash
eval "$(python run.py -sc install=bash)"
# enable aliases for debugging
alias debug='python run.py mode=debug'
alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0'
alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1'
alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests'
```
(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
2. To setup this automation for bash, execute the following line (it will append your `.bashrc` file):
```bash
echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
```
3. Lastly add execution previliges to your `.autoenv` file:
```
chmod +x .autoenv
```
(for safety, only `.autoenv` with previligies will be executed)
**Explanation**
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
</details>
<br>
## Best Practices ## Best Practices
<!--<details> <!--<details>
<summary><b>Use Docker</b></summary> <summary><b>Use Docker</b></summary>
@@ -849,11 +986,14 @@ Docker makes it easy to initialize the whole training environment, e.g. when you
Use miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough). 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> It makes it easier to install some dependencies, like cudatoolkit for GPU support.<br>
Example installation: Example installation:
```yaml ```yaml
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh
``` ```
Create environment using bash script provided in the template: Create environment using bash script provided in the template:
```yaml ```yaml
bash bash/setup_conda.sh bash bash/setup_conda.sh
``` ```
@@ -865,17 +1005,22 @@ bash bash/setup_conda.sh
Use pre-commit hooks to standardize code formatting of your project and save mental energy.<br> Use pre-commit hooks to standardize code formatting of your project and save mental energy.<br>
Simply install pre-commit package with: Simply install pre-commit package with:
```yaml ```yaml
pip install pre-commit pip install pre-commit
``` ```
Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml): Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
```yaml ```yaml
pre-commit install pre-commit install
``` ```
After that your code will be automatically reformatted on every new commit.<br> After that your code will be automatically reformatted on every new commit.<br>
Currently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **flake8** (python code analysis) and **prettier** (yaml formating). <br> Currently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **flake8** (python code analysis) and **prettier** (yaml formating). <br>
To reformat all files in the project use command: To reformat all files in the project use command:
```yaml ```yaml
pre-commit run -a pre-commit run -a
``` ```
@@ -889,12 +1034,15 @@ 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). 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: You should use it for storing environment variables like this:
```yaml ```yaml
MY_VAR=/home/user/my_system_path MY_VAR=/home/user/my_system_path
``` ```
All variables from `.env` are loaded in `run.py` automatically. All variables from `.env` are loaded in `run.py` automatically.
Hydra allows you to reference any env variable in `.yaml` configs like this: Hydra allows you to reference any env variable in `.yaml` configs like this:
```yaml ```yaml
path_to_data: ${oc.env:MY_VAR} path_to_data: ${oc.env:MY_VAR}
``` ```
@@ -905,9 +1053,11 @@ path_to_data: ${oc.env:MY_VAR}
<summary><b>Name metrics using '/' character</b></summary> <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: Depending on which logger you're using, it's often useful to define metric name with `/` character:
```python ```python
self.log("train/loss", loss) 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. This way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.
</details> </details>
@@ -918,6 +1068,7 @@ This way loggers will treat your metrics as belonging to different sections, whi
Use official [torchmetrics](https://github.com/PytorchLightning/metrics) library to ensure proper calculation of metrics. This is especially important for multi-GPU training! 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: For example, instead of calculating accuracy by yourself, you should use the provided `Accuracy` class like this:
```python ```python
from torchmetrics.classification.accuracy import Accuracy from torchmetrics.classification.accuracy import Accuracy
@@ -939,6 +1090,7 @@ class LitModel(LightningModule):
self.log("val/acc", acc) self.log("val/acc", acc)
... ...
``` ```
Make sure to use different metric instance for each step to ensure proper value reduction over all GPU processes. 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. 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.
@@ -951,12 +1103,14 @@ Torchmetrics provides metrics for most use cases, like F1 score or confusion mat
The style guide is available [here](https://pytorch-lightning.readthedocs.io/en/latest/starter/style_guide.html).<br> 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! 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 ```python
class LitModel(LightningModule): class LitModel(LightningModule):
def __init__(self, layer_size: int = 256, lr: float = 0.001): def __init__(self, layer_size: int = 256, lr: float = 0.001):
``` ```
2. Preserve the recommended method order. 2. Preserve the recommended method order.
```python ```python
class LitModel(LightningModule): class LitModel(LightningModule):
@@ -1007,14 +1161,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.<br> Use [DVC](https://dvc.org) to version control big files, like your data or trained ML models.<br>
To initialize the dvc repository: To initialize the dvc repository:
```yaml ```yaml
dvc init dvc init
``` ```
To start tracking a file or directory, use `dvc add`: To start tracking a file or directory, use `dvc add`:
```yaml ```yaml
dvc add data/MNIST 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: 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 ```yaml
git add data/MNIST.dvc data/.gitignore git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data" git commit -m "Add raw data"
@@ -1027,6 +1186,7 @@ git commit -m "Add raw data"
It allows other people to easily use your modules in their own projects. It allows other people to easily use your modules in their own projects.
Change name of the `src` folder to your project name and add `setup.py` file: Change name of the `src` folder to your project name and add `setup.py` file:
```python ```python
from setuptools import find_packages, setup from setuptools import find_packages, setup
@@ -1042,15 +1202,21 @@ setup(
packages=find_packages(), packages=find_packages(),
) )
``` ```
Now your project can be installed from local files: Now your project can be installed from local files:
```yaml ```yaml
pip install -e . pip install -e .
``` ```
Or directly from git repository: Or directly from git repository:
```yaml ```yaml
pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade 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: So any file can be easily imported into any other file like so:
```python ```python
from project_name.models.mnist_model import MNISTLitModel from project_name.models.mnist_model import MNISTLitModel
from project_name.datamodules.mnist_datamodule import MNISTDataModule from project_name.datamodules.mnist_datamodule import MNISTDataModule
@@ -1064,96 +1230,9 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule
It's a good practice for jupyter notebooks to be portable. Try to make them independent from src files. If you need to access external code, try to embed it inside the notebook. It's a good practice for jupyter notebooks to be portable. Try to make them independent from src files. If you need to access external code, try to embed it inside the notebook.
</details> --> </details> -->
<br> <br>
## Tricks
<details>
<summary><b>Automatic activation of virtual environment and tab completion when entering folder</b></summary>
Create a new file called `.autoenv` (this name is excluded from version control in `.gitignore`). <br>
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 virtual environment and hydra tab completion:
```bash
# activate conda environment
conda activate myenv
# activate hydra tab completion for bash
eval "$(python run.py -sc install=bash)"
# enable aliases for debugging
alias debug='python run.py mode=debug'
alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0'
alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1'
alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests'
```
(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
Lastly add execution previliges to your `.autoenv` file:
```
chmod +x .autoenv
```
**Explanation**<br>
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
</details>
</details>
<details>
<summary><b>Accessing datamodule attributes in model</b></summary>
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)
```
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
# you can place this snippet in your datamodule __init__()
resolver_name = "datamodule"
OmegaConf.register_new_resolver(
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
some_parameter: ${datamodule: some_param}
```
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
utils.print_config(config, resolve=False)
```
</details>
<!--
PrettyErrors and Rich exception handling,
-->
<br>
## Other Repositories ## Other Repositories
<details> <details>
@@ -1178,16 +1257,15 @@ This template was inspired by:
</details> </details>
<!-- ## :star:&nbsp; Stargazers Over Time <!-- ## :star:&nbsp; Stargazers Over Time
[![Stargazers over time](https://starchart.cc/ashleve/lightning-hydra-template.svg)](https://starchart.cc/ashleve/lightning-hydra-template) --> [![Stargazers over time](https://starchart.cc/ashleve/lightning-hydra-template.svg)](https://starchart.cc/ashleve/lightning-hydra-template) -->
<br> <br>
## License ## License
This project is licensed under the MIT License. This project is licensed under the MIT License.
``` ```
MIT License MIT License
@@ -1212,14 +1290,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. SOFTWARE.
``` ```
<br> <br>
<br> <br>
<br> <br>
<br> <br>
**DELETE EVERYTHING ABOVE FOR YOUR PROJECT** **DELETE EVERYTHING ABOVE FOR YOUR PROJECT**
--- ---
@@ -1238,10 +1313,13 @@ SOFTWARE.
</div> </div>
## Description ## Description
What it does What it does
## How to run ## How to run
Install dependencies Install dependencies
```yaml ```yaml
# clone project # clone project
git clone https://github.com/YourGithubName/your-repo-name git clone https://github.com/YourGithubName/your-repo-name
@@ -1255,6 +1333,7 @@ pip install -r requirements.txt
``` ```
Train model with default configuration Train model with default configuration
```yaml ```yaml
# default # default
python run.py python run.py
@@ -1267,11 +1346,13 @@ python run.py trainer.gpus=1
``` ```
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/) Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/)
```yaml ```yaml
python run.py experiment=experiment_name python run.py experiment=experiment_name
``` ```
You can override any parameter from command line like this You can override any parameter from command line like this
```yaml ```yaml
python run.py trainer.max_epochs=20 datamodule.batch_size=64 python run.py trainer.max_epochs=20 datamodule.batch_size=64
``` ```