Multiple pipelines - training and evaluation (#250)

- introduce best practice for multiple pipelines
- Implement evaluation pipeline
- allow for using relative ckpt paths
- general refactoring
- update README.md
This commit is contained in:
ashleve authored and GitHub committed 2022-02-19 19:11:11 +01:00
1 parent 02d3b65aaa
commit fe4e61edc1
24 files changed
+346 -184

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# this is example of the file that can be used for storing private and user specific environment variables, like keys or system paths
# create a file named .env (by default .env will be excluded from version control)
# the variables declared in .env are loaded in run.py automatically
# the variables declared in .env are loaded in train.py automatically
# hydra allows you to reference variables in .yaml configs with special syntax: ${oc.env:MY_VAR}
MY_VAR="/home/user/my/system/path"
+121 -123
View File
@@ -60,52 +60,55 @@ It makes your code neatly organized and provides lots of useful features, like a
The directory structure of new project looks like this:
```
├── bash <- Bash scripts
│ └── schedule.sh <- Schedule execution of many runs
├── bash <- Bash scripts
│ └── schedule.sh <- Schedule execution of many runs
│
├── configs <- Hydra configuration files
│ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs
│ ├── debug <- Debugging configs
│ ├── experiment <- Experiment configs
│ ├── hparams_search <- Hyperparameter search configs
│ ├── local <- Local configs
│ ├── log_dir <- Logging directory configs
│ ├── logger <- Logger configs
│ ├── model <- Model configs
│ ├── trainer <- Trainer configs
├── configs <- Hydra configuration files
│ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs
│ ├── debug <- Debugging configs
│ ├── experiment <- Experiment configs
│ ├── hparams_search <- Hyperparameter search configs
│ ├── local <- Local configs
│ ├── log_dir <- Logging directory configs
│ ├── logger <- Logger configs
│ ├── model <- Model configs
│ ├── trainer <- Trainer configs
│ │
│ └── config.yaml <- Main project configuration file
│ ├── test.yaml <- Main config for testing
│ └── train.yaml <- Main config for training
│
├── data <- Project data
├── data <- Project data
│
├── logs <- Logs generated by Hydra and PyTorch Lightning loggers
├── logs <- Logs generated by Hydra and PyTorch Lightning loggers
│
├── 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`.
├── 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
│ ├── helpers <- A couple of testing utilities
│ ├── shell <- Shell/command based tests
│ └── unit <- Unit tests
├── tests <- Tests of any kind
│ ├── helpers <- A couple of testing utilities
│ ├── shell <- Shell/command based tests
│ └── unit <- Unit tests
│
├── src
│ ├── callbacks <- Lightning callbacks
│ ├── datamodules <- Lightning datamodules
│ ├── models <- Lightning models
│ ├── utils <- Utility scripts
│ ├── vendor <- Third party code that cannot be installed using PIP/Conda
├── src <- Source code
│ ├── callbacks <- Lightning callbacks
│ ├── datamodules <- Lightning datamodules
│ ├── models <- Lightning models
│ ├── utils <- Utility scripts
│ ├── vendor <- Third party code that cannot be installed using PIP/Conda
│ │
│ └── train.py <- Training pipeline
│ ├── testing_pipeline.py <- Testing pipeline
│ └── training_pipeline.py <- Training pipeline
│
├── run.py <- Run pipeline with chosen experiment configuration
├── test.py <- Run testing.
├── train.py <- Run training.
│
├── .env.example <- Template of the file for storing private environment variables
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── setup.cfg <- Configurations of linters and pytest
├── requirements.txt <- File for installing python dependencies
├── .env.example <- Template of the file for storing private environment variables
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of pre-commit hooks for code formatting
├── setup.cfg <- Configuration of linters and pytest
├── requirements.txt <- File for installing python dependencies
└── README.md
```
@@ -130,7 +133,7 @@ pip install -r requirements.txt
```
Template contains example with MNIST classification.<br>
When running `python run.py` you should see something like this:
When running `python train.py` you should see something like this:
<div align="center">
@@ -146,13 +149,13 @@ When running `python run.py` you should see something like this:
> Hydra allows you to easily overwrite any parameter defined in your config.
```bash
python run.py trainer.max_epochs=20 model.lr=1e-4
python train.py trainer.max_epochs=20 model.lr=1e-4
```
> You can also add new parameters with `+` sign.
```bash
python run.py +model.new_param="uwu"
python train.py +model.new_param="uwu"
```
</details>
@@ -164,19 +167,19 @@ python run.py +model.new_param="uwu"
```bash
# train on CPU
python run.py trainer.gpus=0
python train.py trainer.gpus=0
# train on 1 GPU
python run.py trainer.gpus=1
python train.py trainer.gpus=1
# train on TPU
python run.py +trainer.tpu_cores=8
python train.py +trainer.tpu_cores=8
# train with DDP (Distributed Data Parallel) (4 GPUs)
python run.py trainer.gpus=4 +trainer.strategy=ddp
python train.py trainer.gpus=4 +trainer.strategy=ddp
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp
python train.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp
```
</details>
@@ -186,7 +189,7 @@ python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp
```bash
# train with pytorch native automatic mixed precision (AMP)
python run.py trainer.gpus=1 +trainer.precision=16
python train.py trainer.gpus=1 +trainer.precision=16
```
</details>
@@ -196,7 +199,7 @@ python run.py trainer.gpus=1 +trainer.precision=16
<summary><b>Optimize large scale models on multiple GPUs with Deepspeed</b></summary>
```bash
python run.py +trainer.
python train.py +trainer.
```
</details>
@@ -216,7 +219,7 @@ wandb:
```bash
# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
python run.py logger=wandb
python train.py logger=wandb
```
</details>
@@ -227,7 +230,7 @@ python run.py logger=wandb
> Experiment configurations are placed in [configs/experiment/](configs/experiment/).
```bash
python run.py experiment=example
python train.py experiment=example
```
</details>
@@ -239,7 +242,7 @@ python run.py experiment=example
> Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
```bash
python run.py callbacks=default
python train.py callbacks=default
```
</details>
@@ -251,19 +254,19 @@ python run.py callbacks=default
```yaml
# gradient clipping may be enabled to avoid exploding gradients
python run.py +trainer.gradient_clip_val=0.5
python train.py +trainer.gradient_clip_val=0.5
# stochastic weight averaging can make your models generalize better
python run.py +trainer.stochastic_weight_avg=true
python train.py +trainer.stochastic_weight_avg=true
# run validation loop 4 times during a training epoch
python run.py +trainer.val_check_interval=0.25
python train.py +trainer.val_check_interval=0.25
# accumulate gradients
python run.py +trainer.accumulate_grad_batches=10
python train.py +trainer.accumulate_grad_batches=10
# terminate training after 12 hours
python run.py +trainer.max_time="00:12:00:00"
python train.py +trainer.max_time="00:12:00:00"
```
</details>
@@ -279,29 +282,29 @@ python run.py +trainer.max_time="00:12:00:00"
# sets level of all command line loggers to 'DEBUG'
# enables extra trainer flags like tracking gradient norm
# enforces debug-friendly configuration
python run.py debug=default
python train.py debug=default
# runs test epoch without training
python run.py debug=test_only
python train.py debug=test_only
# run 1 train, val and test loop, using only 1 batch
python run.py +trainer.fast_dev_run=true
python train.py +trainer.fast_dev_run=true
# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
python run.py +trainer.detect_anomaly=true
python train.py +trainer.detect_anomaly=true
# print execution time profiling after training ends
python run.py +trainer.profiler="simple"
python train.py +trainer.profiler="simple"
# try overfitting to 1 batch
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
python train.py +trainer.overfit_batches=1 trainer.max_epochs=20
# use only 20% of the data
python run.py +trainer.limit_train_batches=0.2 \
python train.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
# log second gradient norm of the model
python run.py +trainer.track_grad_norm=2
python train.py +trainer.track_grad_norm=2
```
</details>
@@ -309,23 +312,34 @@ python run.py +trainer.track_grad_norm=2
<details>
<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.
```yaml
python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
python train.py trainer.resume_from_checkpoint="/path/to/ckpt/name.ckpt"
```
> ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.
</details>
<details>
<summary><b>Execute evaluation for a given checkpoint</b></summary>
> Checkpoint can be either path or URL.
```yaml
python test.py ckpt_path="/path/to/ckpt/name.ckpt"
```
</details>
<details>
<summary><b>Create a sweep over hyperparameters</b></summary>
```bash
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
```
> ⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).
@@ -340,7 +354,7 @@ python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
```bash
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python run.py -m hparams_search=mnist_optuna experiment=example_simple
python train.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.
@@ -353,7 +367,7 @@ python run.py -m hparams_search=mnist_optuna experiment=example_simple
> Hydra provides special syntax for controlling behavior of multiruns. Learn more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run). The command below executes all experiments from folder [configs/experiment/](configs/experiment/).
```bash
python run.py -m 'experiment=glob(*)'
python train.py -m 'experiment=glob(*)'
```
</details>
@@ -398,7 +412,7 @@ Have a question? Found a bug? Missing a specific feature? Have an idea for impro
### How It Works
Every run is initialized by [run.py](run.py) file. All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
```yaml
_target_: src.models.mnist_model.MNISTLitModule
@@ -416,23 +430,23 @@ Using this config we can instantiate the object with the following line:
model = hydra.utils.instantiate(config.model)
```
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>
This allows you to easily iterate over new models! Every time you create a new one, just specify its module path and parameters in appropriate config file. <br>
Switch between models and datamodules with command line arguments:
```bash
python run.py model=mnist
python train.py model=mnist
```
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/training_pipeline.py](src/training_pipeline.py).
<br>
### Main Project Configuration
Location: [configs/config.yaml](configs/config.yaml)<br>
Location: [configs/train.yaml](configs/train.yaml) <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 train.py`.<br>
<details>
<summary><b>Show main project config</b></summary>
@@ -443,7 +457,7 @@ defaults:
- datamodule: mnist.yaml
- model: mnist.yaml
- callbacks: default.yaml
- logger: null # set logger here or use command line (e.g. `python run.py logger=tensorboard`)
- logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
- trainer: default.yaml
# logging folder path
@@ -453,7 +467,7 @@ defaults:
# e.g. best hyperparameters for each combination of model and datamodule
- experiment: null
# debugging config (enable through command line, e.g. `python run.py debug=one_epoch)
# debugging config (enable through command line, e.g. `python train.py debug=one_epoch)
- debug: null
# config for hyperparameter optimization
@@ -487,7 +501,7 @@ train: True
# evaluate on test set, using best model weights achieved during training
# lightning chooses best weights based on the metric specified in checkpoint callback
test_after_training: True
test: True
# seed for random number generators in pytorch, numpy and python.random
seed: null
@@ -512,7 +526,7 @@ For example, you can use them to version control best hyperparameters for each c
```yaml
# to execute this experiment run:
# python run.py experiment=example
# python train.py experiment=example
defaults:
- override /datamodule: mnist.yaml
@@ -588,14 +602,13 @@ hydra:
1. Write your PyTorch Lightning module (see [models/mnist_module.py](src/models/mnist_module.py) for example)
2. Write your PyTorch Lightning datamodule (see [datamodules/mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
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 train.py experiment=experiment_name`
<br>
### Logs
**Hydra creates new working directory for every executed run.** <br>
This means your working directory is different for every run, which might not be compatible with some libraries and workflows. By default, logs have the following structure:
**Hydra creates new working directory for every executed run.** By default, logs have the following structure:
```
├── logs
@@ -604,6 +617,7 @@ This means your working directory is different for every run, which might not be
│ │ │ ├── experiment_name # Experiment name
│ │ │ │ ├── YYYY-MM-DD_HH-MM-SS # Datetime of the run
│ │ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ │ ├── csv # Csv logs
│ │ │ │ │ ├── wandb # Weights&Biases logs
│ │ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ │ └── ... # Any other thing saved during training
@@ -619,35 +633,26 @@ This means your working directory is different for every run, which might not be
│ │ │ └── ...
│ │ └── ...
│ │
│ └── debugs # Folder for the logs generated during debugging
| ├── runs
| │ ├── experiment_name
│ │ │ ├── YYYY-MM-DD_HH-MM-SS
│ │ │ │ └── ...
│ │ │ └── ...
│ │ └── ...
│ │
│ └── multiruns
│ ├── experiment_name
│ │ ├── YYYY-MM-DD_HH-MM-SS
│ │ │ └── ...
│ │ └── ...
│ └── ...
│ ├── evaluations # Folder for the logs generated during testing
│ │ └── ...
│ │
│ └── debugs # Folder for the logs generated during debugging
│ └── ...
```
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/log_dir).
<br>
### Experiment Tracking
PyTorch Lightning supports the most popular logging frameworks:<br>
PyTorch Lightning supports many 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/)**
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:
```bash
python run.py logger=logger_name
python train.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).
@@ -724,7 +729,7 @@ hydra:
</details>
Next, you can execute it with: `python run.py -m hparams_search=mnist_optuna`
Next, you can execute it with: `python train.py -m hparams_search=mnist_optuna`
Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file.
@@ -802,8 +807,7 @@ if __name__ == "__main__":
### Tests
Template comes with example tests implemented with pytest library. <br>
To execute them simply run:
Template comes with example tests implemented with pytest library. To execute them simply run:
```bash
# run all tests
@@ -824,7 +828,8 @@ You can easily modify the commands in the scripts for your use case. If 1 epoch
### 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)).
To support reproducibility:
- **WatchModel**
@@ -840,7 +845,7 @@ To provide examples of logging custom visualisations with callbacks only:
To try all of the callbacks at once, use:
```bash
python run.py logger=wandb callbacks=wandb
python train.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).
@@ -849,13 +854,12 @@ To see the result of all the callbacks attached, take a look at [this experiment
### 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).
Lightning supports multiple ways of doing distributed training. The most common one is DDP, which spawns separate process for each GPU and averages gradients between them. To learn about other approaches read the [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:
```bash
python run.py trainer.gpus=4 +trainer.strategy=ddp
python train.py trainer.gpus=4 +trainer.strategy=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).
@@ -898,7 +902,7 @@ What provides reproducibility:
You can load the config of previous run using:
```bash
python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
python train.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
```
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the `hydra/` part of the config, meaning logging paths will revert to default!
@@ -922,7 +926,7 @@ The `config.yaml` from `.hydra` folder contains all overriden parameters and sec
1. The simplest way is to pass datamodule attribute directly to model on initialization:
```python
# ./src/train.py
# ./src/training_pipeline.py
datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
```
@@ -932,7 +936,7 @@ The `config.yaml` from `.hydra` folder contains all overriden parameters and sec
2. If you only want to access datamodule config, you can simply pass it as an init parameter:
```python
# ./src/train.py
# ./src/training_pipeline.py
model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule, _recursive_=False)
```
@@ -974,10 +978,10 @@ The `config.yaml` from `.hydra` folder contains all overriden parameters and sec
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:**
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 [train.py](train.py) or it will throw errors:**
```python
# ./src/run.py
# ./src/train.py
utils.print_config(config, resolve=False)
```
@@ -994,13 +998,7 @@ The `config.yaml` from `.hydra` folder contains all overriden parameters and sec
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'
eval "$(python train.py -sc install=bash)"
```
(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
@@ -1102,7 +1100,7 @@ You should use it for storing environment variables like this:
MY_VAR=/home/user/my_system_path
```
All variables from `.env` are loaded in `run.py` automatically.
All variables from `.env` are loaded in `train.py` automatically.
Hydra allows you to reference any env variable in `.yaml` configs like this:
@@ -1414,20 +1412,20 @@ Train model with default configuration
```bash
# train on CPU
python run.py trainer.gpus=0
python train.py trainer.gpus=0
# train on GPU
python run.py trainer.gpus=1
python train.py trainer.gpus=1
```
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/)
```bash
python run.py experiment=experiment_name.yaml
python train.py experiment=experiment_name.yaml
```
You can override any parameter from command line like this
```bash
python run.py trainer.max_epochs=20 datamodule.batch_size=64
python train.py trainer.max_epochs=20 datamodule.batch_size=64
```
+2 -2
View File
@@ -2,6 +2,6 @@
# Shedule execution of many runs
# Run from root folder with: bash bash/schedule.sh
python run.py trainer.max_epochs=5
python train.py trainer.max_epochs=5
python run.py trainer.max_epochs=10 logger=csv
python train.py trainer.max_epochs=10 logger=csv
+1 -1
View File
@@ -3,5 +3,5 @@ _target_: src.datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir} # data_dir is specified in config.yaml
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
num_workers: 4
num_workers: 0
pin_memory: False
+5 -4
View File
@@ -1,6 +1,7 @@
# @package _global_
# default debugging setup, runs 1 full epoch
# other debugging configs can inherit from this one
defaults:
- override /log_dir: debug.yaml
@@ -8,19 +9,19 @@ defaults:
trainer:
max_epochs: 1
gpus: 0 # debuggers don't like gpus
detect_anomaly: true
track_grad_norm: 2
detect_anomaly: true # raise exception if NaN or +/-inf is detected in any tensor
track_grad_norm: 2 # track gradient norm with loggers
datamodule:
num_workers: 0 # debuggers don't like multiprocessing
pin_memory: False
pin_memory: False # disable gpu memory pin
# sets level of all command line loggers to 'DEBUG'
# https://hydra.cc/docs/tutorials/basic/running_your_app/logging/
hydra:
verbose: True
# use this to set level of only chosen command line loggers to 'DEBUG'
# use this to set level of only chosen command line loggers to 'DEBUG':
# verbose: [src.train, src.utils]
# config is already printed by hydra when `hydra/verbose: True`
+3 -3
View File
@@ -1,6 +1,6 @@
# @package _global_
# debugs by using only 1% of the data
# uses only 1% of the training data and 5% of validation/test data
defaults:
- default.yaml
@@ -8,5 +8,5 @@ defaults:
trainer:
max_epochs: 3
limit_train_batches: 0.01
limit_val_batches: 0.01
limit_test_batches: 0.01
limit_val_batches: 0.05
limit_test_batches: 0.05
+1 -1
View File
@@ -1,6 +1,6 @@
# @package _global_
# debugs with execution time profiling
# runs with execution time profiling
defaults:
- default.yaml
+1 -1
View File
@@ -1,6 +1,6 @@
# @package _global_
# debugs by running 1 train, 1 validation and 1 test step
# runs 1 train, 1 validation and 1 test step
defaults:
- default.yaml
+2 -2
View File
@@ -1,9 +1,9 @@
# @package _global_
# debugs by running only test epoch
# runs only test epoch
defaults:
- default.yaml
train: False
test_after_training: True
test: True
+1 -1
View File
@@ -1,7 +1,7 @@
# @package _global_
# to execute this experiment run:
# python run.py experiment=example
# python train.py experiment=example
defaults:
- override /datamodule: mnist.yaml
+1 -1
View File
@@ -1,7 +1,7 @@
# @package _global_
# example hyperparameter optimization of some experiment with Optuna:
# python run.py -m hparams_search=mnist_optuna experiment=example_simple hydra.sweeper.n_trials=30
# python train.py -m hparams_search=mnist_optuna experiment=example_simple hydra.sweeper.n_trials=30
defaults:
- override /hydra/sweeper: optuna
+8
View File
@@ -0,0 +1,8 @@
# @package _global_
hydra:
run:
dir: logs/evaluations/runs/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
sweep:
dir: logs/evaluations/multiruns/${name}/${now:%Y-%m-%d}_${now:%H-%M-%S}
subdir: ${hydra.job.num}
+32
View File
@@ -0,0 +1,32 @@
# @package _global_
# specify here default evaluation configuration
defaults:
- _self_
- datamodule: mnist.yaml # choose the datamodule for evaluation
- model: mnist.yaml
- callbacks: null
- logger: null
- trainer: default.yaml
- log_dir: evaluation.yaml
- experiment: null
# enable color logging
- override hydra/hydra_logging: colorlog
- override hydra/job_logging: colorlog
original_work_dir: ${hydra:runtime.cwd}
data_dir: ${original_work_dir}/data/
print_config: True
ignore_warnings: True
seed: null
name: "default"
# passing checkpoint path is necessary
ckpt_path: ???
+3 -6
View File
@@ -6,17 +6,15 @@ defaults:
- datamodule: mnist.yaml
- model: mnist.yaml
- callbacks: default.yaml
- logger: null # set logger here or use command line (e.g. `python run.py logger=tensorboard`)
- logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
- trainer: default.yaml
# logging folder path
- log_dir: default.yaml
# experiment configs allow for version control of specific configurations
# e.g. best hyperparameters for each combination of model and datamodule
- experiment: null
# debugging config (enable through command line, e.g. `python run.py debug=one_epoch)
# debugging config (enable through command line, e.g. `python train.py debug=default)
- debug: null
# config for hyperparameter optimization
@@ -32,7 +30,6 @@ defaults:
# path to original working directory
# hydra hijacks working directory by changing it to the new log directory
# so it's useful to have this path as a special variable
# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
original_work_dir: ${hydra:runtime.cwd}
@@ -50,7 +47,7 @@ train: True
# evaluate on test set, using best model weights achieved during training
# lightning chooses best weights based on the metric specified in checkpoint callback
test_after_training: True
test: True
# seed for random number generators in pytorch, numpy and python.random
seed: null
+1
View File
@@ -8,4 +8,5 @@ max_epochs: 10
# number of validation steps to execute at the beginning of the training
# num_sanity_val_steps: 0
# ckpt path
resume_from_checkpoint: null
+57
View File
@@ -0,0 +1,57 @@
import os
from typing import List
import hydra
from omegaconf import DictConfig
from pytorch_lightning import LightningDataModule, LightningModule, Trainer, seed_everything
from pytorch_lightning.loggers import LightningLoggerBase
from src import utils
log = utils.get_logger(__name__)
def test(config: DictConfig) -> None:
"""Contains minimal example of the testing pipeline.
Evaluates given checkpoint on a testset.
Args:
config (DictConfig): Configuration composed by Hydra.
Returns:
None
"""
# Set seed for random number generators in pytorch, numpy and python.random
if config.get("seed"):
seed_everything(config.seed, workers=True)
# Convert relative ckpt path to absolute path if necessary
if not os.path.isabs(config.ckpt_path):
config.ckpt_path = os.path.join(hydra.utils.get_original_cwd(), config.ckpt_path)
# Init lightning datamodule
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
# Init lightning model
log.info(f"Instantiating model <{config.model._target_}>")
model: LightningModule = hydra.utils.instantiate(config.model)
# Init lightning loggers
logger: List[LightningLoggerBase] = []
if "logger" in config:
for _, lg_conf in config.logger.items():
if "_target_" in lg_conf:
log.info(f"Instantiating logger <{lg_conf._target_}>")
logger.append(hydra.utils.instantiate(lg_conf))
# Init lightning trainer
log.info(f"Instantiating trainer <{config.trainer._target_}>")
trainer: Trainer = hydra.utils.instantiate(config.trainer, logger=logger)
# Log hyperparameters
trainer.logger.log_hyperparams({"ckpt_path": config.ckpt_path})
log.info("Starting testing!")
trainer.test(model=model, datamodule=datamodule, ckpt_path=config.ckpt_path)
+15 -5
View File
@@ -1,3 +1,4 @@
import os
from typing import List, Optional
import hydra
@@ -17,8 +18,8 @@ log = utils.get_logger(__name__)
def train(config: DictConfig) -> Optional[float]:
"""Contains training pipeline.
Instantiates all PyTorch Lightning objects from config.
"""Contains the training pipeline.
Can additionally evaluate model on a testset, using best weights achieved during training.
Args:
config (DictConfig): Configuration composed by Hydra.
@@ -31,6 +32,13 @@ def train(config: DictConfig) -> Optional[float]:
if config.get("seed"):
seed_everything(config.seed, workers=True)
# Convert relative ckpt path to absolute path if necessary
ckpt_path = config.trainer.get("resume_from_checkpoint")
if ckpt_path and not os.path.isabs(ckpt_path):
config.trainer.resume_from_checkpoint = os.path.join(
hydra.utils.get_original_cwd(), ckpt_path
)
# Init lightning datamodule
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
@@ -87,9 +95,11 @@ def train(config: DictConfig) -> Optional[float]:
score = trainer.callback_metrics.get(optimized_metric)
# Test the model
if config.get("test_after_training") and not config.trainer.get("fast_dev_run"):
if config.get("test"):
ckpt_path = "best"
if not config.get("train") or config.trainer.get("fast_dev_run"):
ckpt_path = None
log.info("Starting testing!")
ckpt_path = None if not config.get("train") else "best"
trainer.test(model=model, datamodule=datamodule, ckpt_path=ckpt_path)
# Make sure everything closed properly
@@ -104,7 +114,7 @@ def train(config: DictConfig) -> Optional[float]:
)
# Print path to best checkpoint
if not config.trainer.get("fast_dev_run"):
if not config.trainer.get("fast_dev_run") and config.trainer.get("train"):
log.info(f"Best model ckpt at {trainer.checkpoint_callback.best_model_path}")
# Return metric score for hyperparameter optimization
+13 -7
View File
@@ -34,10 +34,11 @@ log = get_logger(__name__)
def extras(config: DictConfig) -> None:
"""Optional utilities, controlled by hydra config.
"""Applies optional utilities, controlled by config flags.
Args:
config (DictConfig): Configuration composed by Hydra.
Utilities:
- Ignoring python warnings
- Rich config printing
"""
# disable python warnings if <config.ignore_warnings=True>
@@ -45,6 +46,11 @@ def extras(config: DictConfig) -> None:
log.info("Disabling python warnings! <config.ignore_warnings=True>")
warnings.filterwarnings("ignore")
# pretty print config tree using Rich library if <config.print_config=True>
if config.get("print_config"):
log.info("Printing config tree with Rich! <config.print_config=True>")
print_config(config, resolve=True)
@rank_zero_only
def print_config(
@@ -91,8 +97,8 @@ def print_config(
rich.print(tree)
with open("config_tree.log", "w") as fp:
rich.print(tree, file=fp)
with open("config_tree.log", "w") as file:
rich.print(tree, file=file)
@rank_zero_only
@@ -104,10 +110,10 @@ def log_hyperparameters(
callbacks: List[pl.Callback],
logger: List[pl.loggers.LightningLoggerBase],
) -> None:
"""Controls which hyperparameters are saved by Lightning loggers.
"""Controls which config parts are saved by Lightning loggers.
Additionaly saves:
- number of model parameters
- number of model parameters
"""
hparams = {}
+1
View File
@@ -0,0 +1 @@
# use this folder for storing third party code that cannot be installed using pip/conda
+26
View File
@@ -0,0 +1,26 @@
import dotenv
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)
@hydra.main(config_path="configs/", config_name="test.yaml")
def main(config: DictConfig):
# Imports can be nested inside @hydra.main to optimize tab completion
# https://github.com/facebookresearch/hydra/issues/934
from src import utils
from src.testing_pipeline import test
# Applies optional utilities
utils.extras(config)
# Evaluate model
return test(config)
if __name__ == "__main__":
main()
+11 -17
View File
@@ -1,3 +1,5 @@
import pytest
from tests.helpers.run_command import run_command
from tests.helpers.runif import RunIf
@@ -8,22 +10,24 @@ A couple of sanity checks to make sure the model doesn't crash with different ru
def test_fast_dev_run():
"""Test running for 1 train, val and test batch."""
command = ["run.py", "++trainer.fast_dev_run=true"]
command = ["train.py", "++trainer.fast_dev_run=true"]
run_command(command)
@pytest.mark.slow
def test_cpu():
"""Test running 1 epoch on CPU."""
command = ["run.py", "++trainer.max_epochs=1", "++trainer.gpus=0"]
command = ["train.py", "++trainer.max_epochs=1", "++trainer.gpus=0"]
run_command(command)
# use RunIf to skip execution of some tests, e.g. when no gpus are available
@RunIf(min_gpus=1)
@pytest.mark.slow
def test_gpu():
"""Test running 1 epoch on GPU."""
command = [
"run.py",
"train.py",
"++trainer.max_epochs=1",
"++trainer.gpus=1",
]
@@ -31,10 +35,11 @@ def test_gpu():
@RunIf(min_gpus=1)
@pytest.mark.slow
def test_mixed_precision():
"""Test running 1 epoch with pytorch native automatic mixed precision (AMP)."""
command = [
"run.py",
"train.py",
"++trainer.max_epochs=1",
"++trainer.gpus=1",
"++trainer.precision=16",
@@ -42,22 +47,11 @@ def test_mixed_precision():
run_command(command)
def test_limit_batches():
"""Test running 1 epoch on 25% of data."""
command = [
"run.py",
"++trainer.max_epochs=1",
"++trainer.limit_train_batches=0.25",
"++trainer.limit_val_batches=0.25",
"++trainer.limit_test_batches=0.25",
]
run_command(command)
@pytest.mark.slow
def test_double_validation_loop():
"""Test running 1 epoch with validation loop twice per epoch."""
command = [
"run.py",
"train.py",
"++trainer.max_epochs=1",
"++trainer.val_check_interval=0.5",
]
+35
View File
@@ -0,0 +1,35 @@
import pytest
from tests.helpers.run_command import run_command
@pytest.mark.slow
def test_debug_default():
command = ["train.py", "debug=default"]
run_command(command)
def test_debug_limit_batches():
command = ["train.py", "debug=limit_batches"]
run_command(command)
def test_debug_overfit():
command = ["train.py", "debug=overfit"]
run_command(command)
@pytest.mark.slow
def test_debug_profiler():
command = ["train.py", "debug=profiler"]
run_command(command)
def test_debug_step():
command = ["train.py", "debug=step"]
run_command(command)
def test_debug_test_only():
command = ["train.py", "debug=test_only"]
run_command(command)
+3 -3
View File
@@ -13,7 +13,7 @@ Use the following command to skip slow tests:
@pytest.mark.slow
def test_experiments():
"""Test running all available experiment configs for 1 epoch."""
command = ["run.py", "-m", "experiment=glob(*)", "++trainer.max_epochs=1"]
command = ["train.py", "-m", "experiment=glob(*)", "++trainer.max_epochs=1"]
run_command(command)
@@ -21,7 +21,7 @@ def test_experiments():
def test_default_sweep():
"""Test default Hydra sweeper."""
command = [
"run.py",
"train.py",
"-m",
"datamodule.batch_size=64,128",
"model.lr=0.01,0.02",
@@ -35,7 +35,7 @@ def test_default_sweep():
def test_optuna_sweep():
"""Test Optuna sweeper."""
command = [
"run.py",
"train.py",
"-m",
"hparams_search=mnist_optuna",
"trainer=default",
+2 -6
View File
@@ -7,21 +7,17 @@ from omegaconf import DictConfig
dotenv.load_dotenv(override=True)
@hydra.main(config_path="configs/", config_name="config.yaml")
@hydra.main(config_path="configs/", config_name="train.yaml")
def main(config: DictConfig):
# Imports can be nested inside @hydra.main to optimize tab completion
# https://github.com/facebookresearch/hydra/issues/934
from src.train import train
from src import utils
from src.training_pipeline import train
# Applies optional utilities
utils.extras(config)
# Pretty print config using Rich library
if config.get("print_config"):
utils.print_config(config, resolve=True)
# Train model
return train(config)