Dev (#113)
* change local lambda to normal function and move it outside of main method to enable DDP * update .pre-commit-config.yaml * update requirements.txt * reformat files * remove disabling lightning logs feature * change logging strings to enable python 3.7 * update README.md * remove double logging bug prevention since lightning fixed that
This commit is contained in:
1 parent
bc0de86874
commit
99b9c1a717
9 files changed
+146
-140
No files matched your search
+11
-3
@@ -3,7 +3,7 @@ default_language_version:
|
||||
|
||||
repos:
|
||||
|
||||
# Pre-commit-hooks
|
||||
# Pre-commit hooks
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.2.0
|
||||
hooks:
|
||||
@@ -19,7 +19,10 @@ repos:
|
||||
rev: 20.8b1
|
||||
hooks:
|
||||
- id: black
|
||||
# args: [--force-exclude, src/train.py]
|
||||
args: [
|
||||
--line-length, "99",
|
||||
# --exclude, src/train.py,
|
||||
]
|
||||
|
||||
# Isort (import sorting)
|
||||
- repo: https://github.com/PyCQA/isort
|
||||
@@ -28,5 +31,10 @@ repos:
|
||||
- id: isort
|
||||
# profiles: https://pycqa.github.io/isort/docs/configuration/profiles/
|
||||
# other flags: https://pycqa.github.io/isort/docs/configuration/options/
|
||||
args: [--profile, black, --skip, src/train.py, --skip, run.py, --filter-files]
|
||||
args: [
|
||||
--profile, black,
|
||||
--skip, src/train.py,
|
||||
--skip, run.py,
|
||||
--filter-files,
|
||||
]
|
||||
# files: "src/.*"
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
# Lightning-Hydra-Template
|
||||
|
||||
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-orange?style=for-the-badge&logo=pytorch"></a>
|
||||
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-blueviolet?style=for-the-badge"></a>
|
||||
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch-ee4c2c?style=for-the-badge"></a>
|
||||
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?style=for-the-badge"></a>
|
||||
<a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra-blue?style=for-the-badge"></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"></a>
|
||||
|
||||
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
|
||||
Click on [<kbd>Use this template</kbd>](https://github.com/hobogalaxy/lightning-hydra-template/generate) to initialize new repository.
|
||||
|
||||
*This template is work in progress. Suggestions are always welcome!*
|
||||
*This template is work in progress. Currently uses dev version of Hydra.<br>Suggestions are always welcome!*
|
||||
|
||||
</div>
|
||||
<br><br>
|
||||
@@ -20,34 +20,9 @@ Click on [<kbd>Use this template</kbd>](https://github.com/hobogalaxy/lightning-
|
||||
If you use this template please add <br>
|
||||
[](https://github.com/hobogalaxy/lightning-hydra-template) <br>
|
||||
to your `README.md`.
|
||||
<br>
|
||||
<br><br>
|
||||
|
||||
|
||||
**Contents**
|
||||
- [Introduction](#introduction)
|
||||
- [Main Ideas Of This Template](#main-ideas-of-this-template)
|
||||
- [Project Structure](#project-structure)
|
||||
- [Quickstart](#quickstart)
|
||||
- [Guide](#guide)
|
||||
- [How To Learn?](#how-to-learn)
|
||||
- [Main Project Configuration](#main-project-configuration)
|
||||
- [Experiment Configuration](#experiment-configuration)
|
||||
- [Workflow](#workflow)
|
||||
- [Logs](#logs)
|
||||
- [Experiment Tracking](#experiment-tracking)
|
||||
- [Inference](#inference)
|
||||
- [Callbacks](#callbacks)
|
||||
- [Best Practices](#best-practices)
|
||||
- [Miniconda](#miniconda)
|
||||
- [Automatic Code Formatting](#automatic-code-formatting)
|
||||
- [Environment Variables](#environment-variables)
|
||||
- [Data Version Control](#data-version-control)
|
||||
- [Installing Project As A Package](#support-installing-project-as-a-package)
|
||||
- [Tests](#tests)
|
||||
- [Tricks](#tricks)
|
||||
- [Other Repositories](#other-repositories)
|
||||
<br>
|
||||
|
||||
|
||||
## 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).
|
||||
@@ -80,6 +55,7 @@ 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))
|
||||
- Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper)
|
||||
- Best Practices: a couple of recommended tools, practices and standards (see [#Best Practices](#best-practices))
|
||||
- Extra Features: optional utilities to make your life easier (see [#Extra Features](#extra-features))
|
||||
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
|
||||
<br>
|
||||
|
||||
@@ -155,16 +131,16 @@ When running `python run.py` you should see something like this:
|
||||
</div>
|
||||
|
||||
### Your Superpowers
|
||||
##### (click to expand)
|
||||
**(click to expand)**
|
||||
|
||||
<details>
|
||||
<summary>Override any config parameter from command line</summary>
|
||||
|
||||
> *Hydra allows you to overwrite any parameter defined in your config, without writing any code!*
|
||||
> Hydra allows you to overwrite any parameter defined in your config, without writing any code!
|
||||
```yaml
|
||||
python run.py trainer.max_epochs=20 optimizer.lr=1e-4
|
||||
```
|
||||
> *You can also add new parameters with `+` sign.*
|
||||
> You can also add new parameters with `+` sign.
|
||||
```yaml
|
||||
python run.py +model.new_param="uwu"
|
||||
|
||||
@@ -176,7 +152,7 @@ python run.py +model.new_param="uwu"
|
||||
<details>
|
||||
<summary>Train on CPU, GPU, TPU or even with DDP and mixed precision</summary>
|
||||
|
||||
> *PyTorch Lightning makes it really easy to train your models on different hardware.*
|
||||
> PyTorch Lightning makes it really easy to train your models on different hardware.
|
||||
```yaml
|
||||
# train on CPU
|
||||
python run.py trainer.gpus=0
|
||||
@@ -187,11 +163,15 @@ python run.py trainer.gpus=1
|
||||
# train on TPU
|
||||
python run.py +trainer.tpu_cores=8
|
||||
|
||||
# train with DDP (Distributed Data Parallel) (4 GPUs)
|
||||
python run.py trainer.gpus=4 +trainer.accelerator='ddp'
|
||||
|
||||
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
|
||||
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
|
||||
|
||||
# train with mixed precision
|
||||
python run.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16
|
||||
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
|
||||
+trainer.amp_level="O2"
|
||||
```
|
||||
|
||||
</details>
|
||||
@@ -200,7 +180,7 @@ python run.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.preci
|
||||
<details>
|
||||
<summary>Train model with any logger available in PyTorch Lightning, like <a href="https://wandb.ai/">Weights&Biases</a></summary>
|
||||
|
||||
> *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.*
|
||||
> 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.
|
||||
```yaml
|
||||
# set project and entity names in `configs/logger/wandb`
|
||||
wandb:
|
||||
@@ -213,7 +193,7 @@ wandb:
|
||||
# link to wandb dashboard should appear in the terminal
|
||||
python run.py logger=wandb
|
||||
```
|
||||
> ***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.**
|
||||
|
||||
</details>
|
||||
|
||||
@@ -221,7 +201,7 @@ python run.py logger=wandb
|
||||
<details>
|
||||
<summary>Train model with chosen experiment config</summary>
|
||||
|
||||
> *Experiment configurations are placed in [configs/experiment/](configs/experiment/).*
|
||||
> Experiment configurations are placed in [configs/experiment/](configs/experiment/).
|
||||
```yaml
|
||||
python run.py +experiment=exp_example_simple
|
||||
```
|
||||
@@ -232,8 +212,8 @@ python run.py +experiment=exp_example_simple
|
||||
<details>
|
||||
<summary>Attach some callbacks to run</summary>
|
||||
|
||||
> *Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br>
|
||||
Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).*
|
||||
> Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br>
|
||||
Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
|
||||
```yaml
|
||||
python run.py callbacks=default_callbacks
|
||||
```
|
||||
@@ -244,7 +224,7 @@ python run.py callbacks=default_callbacks
|
||||
<details>
|
||||
<summary>Use different tricks available in Pytorch Lightning</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
|
||||
# gradient clipping may be enabled to avoid exploding gradients
|
||||
python run.py +trainer.gradient_clip_val=0.5
|
||||
@@ -259,7 +239,6 @@ python run.py +trainer.val_check_interval=0.25
|
||||
python run.py +trainer.accumulate_grad_batches=10
|
||||
```
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -295,7 +274,7 @@ python run.py +trainer.limit_train_batches=0.2 \
|
||||
# path should be absolute!
|
||||
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>
|
||||
|
||||
@@ -308,7 +287,7 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
|
||||
# each with different combination of batch_size and learning rate
|
||||
python run.py -m datamodule.batch_size=32,64,128 optimizer.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.*
|
||||
> Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -316,54 +295,47 @@ python run.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
|
||||
<details>
|
||||
<summary>Create a sweep over hyperparameters with Optuna</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/config_optuna.yaml)!
|
||||
```yaml
|
||||
# this will run hyperparameter search defined in `configs/config_optuna.yaml`
|
||||
# over chosen experiment config
|
||||
python run.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
|
||||
```
|
||||
> *Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file!*
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Execute all experiments from folder</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/).
|
||||
```yaml
|
||||
# execute all experiments from folder `configs/experiment/`
|
||||
python run.py -m '+experiment=glob(*)'
|
||||
```
|
||||
> *Hydra provides special syntax for controlling behavior of multiruns. Read more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run).*
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Execute sweep on a remote AWS cluster</summary>
|
||||
|
||||
> *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.*
|
||||
> 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.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Execute sweep on a Linux SLURM cluster</summary>
|
||||
|
||||
> *This should be achievable with simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.*
|
||||
> This should be achievable with simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.
|
||||
|
||||
</details>
|
||||
|
||||
<!--
|
||||
|
||||
<details>
|
||||
<summary>Use Hydra tab completion</summary>
|
||||
|
||||
> *Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Read more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).*
|
||||
|
||||
> *To install tab completion for bash shell, navigate to project folder and run the command below.*
|
||||
|
||||
```bash
|
||||
eval "$(python run.py -sc install=bash)"
|
||||
```
|
||||
> 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).
|
||||
|
||||
</details>
|
||||
-->
|
||||
|
||||
|
||||
<br>
|
||||
|
||||
@@ -416,10 +388,6 @@ print_config: True
|
||||
disable_warnings: False
|
||||
|
||||
|
||||
# disable lightning logs if they annoy you
|
||||
disable_lightning_logs: False
|
||||
|
||||
|
||||
# output paths for hydra logs
|
||||
hydra:
|
||||
run:
|
||||
@@ -603,11 +571,47 @@ Take a look at [inference_example.py](src/utils/inference_example.py).
|
||||
|
||||
|
||||
### Callbacks
|
||||
Template contains example callbacks for better Weights&Biases integration (see [wandb_callbacks.py](src/pl_callbacks/wandb_callbacks.py)).<br>
|
||||
To support reproducibility: *UploadCodeToWandbAsArtifact*, *UploadCheckpointsToWandbAsArtifact*, *WatchModelWithWandb*.<br>
|
||||
To provide examples of logging custom visualisations with callbacks only: *LogConfusionMatrixToWandb*, *LogF1PrecRecHeatmapToWandb*.<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/pl_callbacks/wandb_callbacks.py)).<br>
|
||||
To support reproducibility: **WatchModelWithWandb**, **UploadCodeToWandbAsArtifact**, **UploadCheckpointsToWandbAsArtifact**.<br>
|
||||
To provide examples of logging custom visualisations with callbacks only: **LogConfusionMatrixToWandb**, **LogF1PrecRecHeatmapToWandb**.<br>
|
||||
<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"
|
||||
```
|
||||
When using DDP you should remember about a couple of things:
|
||||
1. Make sure you set `datamodule.num_workers=0` and `datamodule.pin_memory=False`.
|
||||
2. 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).
|
||||
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).
|
||||
<br><br>
|
||||
|
||||
### Extra Features
|
||||
List of extra utilities available in the template:
|
||||
- loading environment variables from [.env](.env.tmp) file
|
||||
- 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
|
||||
- (TODO) resuming latest run
|
||||
|
||||
You can easily remove all of those by modifying [run.py](run.py) and [src/train.py](src/train.py).
|
||||
<br><br>
|
||||
|
||||
|
||||
### How To Speed Up Training
|
||||
(TODO)
|
||||
<br><br><br>
|
||||
|
||||
|
||||
|
||||
## Best Practices
|
||||
@@ -638,7 +642,7 @@ Currently template contains configurations of **Black** (python code formatting)
|
||||
|
||||
To format all files in the project use command:
|
||||
```yaml
|
||||
pre-commit run --all-files
|
||||
pre-commit run -a
|
||||
```
|
||||
<br>
|
||||
|
||||
@@ -712,7 +716,7 @@ from project_name.pl_datamodules.mnist_datamodule import MNISTDataModule
|
||||
```
|
||||
<br>
|
||||
|
||||
|
||||
<!--
|
||||
### Tests
|
||||
I find myself often 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. You can easily modify the commands in the script 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>
|
||||
|
||||
@@ -721,10 +725,11 @@ To execute:
|
||||
```yaml
|
||||
bash tests/smoke_tests.sh
|
||||
```
|
||||
<br><br><br>
|
||||
<br><br><br> -->
|
||||
|
||||
|
||||
## Tricks
|
||||
|
||||
### Accessing Datamodule Attributes In Model
|
||||
The simplest way is to pass datamodule attribute directly to model on initialization:
|
||||
```python
|
||||
@@ -800,7 +805,7 @@ This template was inspired by:
|
||||
|
||||
|
||||
|
||||
### DELETE EVERYTHING ABOVE FOR YOUR PROJECT
|
||||
**DELETE EVERYTHING ABOVE FOR YOUR PROJECT**
|
||||
|
||||
---
|
||||
|
||||
@@ -808,10 +813,10 @@ This template was inspired by:
|
||||
|
||||
# Your Project Name
|
||||
|
||||
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-orange?logo=pytorch"></a>
|
||||
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-blueviolet"></a>
|
||||
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c"></a>
|
||||
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5"></a>
|
||||
<a href="https://hydra.cc/"><img alt="Config: Hydra" src="https://img.shields.io/badge/Config-Hydra-blue"></a>
|
||||
[](https://github.com/hobogalaxy/lightning-hydra-template)
|
||||
<a href="https://github.com/hobogalaxy/lightning-hydra-template"><img alt="Template" src="https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=303030"></a>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
+2
-3
@@ -10,6 +10,5 @@ dependencies:
|
||||
- pip
|
||||
- notebook
|
||||
- cudatoolkit
|
||||
- pytorch
|
||||
- torchvision
|
||||
- torchaudio
|
||||
- pytorch=1.8.1
|
||||
- torchvision=0.9.1
|
||||
+6
-4
@@ -10,8 +10,8 @@ defaults:
|
||||
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
|
||||
|
||||
# enable color logging
|
||||
# - override hydra/hydra_logging: colorlog
|
||||
# - override hydra/job_logging: colorlog
|
||||
- override hydra/hydra_logging: colorlog
|
||||
- override hydra/job_logging: colorlog
|
||||
|
||||
|
||||
# path to original working directory
|
||||
@@ -20,23 +20,25 @@ defaults:
|
||||
# learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
|
||||
work_dir: ${hydra:runtime.cwd}
|
||||
|
||||
|
||||
# path to folder with data
|
||||
data_dir: ${work_dir}/data/
|
||||
|
||||
|
||||
# use `python run.py debug=true` for easy debugging!
|
||||
# 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)
|
||||
debug: False
|
||||
|
||||
|
||||
# pretty print config at the start of the run using Rich library
|
||||
print_config: True
|
||||
|
||||
|
||||
# disable python warnings if they annoy you
|
||||
disable_warnings: True
|
||||
|
||||
# disable lightning logs if they annoy you
|
||||
disable_lightning_logs: False
|
||||
|
||||
hydra:
|
||||
# output paths for hydra logs
|
||||
|
||||
+6
-6
@@ -1,20 +1,20 @@
|
||||
# --------- pytorch --------- #
|
||||
torch==1.7.1
|
||||
torchvision==0.8.2
|
||||
torch==1.8.1
|
||||
torchvision==0.9.1
|
||||
pytorch-lightning>=1.2.5
|
||||
|
||||
# --------- hydra --------- #
|
||||
hydra-core==1.1.0.dev5
|
||||
hydra_colorlog>=1.0.0
|
||||
hydra-optuna-sweeper>=0.9.0rc2
|
||||
# hydra-ray-launcher>=0.1.2
|
||||
hydra-colorlog==1.0.0
|
||||
hydra-optuna-sweeper==0.9.0rc2
|
||||
# hydra-ray-launcher==0.1.2
|
||||
# hydra-submitit-launcher==1.1.0
|
||||
|
||||
# --------- loggers --------- #
|
||||
wandb>=0.10.20
|
||||
# neptune-client
|
||||
# comet_ml
|
||||
# mlflow
|
||||
# tensorboard
|
||||
|
||||
# --------- others --------- #
|
||||
rich
|
||||
|
||||
@@ -3,6 +3,7 @@ import hydra
|
||||
from omegaconf import DictConfig
|
||||
|
||||
# load environment variables from `.env` file if it exists
|
||||
# recursively searches for `.env` in all folders starting from work dir
|
||||
dotenv.load_dotenv(override=True)
|
||||
|
||||
|
||||
@@ -16,9 +17,9 @@ def main(config: DictConfig):
|
||||
|
||||
# A couple of optional utilities:
|
||||
# - disabling python warnings
|
||||
# - disabling lightning logs
|
||||
# - easier access to debug mode
|
||||
# - forcing debug friendly configuration
|
||||
# - forcing multi-gpu friendly configuration
|
||||
# You can safely get rid of this line if you don't want those
|
||||
template_utils.extras(config)
|
||||
|
||||
|
||||
@@ -22,11 +22,22 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||
return logger
|
||||
|
||||
raise Exception(
|
||||
"You are using wandb related callback,"
|
||||
"but WandbLogger was not found for some reason..."
|
||||
"You are using wandb related callback, but WandbLogger was not found for some reason..."
|
||||
)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
self.log_freq = log_freq
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class UploadCodeToWandbAsArtifact(Callback):
|
||||
"""Upload all *.py files to wandb as an artifact, at the beginning of the run."""
|
||||
|
||||
@@ -60,26 +71,12 @@ class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
if self.upload_best_only:
|
||||
ckpts.add_file(trainer.checkpoint_callback.best_model_path)
|
||||
else:
|
||||
for path in glob.glob(
|
||||
os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True
|
||||
):
|
||||
for path in glob.glob(os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True):
|
||||
ckpts.add_file(path)
|
||||
|
||||
experiment.use_artifact(ckpts)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
self.log_freq = log_freq
|
||||
|
||||
def on_train_start(self, trainer, pl_module):
|
||||
logger = get_wandb_logger(trainer=trainer)
|
||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||
|
||||
|
||||
class LogConfusionMatrixToWandb(Callback):
|
||||
"""Generate confusion matrix every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
@@ -126,9 +123,7 @@ class LogConfusionMatrixToWandb(Callback):
|
||||
sn.heatmap(confusion_matrix, annot=True, annot_kws={"size": 8}, fmt="g")
|
||||
|
||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
||||
experiment.log(
|
||||
{f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False
|
||||
)
|
||||
experiment.log({f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False)
|
||||
|
||||
# according to wandb docs this should also work but it crashes
|
||||
# experiment.log(f{"confusion_matrix/{experiment.name}": plt})
|
||||
@@ -194,9 +189,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
)
|
||||
|
||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
||||
experiment.log(
|
||||
{f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False
|
||||
)
|
||||
experiment.log({f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False)
|
||||
|
||||
# reset plot
|
||||
plt.clf()
|
||||
|
||||
@@ -105,9 +105,7 @@ class MNISTLitModel(LightningModule):
|
||||
def training_epoch_end(self, outputs: List[Any]) -> None:
|
||||
# log best so far train acc and train loss
|
||||
self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
|
||||
self.metric_hist["train/loss"].append(
|
||||
self.trainer.callback_metrics["train/loss"]
|
||||
)
|
||||
self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"])
|
||||
self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
|
||||
self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
|
||||
|
||||
@@ -133,7 +131,5 @@ class MNISTLitModel(LightningModule):
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
|
||||
|
||||
"""
|
||||
optim = hydra.utils.instantiate(
|
||||
self.hparams.optimizer, params=self.parameters()
|
||||
)
|
||||
optim = hydra.utils.instantiate(self.hparams.optimizer, params=self.parameters())
|
||||
return optim
|
||||
+25
-23
@@ -16,48 +16,45 @@ log = logging.getLogger(__name__)
|
||||
def extras(config: DictConfig) -> None:
|
||||
"""A couple of optional utilities, controlled by main config file.
|
||||
- disabling warnings
|
||||
- disabling lightning logs
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- forcing multi-gpu friendly configuration
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
"""
|
||||
|
||||
# Enable adding new keys to config
|
||||
# enable adding new keys to config
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# Fix double logging bug (this will be removed when lightning releases patch)
|
||||
pl_logger = logging.getLogger("lightning")
|
||||
pl_logger.propagate = False
|
||||
|
||||
# [OPTIONAL] Disable python warnings if <config.disable_warnings=True>
|
||||
# disable python warnings if <config.disable_warnings=True>
|
||||
if config.get("disable_warnings"):
|
||||
log.info(f"Disabling python warnings! <{config.disable_warnings=}>")
|
||||
log.info(f"Disabling python warnings! <config.disable_warnings=True")
|
||||
warnings.filterwarnings("ignore")
|
||||
|
||||
# [OPTIONAL] Disable Lightning logs if <config.disable_lightning_logs=True>
|
||||
if config.get("disable_lightning_logs"):
|
||||
log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>")
|
||||
logging.getLogger("lightning").setLevel(logging.ERROR)
|
||||
|
||||
# [OPTIONAL] Set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
# set <config.trainer.fast_dev_run=True> if <config.debug=True>
|
||||
if config.get("debug"):
|
||||
log.info(f"Running in debug mode! <{config.debug=}>")
|
||||
log.info("Running in debug mode! <config.debug=True>")
|
||||
config.trainer.fast_dev_run = True
|
||||
|
||||
# [OPTIONAL] Force debugger friendly configuration if <config.trainer.fast_dev_run=True>
|
||||
# force debugger friendly configuration if <config.trainer.fast_dev_run=True>
|
||||
if config.trainer.get("fast_dev_run"):
|
||||
log.info(
|
||||
f"Forcing debugger friendly configuration! "
|
||||
f"<{config.trainer.fast_dev_run=}>"
|
||||
)
|
||||
log.info("Forcing debugger friendly configuration! <config.trainer.fast_dev_run=True>")
|
||||
# Debuggers don't like GPUs or multiprocessing
|
||||
if config.trainer.get("gpus"):
|
||||
config.trainer.gpus = 0
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
|
||||
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
|
||||
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>")
|
||||
# ddp doesn't like num_workers>0 or pin_memory=True
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
if config.datamodule.get("pin_memory"):
|
||||
config.datamodule.pin_memory = False
|
||||
|
||||
# Disable adding new keys to config
|
||||
# disable adding new keys to config
|
||||
OmegaConf.set_struct(config, True)
|
||||
|
||||
|
||||
@@ -99,6 +96,10 @@ def print_config(
|
||||
print(tree)
|
||||
|
||||
|
||||
def empty(*args, **kwargs):
|
||||
pass
|
||||
|
||||
|
||||
def log_hyperparameters(
|
||||
config: DictConfig,
|
||||
model: pl.LightningModule,
|
||||
@@ -127,8 +128,9 @@ def log_hyperparameters(
|
||||
# choose which parts of hydra config will be saved to loggers
|
||||
hparams["trainer"] = config["trainer"]
|
||||
hparams["model"] = config["model"]
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
hparams["datamodule"] = config["datamodule"]
|
||||
if "optimizer" in config:
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
if "callbacks" in config:
|
||||
hparams["callbacks"] = config["callbacks"]
|
||||
|
||||
@@ -156,7 +158,7 @@ def log_hyperparameters(
|
||||
|
||||
# disable logging any more hyperparameters for all loggers
|
||||
# (this is just a trick to prevent trainer from logging hparams of model, since we already did that above)
|
||||
trainer.logger.log_hyperparams = lambda params: None
|
||||
trainer.logger.log_hyperparams = empty
|
||||
|
||||
|
||||
def finish(
|
||||
|
||||
Reference in new issue
Block a user