Release/1.2 (#198)
* update template to pytorch 1.10+ and lightning 1.5+ * add experiment mode to all experiment configs and implement special logging paths for experiment mode * add `MaxMetric` to model, for computation of best so far validation accuracy * add RichProgressBar to default callbacks * get rid of trick for preventing auto hparam logging, since lightning now supports it with `self.save_hyperparameters(logger=False)` * add `self.save_hyperparameters()` to datamodule since lightinng now supports it * deprecate Apex support * deprecate bash script for conda setup * change `terminate_on_nan` debug option to `detect_anomaly` for compatibility with lightning v1.5 * specify model and datamodule during `trainer.test()`, for compatibility with lightning v1.5 * remove `configs/trainer/all_params.yaml` * make hyperparameter optimization compatible with lightning v1.5 * general documentation improvements
This commit is contained in:
1 parent
6159c413f2
commit
9468ef91c5
29 files changed
+278
-330
No files matched your search
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
# 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+-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.10+-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.5+-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>
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ This template tries to be as general as possible - you can easily delete any unw
|
|||||||
|
|
||||||
**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:** 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 you shouldn't use it:** this template is not fitted to be a production environment, should be used more as a fast experimentation tool. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task. See [#Limitations](#limitations) for more.
|
||||||
|
|
||||||
### Why PyTorch Lightning?
|
### Why PyTorch Lightning?
|
||||||
|
|
||||||
@@ -60,6 +60,7 @@ It makes your code neatly organized and provides lots of useful features, like a
|
|||||||
- **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
|
- **Extra Features**: optional utilities to make your life easier
|
||||||
|
<!-- - **Reproducibility**: ? -->
|
||||||
- **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>
|
||||||
|
|
||||||
@@ -69,7 +70,6 @@ The directory structure of new project looks like this:
|
|||||||
|
|
||||||
```
|
```
|
||||||
├── bash <- Bash scripts
|
├── bash <- Bash scripts
|
||||||
│ ├── setup_conda.sh <- Setup conda environment
|
|
||||||
│ └── schedule.sh <- Schedule execution of many runs
|
│ └── schedule.sh <- Schedule execution of many runs
|
||||||
│
|
│
|
||||||
├── configs <- Hydra configuration files
|
├── configs <- Hydra configuration files
|
||||||
@@ -77,8 +77,8 @@ The directory structure of new project looks like this:
|
|||||||
│ ├── datamodule <- Datamodule configs
|
│ ├── datamodule <- Datamodule configs
|
||||||
│ ├── experiment <- Experiment configs
|
│ ├── experiment <- Experiment configs
|
||||||
│ ├── hparams_search <- Hyperparameter search configs
|
│ ├── hparams_search <- Hyperparameter search configs
|
||||||
│ ├── mode <- Running mode configs
|
|
||||||
│ ├── logger <- Logger configs
|
│ ├── logger <- Logger configs
|
||||||
|
│ ├── mode <- Running mode configs
|
||||||
│ ├── model <- Model configs
|
│ ├── model <- Model configs
|
||||||
│ ├── trainer <- Trainer configs
|
│ ├── trainer <- Trainer configs
|
||||||
│ │
|
│ │
|
||||||
@@ -125,7 +125,11 @@ git clone https://github.com/ashleve/lightning-hydra-template
|
|||||||
cd lightning-hydra-template
|
cd lightning-hydra-template
|
||||||
|
|
||||||
# [OPTIONAL] create conda environment
|
# [OPTIONAL] create conda environment
|
||||||
bash bash/setup_conda.sh
|
conda create -n myenv python=3.8
|
||||||
|
conda activate myenv
|
||||||
|
|
||||||
|
# install pytorch according to instructions
|
||||||
|
# https://pytorch.org/get-started/
|
||||||
|
|
||||||
# install requirements
|
# install requirements
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
@@ -177,10 +181,10 @@ python run.py trainer.gpus=1
|
|||||||
python run.py +trainer.tpu_cores=8
|
python run.py +trainer.tpu_cores=8
|
||||||
|
|
||||||
# train with DDP (Distributed Data Parallel) (4 GPUs)
|
# train with DDP (Distributed Data Parallel) (4 GPUs)
|
||||||
python run.py trainer.gpus=4 +trainer.accelerator='ddp'
|
python run.py trainer.gpus=4 +trainer.accelerator=ddp
|
||||||
|
|
||||||
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
|
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
|
||||||
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
|
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator=ddp
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
@@ -189,19 +193,25 @@ python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
|
|||||||
<summary><b>Train with mixed precision</b></summary>
|
<summary><b>Train with mixed precision</b></summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# train with mixed precision (Apex level O1)
|
# train with pytorch native automatic mixed precision (AMP)
|
||||||
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
|
python run.py trainer.gpus=1 +trainer.precision=16
|
||||||
+trainer.amp_level="O1"
|
|
||||||
|
|
||||||
# train with mixed precision (Apex level O2)
|
|
||||||
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
|
|
||||||
+trainer.amp_level="O2"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
<!-- deepspeed support still in beta
|
||||||
<details>
|
<details>
|
||||||
<summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases</b></summary>
|
<summary><b>Optimize large scale models on multiple GPUs with Deepspeed</b></summary>
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
python run.py +trainer.
|
||||||
|
```
|
||||||
|
|
||||||
|
</details>
|
||||||
|
-->
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases or Tensorboard</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> > **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
|
> 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.**
|
||||||
|
|
||||||
@@ -229,7 +239,7 @@ python run.py logger=wandb
|
|||||||
python run.py mode=debug
|
python run.py mode=debug
|
||||||
|
|
||||||
# experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/`
|
# experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/`
|
||||||
# name is also used by experiment loggers (like tensorboard or wandb)
|
# name is also used by loggers
|
||||||
python run.py mode=exp name='my_new_experiment_253'
|
python run.py mode=exp name='my_new_experiment_253'
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -286,19 +296,24 @@ python run.py +trainer.max_time="00:12:00:00"
|
|||||||
<summary><b>Easily debug</b></summary>
|
<summary><b>Easily debug</b></summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
|
# run in debug mode
|
||||||
|
# changes logging folder to `logs/debug/...`
|
||||||
|
# enables trainer debugging options specified in `configs/trainer/debug.yaml`
|
||||||
|
# sets level of all command line loggers to 'DEBUG'
|
||||||
|
python run.py mode=debug
|
||||||
|
|
||||||
|
# enable trainer debugging options specified in `configs/trainer/debug.yaml`
|
||||||
|
python run.py trainer=debug
|
||||||
|
|
||||||
# run 1 train, val and test loop, using only 1 batch
|
# run 1 train, val and test loop, using only 1 batch
|
||||||
python run.py +trainer.fast_dev_run=true
|
python run.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
|
||||||
|
|
||||||
# print full weight summary of all PyTorch modules
|
# print full weight summary of all PyTorch modules
|
||||||
python run.py trainer.weights_summary="full"
|
python run.py trainer.weights_summary="full"
|
||||||
|
|
||||||
# raise exception, if any of the parameters or the loss are NaN or +/-inf
|
|
||||||
python run.py +trainer.terminate_on_nan=true
|
|
||||||
|
|
||||||
# quick debug with all the previous options enabled
|
|
||||||
# (this is also enabled when using `python run.py mode=debug`)
|
|
||||||
python run.py trainer=debug
|
|
||||||
|
|
||||||
# print execution time profiling after training ends
|
# print execution time profiling after training ends
|
||||||
python run.py +trainer.profiler="simple"
|
python run.py +trainer.profiler="simple"
|
||||||
|
|
||||||
@@ -407,8 +422,7 @@ To mount the project to the container use:
|
|||||||
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.
|
<br><br>
|
||||||
<br><br><br>
|
|
||||||
|
|
||||||
## ❤️ Contributions
|
## ❤️ Contributions
|
||||||
|
|
||||||
@@ -476,7 +490,7 @@ defaults:
|
|||||||
# 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
|
# 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
|
||||||
@@ -505,6 +519,7 @@ Experiment configurations allow you to overwrite parameters from main project co
|
|||||||
# python run.py experiment=example_simple
|
# python run.py experiment=example_simple
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
|
- override /mode: exp.yaml
|
||||||
- override /trainer: default.yaml
|
- override /trainer: default.yaml
|
||||||
- override /model: mnist_model.yaml
|
- override /model: mnist_model.yaml
|
||||||
- override /datamodule: mnist_datamodule.yaml
|
- override /datamodule: mnist_datamodule.yaml
|
||||||
@@ -514,6 +529,9 @@ defaults:
|
|||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
|
|
||||||
|
# name of the run determines folder name in logs and is accessed by loggers
|
||||||
|
name: "example_simple"
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
@@ -541,6 +559,7 @@ datamodule:
|
|||||||
# python run.py experiment=example_full
|
# python run.py experiment=example_full
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
|
- override /mode: exp.yaml
|
||||||
- override /trainer: null
|
- override /trainer: null
|
||||||
- override /model: null
|
- override /model: null
|
||||||
- override /datamodule: null
|
- override /datamodule: null
|
||||||
@@ -551,6 +570,8 @@ defaults:
|
|||||||
# instead we define all modules and their paths directly in this config,
|
# instead we define all modules and their paths directly in this config,
|
||||||
# so everything is stored in one place
|
# so everything is stored in one place
|
||||||
|
|
||||||
|
name: "example_full"
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
@@ -582,7 +603,8 @@ logger:
|
|||||||
wandb:
|
wandb:
|
||||||
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||||
project: "lightning-hydra-template"
|
project: "lightning-hydra-template"
|
||||||
tags: ["best_model", "uwu"]
|
name: ${name}
|
||||||
|
tags: ["best_model", "mnist"]
|
||||||
notes: "Description of this model."
|
notes: "Description of this model."
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -596,35 +618,48 @@ logger:
|
|||||||
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
|
||||||
│ ├── runs # Folder for logs generated from single runs
|
│ ├── experiments # Folder for logs generated by experiments
|
||||||
│ │ ├── 2021-02-15 # Date of executing run
|
│ │ ├── experiment_name # Name of the experiment
|
||||||
│ │ │ ├── 16-50-49 # Hour of executing run
|
│ │ │ ├── 2021-02-15_16-50-49 # Date of execution
|
||||||
│ │ │ │ ├── .hydra # Hydra logs
|
│ │ │ │ ├── .hydra # Hydra logs
|
||||||
│ │ │ │ ├── wandb # Weights&Biases logs
|
│ │ │ │ ├── wandb # Weights&Biases logs
|
||||||
│ │ │ │ ├── checkpoints # Training checkpoints
|
│ │ │ │ ├── checkpoints # Training checkpoints
|
||||||
│ │ │ │ └── ... # Any other thing saved during training
|
│ │ │ │ └── ... # Any other thing saved during training
|
||||||
|
│ │ │ └── ...
|
||||||
|
│ │ ├── ...
|
||||||
|
│ │ └── ...
|
||||||
|
│ │
|
||||||
|
│ ├── debugs # Folder for logs generated during debugging
|
||||||
|
│ │ ├── 2021-02-15
|
||||||
|
│ │ │ ├── 16-50-49
|
||||||
|
│ │ │ └── ...
|
||||||
|
│ │ ├── ...
|
||||||
|
│ │ └── ...
|
||||||
|
│ │
|
||||||
|
│ ├── runs # Folder for logs generated by normal runs
|
||||||
|
│ │ ├── 2021-02-15
|
||||||
|
│ │ │ ├── 16-50-49
|
||||||
|
│ │ │ │ └── ...
|
||||||
│ │ │ ├── ...
|
│ │ │ ├── ...
|
||||||
│ │ │ └── ...
|
│ │ │ └── ...
|
||||||
│ │ ├── ...
|
│ │ ├── ...
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
│ │
|
│ │
|
||||||
│ └── multiruns # Folder for logs generated from multiruns (sweeps)
|
│ └── multiruns # Folder for logs generated by multiruns (sweeps)
|
||||||
│ ├── 2021-02-15_16-50-49 # Date and hour of executing sweep
|
│ ├── 2021-02-15_16-50-49
|
||||||
│ │ ├── 0 # Job number
|
│ │ ├── 0
|
||||||
│ │ │ ├── .hydra # Hydra logs
|
│ │ │ └── ...
|
||||||
│ │ │ ├── wandb # Weights&Biases logs
|
|
||||||
│ │ │ ├── checkpoints # Training checkpoints
|
|
||||||
│ │ │ └── ... # Any other thing saved during training
|
|
||||||
│ │ ├── 1
|
│ │ ├── 1
|
||||||
│ │ ├── 2
|
│ │ ├── 2
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
@@ -647,8 +682,10 @@ These tools help you keep track of hyperparameters and output metrics and allow
|
|||||||
python run.py logger=logger_name
|
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).
|
||||||
You can also write your own logger.<br>
|
|
||||||
|
You can also write your own logger.
|
||||||
|
|
||||||
Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs [here](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging) or take a look at [MNIST example](src/models/mnist_model.py).
|
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>
|
||||||
|
|
||||||
@@ -664,7 +701,7 @@ 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_best"
|
||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
# here we define Optuna hyperparameter search
|
# here we define Optuna hyperparameter search
|
||||||
@@ -844,6 +881,7 @@ 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:
|
||||||
@@ -854,6 +892,15 @@ python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
|
|||||||
|
|
||||||
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections.
|
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections.
|
||||||
<br><br><br>
|
<br><br><br>
|
||||||
|
-->
|
||||||
|
|
||||||
|
### Limitations
|
||||||
|
|
||||||
|
- Currently, template doesn't support k-fold cross validation, but it's possible to achieve it with Lightning Loop interface. See the [official example](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/loop_examples/kfold.py). Implementing it requires rewriting the training pipeline.
|
||||||
|
- Pytorch Lightning might not the best choice for scalable reinforcement learning, it's probably better to use something like [Ray](https://github.com/ray-project/ray).
|
||||||
|
- Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.
|
||||||
|
|
||||||
|
<br><br>
|
||||||
|
|
||||||
## Useful Tricks
|
## Useful Tricks
|
||||||
|
|
||||||
@@ -969,6 +1016,15 @@ The mentioned line appends your `.bashrc` file with 2 commands:
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
<!--
|
||||||
|
<details>
|
||||||
|
<summary><b>Making sweeps failure resistant</b></summary>
|
||||||
|
|
||||||
|
TODO
|
||||||
|
|
||||||
|
</details>
|
||||||
|
-->
|
||||||
|
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
## Best Practices
|
## Best Practices
|
||||||
@@ -1190,15 +1246,19 @@ 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
|
||||||
|
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="src", # you should change "src" to your project name
|
name="src", # change "src" folder name to your project name
|
||||||
version="0.0.0",
|
version="0.0.0",
|
||||||
description="Describe Your Cool Project",
|
description="Describe Your Cool Project",
|
||||||
author="",
|
author="...",
|
||||||
author_email="",
|
author_email="...",
|
||||||
# replace with your own github project link
|
url="https://github.com/ashleve/lightning-hydra-template", # replace with your own github project link
|
||||||
url="https://github.com/ashleve/lightning-hydra-template",
|
install_requires=[
|
||||||
install_requires=["pytorch-lightning>=1.2.0", "hydra-core>=1.0.6"],
|
"pytorch>=1.10.0",
|
||||||
|
"pytorch-lightning>=1.4.0",
|
||||||
|
"hydra-core>=1.1.0",
|
||||||
|
],
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
)
|
)
|
||||||
```
|
```
|
||||||
@@ -1326,7 +1386,11 @@ git clone https://github.com/YourGithubName/your-repo-name
|
|||||||
cd your-repo-name
|
cd your-repo-name
|
||||||
|
|
||||||
# [OPTIONAL] create conda environment
|
# [OPTIONAL] create conda environment
|
||||||
bash bash/setup_conda.sh
|
conda create -n myenv python=3.8
|
||||||
|
conda activate myenv
|
||||||
|
|
||||||
|
# install pytorch according to instructions
|
||||||
|
# https://pytorch.org/get-started/
|
||||||
|
|
||||||
# install requirements
|
# install requirements
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
@@ -1335,9 +1399,6 @@ pip install -r requirements.txt
|
|||||||
Train model with default configuration
|
Train model with default configuration
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# default
|
|
||||||
python run.py
|
|
||||||
|
|
||||||
# train on CPU
|
# train on CPU
|
||||||
python run.py trainer.gpus=0
|
python run.py trainer.gpus=0
|
||||||
|
|
||||||
@@ -1348,7 +1409,7 @@ 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.yaml
|
||||||
```
|
```
|
||||||
|
|
||||||
You can override any parameter from command line like this
|
You can override any parameter from command line like this
|
||||||
|
|||||||
+1
-3
@@ -4,6 +4,4 @@
|
|||||||
|
|
||||||
python run.py trainer.max_epochs=5
|
python run.py trainer.max_epochs=5
|
||||||
|
|
||||||
python run.py trainer.max_epochs=5 experiment=example_simple
|
python run.py trainer.max_epochs=10 logger=csv
|
||||||
|
|
||||||
python run.py trainer.max_epochs=5 experiment=example_full
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#!/bin/bash
|
|
||||||
|
|
||||||
|
|
||||||
# Check if conda is installed
|
|
||||||
if ! command -v conda &> /dev/null
|
|
||||||
then
|
|
||||||
echo "The 'conda' command could not be found. Exiting..."
|
|
||||||
exit
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
# Configure env
|
|
||||||
read -rp "Enter conda environment name: " env_name
|
|
||||||
read -rp "Enter python version (recommended '3.8') " python_version
|
|
||||||
read -rp "Enter cuda version ('10.2', '11.1' or 'none' for CPU only): " cuda_version
|
|
||||||
|
|
||||||
|
|
||||||
# Create env
|
|
||||||
conda create -y -n "$env_name" python="$python_version"
|
|
||||||
|
|
||||||
|
|
||||||
# Install pytorch + cuda
|
|
||||||
if [ "$cuda_version" == "none" ]; then
|
|
||||||
conda install -n "$env_name" -y pytorch torchvision torchaudio cpuonly -c pytorch
|
|
||||||
elif [ "$cuda_version" == "10.2" ]; then
|
|
||||||
conda install -n "$env_name" pytorch torchvision torchaudio cudatoolkit=$cuda_version -c pytorch
|
|
||||||
elif [ "$cuda_version" == "11.1" ]; then
|
|
||||||
conda install -n "$env_name" pytorch torchvision torchaudio cudatoolkit=$cuda_version -c pytorch -c nvidia
|
|
||||||
else
|
|
||||||
echo "Incorrect cuda version. Exiting..."
|
|
||||||
exit
|
|
||||||
fi
|
|
||||||
|
|
||||||
|
|
||||||
# Final message
|
|
||||||
echo "======================================="
|
|
||||||
echo "To activate this environment use:"
|
|
||||||
echo "conda activate $env_name"
|
|
||||||
echo "======================================="
|
|
||||||
echo -e "\a"
|
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
model_checkpoint:
|
model_checkpoint:
|
||||||
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
||||||
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # "max" means higher metric value is better, can be also "min"
|
||||||
save_top_k: 1 # save k best models (determined by above metric)
|
save_top_k: 1 # save k best models (determined by above metric)
|
||||||
save_last: True # additionaly always save model from last epoch
|
save_last: True # additionaly always save model from last epoch
|
||||||
verbose: False
|
verbose: False
|
||||||
@@ -12,6 +12,9 @@ model_checkpoint:
|
|||||||
early_stopping:
|
early_stopping:
|
||||||
_target_: pytorch_lightning.callbacks.EarlyStopping
|
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||||
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # "max" means higher metric value is better, can be also "min"
|
||||||
patience: 100 # how many validation epochs of not improving until training stops
|
patience: 100 # how many validation epochs of not improving until training stops
|
||||||
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
|
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
|
||||||
|
|
||||||
|
rich_progress_bar:
|
||||||
|
_target_: pytorch_lightning.callbacks.RichProgressBar
|
||||||
+4
-3
@@ -33,12 +33,13 @@ print_config: True
|
|||||||
# disable python warnings if they annoy you
|
# disable python warnings if they annoy you
|
||||||
ignore_warnings: True
|
ignore_warnings: True
|
||||||
|
|
||||||
# check performance on test set, using the best model achieved during training
|
# evaluate on test set, using best model weights achieved during training
|
||||||
# lightning chooses best model based on metric specified in checkpoint callback
|
# lightning chooses best weights based on metric specified in checkpoint callback
|
||||||
test_after_training: True
|
test_after_training: True
|
||||||
|
|
||||||
# seed for random number generators in pytorch, numpy and python.random
|
# seed for random number generators in pytorch, numpy and python.random
|
||||||
seed: null
|
seed: null
|
||||||
|
|
||||||
# name of the run, accessed by loggers
|
# name of the run is accessed by loggers
|
||||||
|
# should be used along with experiment mode
|
||||||
name: null
|
name: null
|
||||||
@@ -4,7 +4,8 @@
|
|||||||
# python run.py experiment=example_full.yaml
|
# python run.py experiment=example_full.yaml
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
|
- override /mode: exp.yaml
|
||||||
|
- override /trainer: null
|
||||||
- override /model: null
|
- override /model: null
|
||||||
- override /datamodule: null
|
- override /datamodule: null
|
||||||
- override /callbacks: null
|
- override /callbacks: null
|
||||||
@@ -14,6 +15,10 @@ defaults:
|
|||||||
# instead we define all modules and their paths directly in this config,
|
# instead we define all modules and their paths directly in this config,
|
||||||
# so everything is stored in one place
|
# so everything is stored in one place
|
||||||
|
|
||||||
|
# name of the run determines folder name in logs
|
||||||
|
# it's also accessed by loggers
|
||||||
|
name: "example_full"
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
@@ -23,18 +28,18 @@ trainer:
|
|||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
accumulate_grad_batches: 2
|
accumulate_grad_batches: 2
|
||||||
weights_summary: null
|
weights_summary: "full"
|
||||||
# resume_from_checkpoint: ${work_dir}/last.ckpt
|
num_sanity_val_steps: 0
|
||||||
|
|
||||||
model:
|
model:
|
||||||
_target_: src.models.mnist_model.MNISTLitModel
|
_target_: src.models.mnist_model.MNISTLitModel
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00005
|
|
||||||
input_size: 784
|
input_size: 784
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
output_size: 10
|
output_size: 10
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.0005
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
@@ -48,22 +53,24 @@ callbacks:
|
|||||||
model_checkpoint:
|
model_checkpoint:
|
||||||
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
_target_: pytorch_lightning.callbacks.ModelCheckpoint
|
||||||
monitor: "val/acc"
|
monitor: "val/acc"
|
||||||
save_top_k: 2
|
|
||||||
save_last: True
|
|
||||||
mode: "max"
|
mode: "max"
|
||||||
|
save_top_k: 1
|
||||||
|
save_last: True
|
||||||
|
verbose: False
|
||||||
dirpath: "checkpoints/"
|
dirpath: "checkpoints/"
|
||||||
filename: "sample-mnist-{epoch:02d}"
|
filename: "epoch_{epoch:03d}"
|
||||||
|
auto_insert_metric_name: False
|
||||||
early_stopping:
|
early_stopping:
|
||||||
_target_: pytorch_lightning.callbacks.EarlyStopping
|
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||||
monitor: "val/acc"
|
monitor: "val/acc"
|
||||||
patience: 10
|
|
||||||
mode: "max"
|
mode: "max"
|
||||||
|
patience: 5
|
||||||
|
min_delta: 0
|
||||||
|
rich_progress_bar:
|
||||||
|
_target_: pytorch_lightning.callbacks.RichProgressBar
|
||||||
|
|
||||||
logger:
|
logger:
|
||||||
wandb:
|
wandb:
|
||||||
tags: ["best_model", "uwu"]
|
name: ${name}_${now:%Y-%m-%d_%H-%M-%S}
|
||||||
|
tags: ["best_model", "mnist"]
|
||||||
notes: "Description of this model."
|
notes: "Description of this model."
|
||||||
neptune:
|
|
||||||
tags: ["best_model"]
|
|
||||||
csv_logger:
|
|
||||||
save_dir: "."
|
|
||||||
@@ -4,6 +4,7 @@
|
|||||||
# python run.py experiment=example_simple.yaml
|
# python run.py experiment=example_simple.yaml
|
||||||
|
|
||||||
defaults:
|
defaults:
|
||||||
|
- override /mode: exp.yaml
|
||||||
- override /trainer: default.yaml
|
- override /trainer: default.yaml
|
||||||
- override /model: mnist_model.yaml
|
- override /model: mnist_model.yaml
|
||||||
- override /datamodule: mnist_datamodule.yaml
|
- override /datamodule: mnist_datamodule.yaml
|
||||||
@@ -13,6 +14,10 @@ defaults:
|
|||||||
# all parameters below will be merged with parameters from default configurations set above
|
# all parameters below will be merged with parameters from default configurations set above
|
||||||
# this allows you to overwrite only specified parameters
|
# this allows you to overwrite only specified parameters
|
||||||
|
|
||||||
|
# name of the run determines folder name in logs
|
||||||
|
# it's also accessed by loggers
|
||||||
|
name: "example_simple"
|
||||||
|
|
||||||
seed: 12345
|
seed: 12345
|
||||||
|
|
||||||
trainer:
|
trainer:
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
# @package _global_
|
# @package _global_
|
||||||
|
|
||||||
# example hyperparameter optimization of some experiment with Optuna:
|
# example hyperparameter optimization of some experiment with Optuna:
|
||||||
# python run.py -m hparams_search=mnist_optuna experiment=example_simple
|
|
||||||
# python run.py -m hparams_search=mnist_optuna experiment=example_simple hydra.sweeper.n_trials=30
|
# python run.py -m hparams_search=mnist_optuna experiment=example_simple hydra.sweeper.n_trials=30
|
||||||
|
|
||||||
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_best"
|
||||||
|
|
||||||
hydra:
|
hydra:
|
||||||
# here we define Optuna hyperparameter search
|
# here we define Optuna hyperparameter search
|
||||||
|
|||||||
@@ -5,5 +5,5 @@ defaults:
|
|||||||
- csv.yaml
|
- csv.yaml
|
||||||
# - mlflow.yaml
|
# - mlflow.yaml
|
||||||
# - neptune.yaml
|
# - neptune.yaml
|
||||||
# - tensorboard.yaml
|
- tensorboard.yaml
|
||||||
- wandb.yaml
|
- wandb.yaml
|
||||||
@@ -3,7 +3,7 @@
|
|||||||
tensorboard:
|
tensorboard:
|
||||||
_target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger
|
_target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger
|
||||||
save_dir: "tensorboard/"
|
save_dir: "tensorboard/"
|
||||||
name: "default"
|
name: null
|
||||||
version: ${name}
|
version: ${name}
|
||||||
log_graph: False
|
log_graph: False
|
||||||
default_hp_metric: True
|
default_hp_metric: True
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ wandb:
|
|||||||
save_dir: "."
|
save_dir: "."
|
||||||
offline: False # set True to store all logs only locally
|
offline: False # set True to store all logs only locally
|
||||||
id: null # pass correct id to resume experiment!
|
id: null # pass correct id to resume experiment!
|
||||||
# entity: "" # set to name of your wandb team or just remove it
|
# entity: "" # set to name of your wandb team
|
||||||
log_model: False
|
log_model: False
|
||||||
prefix: ""
|
prefix: ""
|
||||||
job_type: "train"
|
job_type: "train"
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ hydra:
|
|||||||
verbose: True
|
verbose: True
|
||||||
|
|
||||||
# https://hydra.cc/docs/tutorials/basic/running_your_app/logging/
|
# https://hydra.cc/docs/tutorials/basic/running_your_app/logging/
|
||||||
# sets 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.utils]
|
# verbose: [src.train, src.utils.utils]
|
||||||
|
|
||||||
# sets output paths for all file logs to 'logs/debug/'
|
# sets output paths for all file logs to 'logs/debug/'
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ name: ???
|
|||||||
hydra:
|
hydra:
|
||||||
# sets output paths for all file logs to `logs/experiment/name'
|
# sets output paths for all file logs to `logs/experiment/name'
|
||||||
run:
|
run:
|
||||||
dir: logs/experiments/${name}
|
dir: logs/experiments/${name}/${now:%Y-%m-%d_%H-%M-%S}
|
||||||
sweep:
|
sweep:
|
||||||
dir: logs/experiments/${name}
|
dir: logs/experiments/${name}/multirun_${now:%Y-%m-%d_%H-%M-%S}
|
||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
_target_: pytorch_lightning.Trainer
|
|
||||||
|
|
||||||
# default values for all trainer parameters
|
|
||||||
checkpoint_callback: True
|
|
||||||
default_root_dir: null
|
|
||||||
gradient_clip_val: 0.0
|
|
||||||
process_position: 0
|
|
||||||
num_nodes: 1
|
|
||||||
num_processes: 1
|
|
||||||
gpus: null
|
|
||||||
auto_select_gpus: False
|
|
||||||
tpu_cores: null
|
|
||||||
log_gpu_memory: null
|
|
||||||
progress_bar_refresh_rate: 1
|
|
||||||
overfit_batches: 0.0
|
|
||||||
track_grad_norm: -1
|
|
||||||
check_val_every_n_epoch: 1
|
|
||||||
fast_dev_run: False
|
|
||||||
accumulate_grad_batches: 1
|
|
||||||
max_epochs: 1
|
|
||||||
min_epochs: 1
|
|
||||||
max_steps: null
|
|
||||||
min_steps: null
|
|
||||||
limit_train_batches: 1.0
|
|
||||||
limit_val_batches: 1.0
|
|
||||||
limit_test_batches: 1.0
|
|
||||||
val_check_interval: 1.0
|
|
||||||
flush_logs_every_n_steps: 100
|
|
||||||
log_every_n_steps: 50
|
|
||||||
accelerator: null
|
|
||||||
sync_batchnorm: False
|
|
||||||
precision: 32
|
|
||||||
weights_summary: "top"
|
|
||||||
weights_save_path: null
|
|
||||||
num_sanity_val_steps: 2
|
|
||||||
truncated_bptt_steps: null
|
|
||||||
resume_from_checkpoint: null
|
|
||||||
profiler: null
|
|
||||||
benchmark: False
|
|
||||||
deterministic: False
|
|
||||||
reload_dataloaders_every_epoch: False
|
|
||||||
auto_lr_find: False
|
|
||||||
replace_sampler_ddp: True
|
|
||||||
terminate_on_nan: False
|
|
||||||
auto_scale_batch_size: False
|
|
||||||
prepare_data_per_node: True
|
|
||||||
plugins: null
|
|
||||||
amp_backend: "native"
|
|
||||||
amp_level: "O2"
|
|
||||||
move_metrics_to_cpu: False
|
|
||||||
@@ -13,10 +13,9 @@ profiler: null
|
|||||||
|
|
||||||
# debugs
|
# debugs
|
||||||
fast_dev_run: true
|
fast_dev_run: true
|
||||||
num_sanity_val_steps: 2
|
|
||||||
overfit_batches: 0
|
overfit_batches: 0
|
||||||
limit_train_batches: 1.0
|
limit_train_batches: 1.0
|
||||||
limit_val_batches: 1.0
|
limit_val_batches: 1.0
|
||||||
limit_test_batches: 1.0
|
limit_test_batches: 1.0
|
||||||
track_grad_norm: -1
|
track_grad_norm: -1
|
||||||
terminate_on_nan: true
|
detect_anomaly: true
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
_target_: pytorch_lightning.Trainer
|
_target_: pytorch_lightning.Trainer
|
||||||
|
|
||||||
# set `1` to train on GPU, `0` to train on CPU only
|
|
||||||
gpus: 0
|
gpus: 0
|
||||||
|
|
||||||
min_epochs: 1
|
min_epochs: 1
|
||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
|
|
||||||
weights_summary: null
|
|
||||||
progress_bar_refresh_rate: 5
|
progress_bar_refresh_rate: 5
|
||||||
resume_from_checkpoint: null
|
resume_from_checkpoint: null
|
||||||
|
weights_summary: "full"
|
||||||
|
num_sanity_val_steps: 0
|
||||||
+4
-3
@@ -1,7 +1,8 @@
|
|||||||
# --------- pytorch --------- #
|
# --------- pytorch --------- #
|
||||||
torch>=1.8.1
|
torch>=1.10.0
|
||||||
torchvision>=0.9.1
|
torchvision>=0.11.0
|
||||||
pytorch-lightning>=1.3.8
|
pytorch-lightning>=1.4.0
|
||||||
|
torchmetrics>=0.6.0
|
||||||
|
|
||||||
# --------- hydra --------- #
|
# --------- hydra --------- #
|
||||||
hydra-core==1.1.0
|
hydra-core==1.1.0
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ dotenv.load_dotenv(override=True)
|
|||||||
@hydra.main(config_path="configs/", config_name="config.yaml")
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
def main(config: DictConfig):
|
def main(config: DictConfig):
|
||||||
|
|
||||||
# Imports should be nested inside @hydra.main to optimize tab completion
|
# Imports can be nested inside @hydra.main to optimize tab completion
|
||||||
# Read more here: https://github.com/facebookresearch/hydra/issues/934
|
# https://github.com/facebookresearch/hydra/issues/934
|
||||||
from src.train import train
|
from src.train import train
|
||||||
from src.utils import utils
|
from src.utils import utils
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,3 @@
|
|||||||
[metadata]
|
|
||||||
project_name = ...
|
|
||||||
author = ...
|
|
||||||
contact = ...
|
|
||||||
license_file = LICENSE
|
|
||||||
description_file = README.md
|
|
||||||
project_template = https://github.com/ashleve/lightning-hydra-template
|
|
||||||
|
|
||||||
|
|
||||||
[isort]
|
[isort]
|
||||||
line_length = 99
|
line_length = 99
|
||||||
profile = black
|
profile = black
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ class WatchModel(Callback):
|
|||||||
@rank_zero_only
|
@rank_zero_only
|
||||||
def on_train_start(self, trainer, pl_module):
|
def on_train_start(self, trainer, pl_module):
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
logger = get_wandb_logger(trainer=trainer)
|
||||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq, log_graph=True)
|
||||||
|
|
||||||
|
|
||||||
class UploadCodeAsArtifact(Callback):
|
class UploadCodeAsArtifact(Callback):
|
||||||
@@ -69,22 +69,22 @@ class UploadCodeAsArtifact(Callback):
|
|||||||
code = wandb.Artifact("project-source", type="code")
|
code = wandb.Artifact("project-source", type="code")
|
||||||
|
|
||||||
if self.use_git:
|
if self.use_git:
|
||||||
# get .git folder
|
# get .git folder path
|
||||||
# https://alexwlchan.net/2020/11/a-python-function-to-ignore-a-path-with-git-info-exclude/
|
|
||||||
git_dir_path = Path(
|
git_dir_path = Path(
|
||||||
subprocess.check_output(["git", "rev-parse", "--git-dir"]).strip().decode("utf8")
|
subprocess.check_output(["git", "rev-parse", "--git-dir"]).strip().decode("utf8")
|
||||||
).resolve()
|
).resolve()
|
||||||
|
|
||||||
for path in Path(self.code_dir).resolve().rglob("*"):
|
for path in Path(self.code_dir).resolve().rglob("*"):
|
||||||
if (
|
|
||||||
path.is_file()
|
# don't upload files ignored by git
|
||||||
# ignore files in .git
|
# https://alexwlchan.net/2020/11/a-python-function-to-ignore-a-path-with-git-info-exclude/
|
||||||
and not str(path).startswith(str(git_dir_path)) # noqa: W503
|
command = ["git", "check-ignore", "-q", str(path)]
|
||||||
# ignore files ignored by git
|
not_ignored = subprocess.run(command).returncode == 1
|
||||||
and ( # noqa: W503
|
|
||||||
subprocess.run(["git", "check-ignore", "-q", str(path)]).returncode == 1
|
# don't upload files from .git folder
|
||||||
)
|
not_git = not str(path).startswith(str(git_dir_path))
|
||||||
):
|
|
||||||
|
if path.is_file() and not_git and not_ignored:
|
||||||
code.add_file(str(path), name=str(path.relative_to(self.code_dir)))
|
code.add_file(str(path), name=str(path.relative_to(self.code_dir)))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -35,12 +35,11 @@ class MNISTDataModule(LightningDataModule):
|
|||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir
|
# this line allows to access init params with 'self.hparams' attribute
|
||||||
self.train_val_test_split = train_val_test_split
|
# it also ensures init params will be stored in ckpt
|
||||||
self.batch_size = batch_size
|
self.save_hyperparameters(logger=False)
|
||||||
self.num_workers = num_workers
|
|
||||||
self.pin_memory = pin_memory
|
|
||||||
|
|
||||||
|
# data transformations
|
||||||
self.transforms = transforms.Compose(
|
self.transforms = transforms.Compose(
|
||||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||||
)
|
)
|
||||||
@@ -59,44 +58,48 @@ class MNISTDataModule(LightningDataModule):
|
|||||||
def prepare_data(self):
|
def prepare_data(self):
|
||||||
"""Download data if needed. This method is called only from a single GPU.
|
"""Download data if needed. This method is called only from a single GPU.
|
||||||
Do not use it to assign state (self.x = y)."""
|
Do not use it to assign state (self.x = y)."""
|
||||||
MNIST(self.data_dir, train=True, download=True)
|
MNIST(self.hparams.data_dir, train=True, download=True)
|
||||||
MNIST(self.data_dir, train=False, download=True)
|
MNIST(self.hparams.data_dir, train=False, download=True)
|
||||||
|
|
||||||
def setup(self, stage: Optional[str] = None):
|
def setup(self, stage: Optional[str] = None):
|
||||||
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
|
"""Load data. Set variables: `self.data_train`, `self.data_val`, `self.data_test`.
|
||||||
This method is called by lightning separately when using `trainer.fit()` and `trainer.test()`!
|
This method is called by lightning twice for `trainer.fit()` and `trainer.test()`, so be careful if you do a random split!
|
||||||
The `stage` can be used to differentiate whether the `setup()` is called before trainer.fit()` or `trainer.test()`."""
|
The `stage` can be used to differentiate whether it's called before trainer.fit()` or `trainer.test()`."""
|
||||||
if not self.data_train or not self.data_val or not self.data_test:
|
|
||||||
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
|
# load datasets only if they're not loaded already
|
||||||
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
|
if not self.data_train and not self.data_val and not self.data_test:
|
||||||
|
trainset = MNIST(self.hparams.data_dir, train=True, transform=self.transforms)
|
||||||
|
testset = MNIST(self.hparams.data_dir, train=False, transform=self.transforms)
|
||||||
dataset = ConcatDataset(datasets=[trainset, testset])
|
dataset = ConcatDataset(datasets=[trainset, testset])
|
||||||
self.data_train, self.data_val, self.data_test = random_split(
|
self.data_train, self.data_val, self.data_test = random_split(
|
||||||
dataset, self.train_val_test_split, generator=torch.Generator().manual_seed(42)
|
dataset=dataset,
|
||||||
|
lengths=self.hparams.train_val_test_split,
|
||||||
|
generator=torch.Generator().manual_seed(42),
|
||||||
)
|
)
|
||||||
|
|
||||||
def train_dataloader(self):
|
def train_dataloader(self):
|
||||||
return DataLoader(
|
return DataLoader(
|
||||||
dataset=self.data_train,
|
dataset=self.data_train,
|
||||||
batch_size=self.batch_size,
|
batch_size=self.hparams.batch_size,
|
||||||
num_workers=self.num_workers,
|
num_workers=self.hparams.num_workers,
|
||||||
pin_memory=self.pin_memory,
|
pin_memory=self.hparams.pin_memory,
|
||||||
shuffle=True,
|
shuffle=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
def val_dataloader(self):
|
def val_dataloader(self):
|
||||||
return DataLoader(
|
return DataLoader(
|
||||||
dataset=self.data_val,
|
dataset=self.data_val,
|
||||||
batch_size=self.batch_size,
|
batch_size=self.hparams.batch_size,
|
||||||
num_workers=self.num_workers,
|
num_workers=self.hparams.num_workers,
|
||||||
pin_memory=self.pin_memory,
|
pin_memory=self.hparams.pin_memory,
|
||||||
shuffle=False,
|
shuffle=False,
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_dataloader(self):
|
def test_dataloader(self):
|
||||||
return DataLoader(
|
return DataLoader(
|
||||||
dataset=self.data_test,
|
dataset=self.data_test,
|
||||||
batch_size=self.batch_size,
|
batch_size=self.hparams.batch_size,
|
||||||
num_workers=self.num_workers,
|
num_workers=self.hparams.num_workers,
|
||||||
pin_memory=self.pin_memory,
|
pin_memory=self.hparams.pin_memory,
|
||||||
shuffle=False,
|
shuffle=False,
|
||||||
)
|
)
|
||||||
+21
-12
@@ -2,6 +2,7 @@ from typing import Any, List
|
|||||||
|
|
||||||
import torch
|
import torch
|
||||||
from pytorch_lightning import LightningModule
|
from pytorch_lightning import LightningModule
|
||||||
|
from torchmetrics import MaxMetric
|
||||||
from torchmetrics.classification.accuracy import Accuracy
|
from torchmetrics.classification.accuracy import Accuracy
|
||||||
|
|
||||||
from src.models.modules.simple_dense_net import SimpleDenseNet
|
from src.models.modules.simple_dense_net import SimpleDenseNet
|
||||||
@@ -34,9 +35,9 @@ class MNISTLitModel(LightningModule):
|
|||||||
):
|
):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
# this line ensures params passed to LightningModule will be saved to ckpt
|
# this line allows to access init params with 'self.hparams' attribute
|
||||||
# it also allows to access params with 'self.hparams' attribute
|
# it also ensures init params will be stored in ckpt
|
||||||
self.save_hyperparameters()
|
self.save_hyperparameters(logger=False)
|
||||||
|
|
||||||
self.model = SimpleDenseNet(hparams=self.hparams)
|
self.model = SimpleDenseNet(hparams=self.hparams)
|
||||||
|
|
||||||
@@ -45,9 +46,12 @@ class MNISTLitModel(LightningModule):
|
|||||||
|
|
||||||
# use separate metric instance for train, val and test step
|
# use separate metric instance for train, val and test step
|
||||||
# to ensure a proper reduction over the epoch
|
# to ensure a proper reduction over the epoch
|
||||||
self.train_accuracy = Accuracy()
|
self.train_acc = Accuracy()
|
||||||
self.val_accuracy = Accuracy()
|
self.val_acc = Accuracy()
|
||||||
self.test_accuracy = Accuracy()
|
self.test_acc = Accuracy()
|
||||||
|
|
||||||
|
# for logging best accuracy achieved so far
|
||||||
|
self.val_acc_best = MaxMetric()
|
||||||
|
|
||||||
def forward(self, x: torch.Tensor):
|
def forward(self, x: torch.Tensor):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
@@ -63,13 +67,13 @@ class MNISTLitModel(LightningModule):
|
|||||||
loss, preds, targets = self.step(batch)
|
loss, preds, targets = self.step(batch)
|
||||||
|
|
||||||
# log train metrics
|
# log train metrics
|
||||||
acc = self.train_accuracy(preds, targets)
|
acc = self.train_acc(preds, targets)
|
||||||
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||||
self.log("train/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log("train/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here dict with any tensors
|
# we can return here dict with any tensors
|
||||||
# and then read it in some callback or in training_epoch_end() below
|
# and then read it in some callback or in `training_epoch_end()`` below
|
||||||
# remember to always return loss from training_step, or else backpropagation will fail!
|
# remember to always return loss from `training_step()` or else backpropagation will fail!
|
||||||
return {"loss": loss, "preds": preds, "targets": targets}
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
def training_epoch_end(self, outputs: List[Any]):
|
def training_epoch_end(self, outputs: List[Any]):
|
||||||
@@ -80,20 +84,25 @@ class MNISTLitModel(LightningModule):
|
|||||||
loss, preds, targets = self.step(batch)
|
loss, preds, targets = self.step(batch)
|
||||||
|
|
||||||
# log val metrics
|
# log val metrics
|
||||||
acc = self.val_accuracy(preds, targets)
|
acc = self.val_acc(preds, targets)
|
||||||
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||||
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
return {"loss": loss, "preds": preds, "targets": targets}
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
def validation_epoch_end(self, outputs: List[Any]):
|
def validation_epoch_end(self, outputs: List[Any]):
|
||||||
pass
|
acc = self.val_acc.compute() # get val accuracy from current epoch
|
||||||
|
self.val_acc.reset() # reset is necessary if you're using `num_sanity_val_steps` in trainer
|
||||||
|
|
||||||
|
# compute and log best so far val accuracy
|
||||||
|
self.val_acc_best.update(acc)
|
||||||
|
self.log("val/acc_best", self.val_acc_best.compute(), on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
def test_step(self, batch: Any, batch_idx: int):
|
def test_step(self, batch: Any, batch_idx: int):
|
||||||
loss, preds, targets = self.step(batch)
|
loss, preds, targets = self.step(batch)
|
||||||
|
|
||||||
# log test metrics
|
# log test metrics
|
||||||
acc = self.test_accuracy(preds, targets)
|
acc = self.test_acc(preds, targets)
|
||||||
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
||||||
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
||||||
|
|
||||||
|
|||||||
+7
-6
@@ -76,10 +76,13 @@ def train(config: DictConfig) -> Optional[float]:
|
|||||||
log.info("Starting training!")
|
log.info("Starting training!")
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
# Evaluate model on test set, using the best model achieved during training
|
# Get metric score for hyperparameter optimization
|
||||||
|
score = trainer.callback_metrics.get(config.get("optimized_metric"))
|
||||||
|
|
||||||
|
# Test the model
|
||||||
if config.get("test_after_training") and not config.trainer.get("fast_dev_run"):
|
if config.get("test_after_training") and not config.trainer.get("fast_dev_run"):
|
||||||
log.info("Starting testing!")
|
log.info("Starting testing!")
|
||||||
trainer.test()
|
trainer.test(model=model, datamodule=datamodule, ckpt_path="best")
|
||||||
|
|
||||||
# Make sure everything closed properly
|
# Make sure everything closed properly
|
||||||
log.info("Finalizing!")
|
log.info("Finalizing!")
|
||||||
@@ -94,9 +97,7 @@ def train(config: DictConfig) -> Optional[float]:
|
|||||||
|
|
||||||
# Print path to best checkpoint
|
# Print path to best checkpoint
|
||||||
if not config.trainer.get("fast_dev_run"):
|
if not config.trainer.get("fast_dev_run"):
|
||||||
log.info(f"Best model ckpt: {trainer.checkpoint_callback.best_model_path}")
|
log.info(f"Best model ckpt at {trainer.checkpoint_callback.best_model_path}")
|
||||||
|
|
||||||
# Return metric score for hyperparameter optimization
|
# Return metric score for hyperparameter optimization
|
||||||
optimized_metric = config.get("optimized_metric")
|
return score
|
||||||
if optimized_metric:
|
|
||||||
return trainer.callback_metrics[optimized_metric]
|
|
||||||
+16
-16
@@ -10,13 +10,21 @@ from pytorch_lightning.utilities import rank_zero_only
|
|||||||
|
|
||||||
|
|
||||||
def get_logger(name=__name__) -> logging.Logger:
|
def get_logger(name=__name__) -> logging.Logger:
|
||||||
"""Initializes multi-GPU-friendly python logger."""
|
"""Initializes multi-GPU-friendly python command line logger."""
|
||||||
|
|
||||||
logger = logging.getLogger(name)
|
logger = logging.getLogger(name)
|
||||||
|
|
||||||
# this ensures all logging levels get marked with the rank zero decorator
|
# this ensures all logging levels get marked with the rank zero decorator
|
||||||
# otherwise logs would get multiplied for each GPU process in multi-GPU setup
|
# otherwise logs would get multiplied for each GPU process in multi-GPU setup
|
||||||
for level in ("debug", "info", "warning", "error", "exception", "fatal", "critical"):
|
for level in (
|
||||||
|
"debug",
|
||||||
|
"info",
|
||||||
|
"warning",
|
||||||
|
"error",
|
||||||
|
"exception",
|
||||||
|
"fatal",
|
||||||
|
"critical",
|
||||||
|
):
|
||||||
setattr(logger, level, rank_zero_only(getattr(logger, level)))
|
setattr(logger, level, rank_zero_only(getattr(logger, level)))
|
||||||
|
|
||||||
return logger
|
return logger
|
||||||
@@ -101,14 +109,10 @@ def print_config(
|
|||||||
|
|
||||||
rich.print(tree)
|
rich.print(tree)
|
||||||
|
|
||||||
with open("config_tree.txt", "w") as fp:
|
with open("config_tree.log", "w") as fp:
|
||||||
rich.print(tree, file=fp)
|
rich.print(tree, file=fp)
|
||||||
|
|
||||||
|
|
||||||
def empty(*args, **kwargs):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@rank_zero_only
|
@rank_zero_only
|
||||||
def log_hyperparameters(
|
def log_hyperparameters(
|
||||||
config: DictConfig,
|
config: DictConfig,
|
||||||
@@ -121,7 +125,7 @@ def log_hyperparameters(
|
|||||||
"""This method controls which parameters from Hydra config are saved by Lightning loggers.
|
"""This method controls which parameters from Hydra config are saved by Lightning loggers.
|
||||||
|
|
||||||
Additionaly saves:
|
Additionaly saves:
|
||||||
- number of trainable model parameters
|
- number of model parameters
|
||||||
"""
|
"""
|
||||||
|
|
||||||
hparams = {}
|
hparams = {}
|
||||||
@@ -130,28 +134,24 @@ def log_hyperparameters(
|
|||||||
hparams["trainer"] = config["trainer"]
|
hparams["trainer"] = config["trainer"]
|
||||||
hparams["model"] = config["model"]
|
hparams["model"] = config["model"]
|
||||||
hparams["datamodule"] = config["datamodule"]
|
hparams["datamodule"] = config["datamodule"]
|
||||||
|
|
||||||
if "seed" in config:
|
if "seed" in config:
|
||||||
hparams["seed"] = config["seed"]
|
hparams["seed"] = config["seed"]
|
||||||
if "callbacks" in config:
|
if "callbacks" in config:
|
||||||
hparams["callbacks"] = config["callbacks"]
|
hparams["callbacks"] = config["callbacks"]
|
||||||
|
|
||||||
# save number of model parameters
|
# save number of model parameters
|
||||||
hparams["model/params_total"] = sum(p.numel() for p in model.parameters())
|
hparams["model/params/total"] = sum(p.numel() for p in model.parameters())
|
||||||
hparams["model/params_trainable"] = sum(
|
hparams["model/params/trainable"] = sum(
|
||||||
p.numel() for p in model.parameters() if p.requires_grad
|
p.numel() for p in model.parameters() if p.requires_grad
|
||||||
)
|
)
|
||||||
hparams["model/params_not_trainable"] = sum(
|
hparams["model/params/non_trainable"] = sum(
|
||||||
p.numel() for p in model.parameters() if not p.requires_grad
|
p.numel() for p in model.parameters() if not p.requires_grad
|
||||||
)
|
)
|
||||||
|
|
||||||
# send hparams to all loggers
|
# send hparams to all loggers
|
||||||
trainer.logger.log_hyperparams(hparams)
|
trainer.logger.log_hyperparams(hparams)
|
||||||
|
|
||||||
# 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 = empty
|
|
||||||
|
|
||||||
|
|
||||||
def finish(
|
def finish(
|
||||||
config: DictConfig,
|
config: DictConfig,
|
||||||
|
|||||||
@@ -24,7 +24,6 @@ def _module_available(module_path: str) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
_IS_WINDOWS = platform.system() == "Windows"
|
_IS_WINDOWS = platform.system() == "Windows"
|
||||||
_APEX_AVAILABLE = _module_available("apex.amp")
|
|
||||||
_DEEPSPEED_AVAILABLE = not _IS_WINDOWS and _module_available("deepspeed")
|
_DEEPSPEED_AVAILABLE = not _IS_WINDOWS and _module_available("deepspeed")
|
||||||
_FAIRSCALE_AVAILABLE = not _IS_WINDOWS and _module_available("fairscale.nn")
|
_FAIRSCALE_AVAILABLE = not _IS_WINDOWS and _module_available("fairscale.nn")
|
||||||
_RPC_AVAILABLE = not _IS_WINDOWS and _module_available("torch.distributed.rpc")
|
_RPC_AVAILABLE = not _IS_WINDOWS and _module_available("torch.distributed.rpc")
|
||||||
@@ -12,7 +12,6 @@ Adapted from:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
from tests.helpers.module_available import (
|
from tests.helpers.module_available import (
|
||||||
_APEX_AVAILABLE,
|
|
||||||
_DEEPSPEED_AVAILABLE,
|
_DEEPSPEED_AVAILABLE,
|
||||||
_FAIRSCALE_AVAILABLE,
|
_FAIRSCALE_AVAILABLE,
|
||||||
_IS_WINDOWS,
|
_IS_WINDOWS,
|
||||||
@@ -40,7 +39,6 @@ class RunIf:
|
|||||||
min_torch: Optional[str] = None,
|
min_torch: Optional[str] = None,
|
||||||
max_torch: Optional[str] = None,
|
max_torch: Optional[str] = None,
|
||||||
min_python: Optional[str] = None,
|
min_python: Optional[str] = None,
|
||||||
amp_apex: bool = False,
|
|
||||||
skip_windows: bool = False,
|
skip_windows: bool = False,
|
||||||
rpc: bool = False,
|
rpc: bool = False,
|
||||||
fairscale: bool = False,
|
fairscale: bool = False,
|
||||||
@@ -53,7 +51,6 @@ class RunIf:
|
|||||||
min_torch: minimum pytorch version to run test
|
min_torch: minimum pytorch version to run test
|
||||||
max_torch: maximum pytorch version to run test
|
max_torch: maximum pytorch version to run test
|
||||||
min_python: minimum python version required to run test
|
min_python: minimum python version required to run test
|
||||||
amp_apex: NVIDIA Apex is installed
|
|
||||||
skip_windows: skip test for Windows platform
|
skip_windows: skip test for Windows platform
|
||||||
rpc: requires Remote Procedure Call (RPC)
|
rpc: requires Remote Procedure Call (RPC)
|
||||||
fairscale: if `fairscale` module is required to run the test
|
fairscale: if `fairscale` module is required to run the test
|
||||||
@@ -84,10 +81,6 @@ class RunIf:
|
|||||||
conditions.append(Version(py_version) < Version(min_python))
|
conditions.append(Version(py_version) < Version(min_python))
|
||||||
reasons.append(f"python>={min_python}")
|
reasons.append(f"python>={min_python}")
|
||||||
|
|
||||||
if amp_apex:
|
|
||||||
conditions.append(not _APEX_AVAILABLE)
|
|
||||||
reasons.append("NVIDIA Apex")
|
|
||||||
|
|
||||||
if skip_windows:
|
if skip_windows:
|
||||||
conditions.append(_IS_WINDOWS)
|
conditions.append(_IS_WINDOWS)
|
||||||
reasons.append("does not run on Windows")
|
reasons.append("does not run on Windows")
|
||||||
|
|||||||
@@ -1,43 +1,49 @@
|
|||||||
import pytest
|
|
||||||
|
|
||||||
from tests.helpers.run_command import run_command
|
from tests.helpers.run_command import run_command
|
||||||
from tests.helpers.runif import RunIf
|
from tests.helpers.runif import RunIf
|
||||||
|
|
||||||
|
"""
|
||||||
|
A couple of sanity checks to make sure the model doesn't crash with different running options.
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
def test_fast_dev_run():
|
def test_fast_dev_run():
|
||||||
"""Run 1 train, val, test batch."""
|
"""Test running for 1 train, val and test batch."""
|
||||||
command = ["run.py", "++trainer.fast_dev_run=true"]
|
command = ["run.py", "++trainer.fast_dev_run=true"]
|
||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
def test_default_cpu():
|
def test_cpu():
|
||||||
"""Test default config on CPU."""
|
"""Test running 1 epoch on CPU."""
|
||||||
command = ["run.py", "++trainer.max_epochs=1", "++trainer.gpus=0"]
|
command = ["run.py", "++trainer.max_epochs=1", "++trainer.gpus=0"]
|
||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
# use RunIf to skip execution of some tests, e.g. when no gpus are available
|
# use RunIf to skip execution of some tests, e.g. when no gpus are available
|
||||||
@RunIf(min_gpus=1)
|
@RunIf(min_gpus=1)
|
||||||
def test_default_gpu():
|
def test_gpu():
|
||||||
"""Test default config on GPU."""
|
"""Test running 1 epoch on GPU."""
|
||||||
command = [
|
command = [
|
||||||
"run.py",
|
"run.py",
|
||||||
"++trainer.max_epochs=1",
|
"++trainer.max_epochs=1",
|
||||||
"++trainer.gpus=1",
|
"++trainer.gpus=1",
|
||||||
"++datamodule.pin_memory=True",
|
|
||||||
]
|
]
|
||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.slow
|
@RunIf(min_gpus=1)
|
||||||
def test_experiments():
|
def test_mixed_precision():
|
||||||
"""Train 1 epoch with all experiment configs."""
|
"""Test running 1 epoch with pytorch native automatic mixed precision (AMP)."""
|
||||||
command = ["run.py", "-m", "experiment=glob(*)", "++trainer.max_epochs=1"]
|
command = [
|
||||||
|
"run.py",
|
||||||
|
"++trainer.max_epochs=1",
|
||||||
|
"++trainer.gpus=1",
|
||||||
|
"++trainer.precision=16",
|
||||||
|
]
|
||||||
run_command(command)
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
def test_limit_batches():
|
def test_limit_batches():
|
||||||
"""Train 1 epoch on 25% of data."""
|
"""Test running 1 epoch on 25% of data."""
|
||||||
command = [
|
command = [
|
||||||
"run.py",
|
"run.py",
|
||||||
"++trainer.max_epochs=1",
|
"++trainer.max_epochs=1",
|
||||||
@@ -49,7 +55,7 @@ def test_limit_batches():
|
|||||||
|
|
||||||
|
|
||||||
def test_double_validation_loop():
|
def test_double_validation_loop():
|
||||||
"""Train 1 epoch with validation loop twice per epoch."""
|
"""Test running 1 epoch with validation loop twice per epoch."""
|
||||||
command = [
|
command = [
|
||||||
"run.py",
|
"run.py",
|
||||||
"++trainer.max_epochs=1",
|
"++trainer.max_epochs=1",
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
from tests.helpers.run_command import run_command
|
|
||||||
from tests.helpers.runif import RunIf
|
|
||||||
|
|
||||||
|
|
||||||
@RunIf(amp_apex=True)
|
|
||||||
def test_apex_O1():
|
|
||||||
"""Test mixed-precision level O1."""
|
|
||||||
command = [
|
|
||||||
"run.py",
|
|
||||||
"trainer=default",
|
|
||||||
"++trainer.max_epochs=1",
|
|
||||||
"++trainer.gpus=1",
|
|
||||||
"++trainer.amp_backend=apex",
|
|
||||||
"++trainer.amp_level=O1",
|
|
||||||
"++trainer.precision=16",
|
|
||||||
]
|
|
||||||
run_command(command)
|
|
||||||
|
|
||||||
|
|
||||||
@RunIf(amp_apex=True)
|
|
||||||
def test_apex_O2():
|
|
||||||
"""Test mixed-precision level O2."""
|
|
||||||
command = [
|
|
||||||
"run.py",
|
|
||||||
"trainer=default",
|
|
||||||
"++trainer.max_epochs=1",
|
|
||||||
"++trainer.gpus=1",
|
|
||||||
"++trainer.amp_backend=apex",
|
|
||||||
"++trainer.amp_level=O2",
|
|
||||||
"++trainer.precision=16",
|
|
||||||
]
|
|
||||||
run_command(command)
|
|
||||||
|
|
||||||
|
|
||||||
@RunIf(amp_apex=True)
|
|
||||||
def test_apex_O3():
|
|
||||||
"""Test mixed-precision level O3."""
|
|
||||||
command = [
|
|
||||||
"run.py",
|
|
||||||
"trainer=default",
|
|
||||||
"++trainer.max_epochs=1",
|
|
||||||
"++trainer.gpus=1",
|
|
||||||
"++trainer.amp_backend=apex",
|
|
||||||
"++trainer.amp_level=O3",
|
|
||||||
"++trainer.precision=16",
|
|
||||||
]
|
|
||||||
run_command(command)
|
|
||||||
@@ -3,11 +3,20 @@ import pytest
|
|||||||
from tests.helpers.run_command import run_command
|
from tests.helpers.run_command import run_command
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
A couple of tests executing hydra sweeps.
|
||||||
|
|
||||||
Use the following command to skip slow tests:
|
Use the following command to skip slow tests:
|
||||||
pytest -k "not slow"
|
pytest -k "not slow"
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
@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"]
|
||||||
|
run_command(command)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.slow
|
@pytest.mark.slow
|
||||||
def test_default_sweep():
|
def test_default_sweep():
|
||||||
"""Test default Hydra sweeper."""
|
"""Test default Hydra sweeper."""
|
||||||
|
|||||||
Reference in new issue
Block a user