diff --git a/.autoenv.template b/.autoenv.template
deleted file mode 100644
index 90c1b73..0000000
--- a/.autoenv.template
+++ /dev/null
@@ -1,15 +0,0 @@
-# this a template of the file that can be used for automatic execution of shell commands when entering folder
-# it useful for automatic activation of conda environment and hydra tab completion
-# create a file named .autoenv
-# by default .autoenv will be excluded from version control
-# next, execute the line below to enable the automation for bash:
-# echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
-# alternatively, you can load it manually each time with:
-# source .autoenv
-
-
-# activate conda environment
-conda activate myenv
-
-# initialize hydra tab completion for bash
-eval "$(python run.py -sc install=bash)"
diff --git a/README.md b/README.md
index 7367484..2d68fae 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ to your `README.md`.
-->
-## Introduction
+## :pushpin: Introduction
This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [src/train.py](src/train.py).
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
@@ -58,6 +58,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)
- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices))
- **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features))
+- **Tests**: unit tests and smoke tests (see [#Best Practices](#best-practices))
- **Workflow**: comes down to 4 simple steps (see [#Workflow](#workflow))
@@ -85,6 +86,8 @@ The directory structure of new project looks like this:
│ `1.0-jqp-initial-data-exploration.ipynb`.
│
├── tests <- Tests of any kind
+│ ├── smoke_tests
+│ └── unit_tests
│
├── src
│ ├── callbacks <- Lightning callbacks
@@ -99,7 +102,6 @@ The directory structure of new project looks like this:
├── run.py <- Run any pipeline with chosen experiment configuration
│
├── .env.template <- Template of file for storing private environment variables
-├── .autoenv.template <- Template of file for automatic virtual environment setup
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── conda_env_gpu.yaml <- File for installing conda environment
@@ -140,7 +142,7 @@ When running `python run.py` you should see something like this:
> Hydra allows you to easily overwrite any parameter defined in your config.
```yaml
-python run.py trainer.max_epochs=20 optimizer.lr=1e-4
+python run.py trainer.max_epochs=20 model.lr=1e-4
```
> You can also add new parameters with `+` sign.
```yaml
@@ -205,7 +207,7 @@ python run.py logger=wandb
> Experiment configurations are placed in [configs/experiment/](configs/experiment/).
```yaml
-python run.py experiment=exp_example_simple
+python run.py experiment=example_simple
```
@@ -217,7 +219,7 @@ python run.py experiment=exp_example_simple
> Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).
Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
```yaml
-python run.py callbacks=default_callbacks
+python run.py callbacks=default
```
@@ -289,7 +291,7 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
```yaml
# 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 optimizer.lr=0.001,0.0005
+python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
```
> ⚠️ Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
@@ -303,7 +305,7 @@ python run.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
```yaml
# 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=exp_example_simple
+python run.py -m hparams_search=mnist_optuna experiment=example_simple
```
@@ -352,6 +354,8 @@ docker pull nvcr.io/nvidia/pytorch:21.03-py3
# run container from image with GPUs enabled
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
+# # run container with mounted volume
+# docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
```
```yaml
# alternatively build image by yourself using Dockerfile from the mentioned template branch
@@ -369,7 +373,7 @@ Have a question? Found a bug? Missing a specific feature? Ran into a problem? Fe
## :information_source: Guide
-### How To Learn
+### How To Get Started
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)
- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) and [docs about instantiating objects with Hydra](https://hydra.cc/docs/patterns/instantiate_objects/overview)
@@ -408,10 +412,10 @@ It also specifies everything that shouldn't be managed by experiment configurati
```yaml
# specify here default training configuration
defaults:
- - trainer: default_trainer.yaml
+ - trainer: minimal.yaml
- model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml
- - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
+ - callbacks: default.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
@@ -460,13 +464,13 @@ Experiment configurations allow you to overwrite parameters from main project co
**Simple example**
```yaml
# to execute this experiment run:
-# python run.py +experiment=exp_example_simple
+# python run.py +experiment=example_simple
defaults:
- - override /trainer: default_trainer.yaml
+ - override /trainer: minimal.yaml
- override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml
- - override /callbacks: default_callbacks.yaml
+ - override /callbacks: default.yaml
- override /logger: null
# all parameters below will be merged with parameters from default configurations set above
@@ -496,7 +500,7 @@ datamodule:
```yaml
# to execute this experiment run:
-# python run.py +experiment=exp_example_full
+# python run.py +experiment=example_full
defaults:
- override /trainer: null
@@ -507,7 +511,7 @@ defaults:
# we override default configurations with nulls to prevent them from loading at all
# instead we define all modules and their paths directly in this config,
-# so everything is stored in one place for more readability
+# so everything is stored in one place
seed: 12345
@@ -615,8 +619,15 @@ Take a look at [inference_example.py](src/utils/inference_example.py).
### 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)).
-To support reproducibility: **WatchModelWithWandb**, **UploadCodeToWandbAsArtifact**, **UploadCheckpointsToWandbAsArtifact**.
-To provide examples of logging custom visualisations with callbacks only: **LogConfusionMatrixToWandb**, **LogF1PrecRecHeatmapToWandb**.
+To support reproducibility:
+- **WatchModel**
+- **UploadCodeAsArtifact**
+- **UploadCheckpointsAsArtifact**
+
+To provide examples of logging custom visualisations with callbacks only:
+- **LogConfusionMatrix**
+- **LogF1PrecRecHeatmap**
+- **ImagePredictionLogger**
@@ -647,7 +658,6 @@ Use metrics api objects, e.g. `pytorch_lightning.metrics.classification.Accuracy
### Extra Features
List of extra utilities available in the template:
- loading environment variables from [.env](.env.template) file
-- automatic virtual environment setup with [.autoenv](.autoenv.template) file
- pretty printing config with [Rich](https://github.com/willmcgugan/rich) library
- disabling python warnings
- easier access to debug mode
@@ -667,6 +677,27 @@ You can easily remove any of those by modifying [run.py](run.py) and [src/train.
## Best Practices
+
+Write unit tests and smoke tests
+
+Template comes with example tests implemented with pytest library.
+To execute them simply run:
+```yaml
+# run all tests
+pytest
+
+# run tests from specific file
+pytest tests/smoke_tests/test_commands.py
+
+# run all tests except the ones using wandb
+pytest -k "not wandb"
+```
+I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. You can find those tests implemented with pytest in [tests/smoke_tests](tests/smoke_tests) folder.
+
+You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).
+
+
+
Use Docker
@@ -684,7 +715,11 @@ Example installation:
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
-Docker image provided in the template already comes with initialized miniconda environment.
+Create environment from file provided in the template:
+```yaml
+conda env create -f conda_env_gpu.yaml -n myenv
+conda activate myenv
+```
@@ -840,38 +875,23 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule
-
-
-Write tests
-
-(TODO)
-
-
-
-
+
+
+
## Tricks
-Automatic activation of virtual environment and tab completion
+Automatic activation of virtual environment and tab completion when entering folder
-Template contains `.autoenv.template` file, which serves as an example. Create a new file called `.autoenv` (this name is excluded from version control in .gitignore).
-You can use it to automatically execute shell commands when entering folder:
+Create a new file called `.autoenv` (this name is excluded from version control in .gitignore).
+Add to the file the following lines:
```bash
# activate conda environment
conda activate myenv
@@ -880,17 +900,19 @@ conda activate myenv
eval "$(python run.py -sc install=bash)"
```
+You can use it to automatically execute shell commands when entering folder.
To setup this automation for bash, execute the following line:
```bash
echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
```
+Keep in mind this will modify your `.bashrc` file to always run `.autoenv` file whenever it's present in the current folder, which means it creates a potential security issue.
+
**Explanation**
-This line appends your `.bashrc` file with 3 commands:
+The mentioned line appends your `.bashrc` file with 3 commands:
1. `autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir
2. `cd() { builtin cd \"\$@\" ; autoenv ; }` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal
3. `autoenv` this is just to ensure the function will also be called when directly openning terminal in any folder
-
@@ -956,7 +978,8 @@ This template was inspired by:
- [pytorch/hydra-torch](https://github.com/pytorch/hydra-torch) - resources for configuring PyTorch classes with Hydra,
- [romesco/hydra-lightning](https://github.com/romesco/hydra-lightning) - resources for configuring PyTorch Lightning classes with Hydra
-- [lucmos/nn-template](https://github.com/lucmos/nn-template) - similar template that's easier to start with but less scalable
+- [lucmos/nn-template](https://github.com/lucmos/nn-template) - similar template
+- [PyTorchLightning/lightning-transformers](https://github.com/PyTorchLightning/lightning-transformers) - official Lightning Transformers repo built with Hydra
@@ -970,6 +993,11 @@ This template was inspired by:
+
+
+
@@ -1027,7 +1055,7 @@ python run.py trainer.gpus=1
Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/)
```yaml
-python run.py +experiment=experiment_name
+python run.py experiment=experiment_name
```
You can override any parameter from command line like this
diff --git a/configs/callbacks/default_callbacks.yaml b/configs/callbacks/default.yaml
similarity index 100%
rename from configs/callbacks/default_callbacks.yaml
rename to configs/callbacks/default.yaml
diff --git a/configs/callbacks/wandb_callbacks.yaml b/configs/callbacks/wandb.yaml
similarity index 73%
rename from configs/callbacks/wandb_callbacks.yaml
rename to configs/callbacks/wandb.yaml
index 92f7421..7c51474 100644
--- a/configs/callbacks/wandb_callbacks.yaml
+++ b/configs/callbacks/wandb.yaml
@@ -1,31 +1,32 @@
defaults:
- - default_callbacks.yaml
+ - default.yaml
-watch_model_with_wandb:
+watch_model:
_target_: src.callbacks.wandb_callbacks.WatchModelWithWandb
log: "all"
log_freq: 100
-upload_code_to_wandb_as_artifact:
+upload_code_as_artifact:
_target_: src.callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact
code_dir: ${work_dir}
-upload_ckpts_to_wandb_as_artifact:
+upload_ckpts_as_artifact:
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
ckpt_dir: "checkpoints/"
upload_best_only: True
-save_f1_precision_recall_heatmap_to_wandb:
+log_f1_precision_recall_heatmap:
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb
-save_confusion_matrix_to_wandb:
+log_confusion_matrix:
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb
-log_images:
+
+log_images_with_predictions:
_target_: src.callbacks.wandb_callbacks.ImagePredictionLogger
num_samples: 8
diff --git a/configs/config.yaml b/configs/config.yaml
index 942b4e8..7fc4f7e 100644
--- a/configs/config.yaml
+++ b/configs/config.yaml
@@ -2,10 +2,10 @@
# specify here default training configuration
defaults:
- - trainer: default_trainer.yaml
+ - trainer: minimal.yaml
- model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml
- - callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
+ - callbacks: default.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
- experiment: null
diff --git a/configs/experiment/exp_example_full.yaml b/configs/experiment/example_full.yaml
similarity index 94%
rename from configs/experiment/exp_example_full.yaml
rename to configs/experiment/example_full.yaml
index 1c1b5dd..2b8e3fe 100644
--- a/configs/experiment/exp_example_full.yaml
+++ b/configs/experiment/example_full.yaml
@@ -1,7 +1,7 @@
# @package _global_
# to execute this experiment run:
-# python run.py +experiment=exp_example_full
+# python run.py experiment=example_full.yaml
defaults:
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
@@ -12,7 +12,7 @@ defaults:
# we override default configurations with nulls to prevent them from loading at all
# instead we define all modules and their paths directly in this config,
-# so everything is stored in one place for more readability
+# so everything is stored in one place
seed: 12345
diff --git a/configs/experiment/exp_example_simple.yaml b/configs/experiment/example_simple.yaml
similarity index 75%
rename from configs/experiment/exp_example_simple.yaml
rename to configs/experiment/example_simple.yaml
index fa6f221..117c654 100644
--- a/configs/experiment/exp_example_simple.yaml
+++ b/configs/experiment/example_simple.yaml
@@ -1,13 +1,13 @@
# @package _global_
# to execute this experiment run:
-# python run.py +experiment=exp_example_simple
+# python run.py experiment=example_simple.yaml
defaults:
- - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/'
+ - override /trainer: minimal.yaml # choose trainer from 'configs/trainer/'
- override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml
- - override /callbacks: default_callbacks.yaml
+ - override /callbacks: default.yaml
- override /logger: null
# all parameters below will be merged with parameters from default configurations set above
diff --git a/configs/trainer/ddp.yaml b/configs/trainer/ddp.yaml
new file mode 100644
index 0000000..d14a2d9
--- /dev/null
+++ b/configs/trainer/ddp.yaml
@@ -0,0 +1,5 @@
+
+_target_: pytorch_lightning.Trainer
+
+gpus: 4
+accelerator: ddp
diff --git a/configs/trainer/debug.yaml b/configs/trainer/debug.yaml
new file mode 100644
index 0000000..9eca67b
--- /dev/null
+++ b/configs/trainer/debug.yaml
@@ -0,0 +1,21 @@
+_target_: pytorch_lightning.Trainer
+
+gpus: 0
+
+min_epochs: 1
+max_epochs: 3
+
+# prints
+progress_bar_refresh_rate: null
+weights_summary: null
+profiler: null
+
+# debugs
+num_sanity_val_steps: 2
+fast_dev_run: False
+overfit_batches: 0
+limit_train_batches: 1.0
+limit_val_batches: 1.0
+limit_test_batches: 1.0
+track_grad_norm: -1
+terminate_on_nan: False
diff --git a/configs/trainer/debug_trainer.yaml b/configs/trainer/debug_trainer.yaml
deleted file mode 100644
index 454cecd..0000000
--- a/configs/trainer/debug_trainer.yaml
+++ /dev/null
@@ -1,49 +0,0 @@
-# Trainer args for debugging model
-
-_target_: pytorch_lightning.Trainer
-
-
-gpus: 0
-
-min_epochs: 1
-max_epochs: 3
-
-# prints
-progress_bar_refresh_rate: null
-weights_summary: null
-profiler: null
-
-# all parameters below are set to Lightning defaults
-
-# tricks
-gradient_clip_val: 0
-accumulate_grad_batches: 1
-val_check_interval: 1.0
-check_val_every_n_epoch: 1
-stochastic_weight_avg: False
-
-# debug
-num_sanity_val_steps: 2
-fast_dev_run: False
-overfit_batches: 0
-limit_train_batches: 1.0
-limit_val_batches: 1.0
-limit_test_batches: 1.0
-track_grad_norm: -1
-terminate_on_nan: False
-
-# others
-amp_backend: "native"
-amp_level: "02"
-precision: 32
-accelerator: null
-num_nodes: 1
-tpu_cores: null
-deterministic: False
-
-resume_from_checkpoint: null
-
-
-# automatically find the largest batch size that fits into memory and is power of 2
-# (requires calling trainer.tune(model=model, datamodule=datamodule))
-# auto_scale_batch_size:'power'
diff --git a/configs/trainer/default.yaml b/configs/trainer/default.yaml
new file mode 100644
index 0000000..450a6fd
--- /dev/null
+++ b/configs/trainer/default.yaml
@@ -0,0 +1,50 @@
+_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
diff --git a/configs/trainer/default_trainer.yaml b/configs/trainer/minimal.yaml
similarity index 85%
rename from configs/trainer/default_trainer.yaml
rename to configs/trainer/minimal.yaml
index 42e4c70..bcfc53e 100644
--- a/configs/trainer/default_trainer.yaml
+++ b/configs/trainer/minimal.yaml
@@ -9,4 +9,4 @@ max_epochs: 10
weights_summary: null
progress_bar_refresh_rate: 10
-terminate_on_nan: False
+# resume_from_checkpoint: null
diff --git a/requirements.txt b/requirements.txt
index a401dd7..0a5233b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,7 +1,7 @@
# --------- pytorch --------- #
torch==1.8.1
torchvision==0.9.1
-pytorch-lightning>=1.2.7
+pytorch-lightning>=1.2.10
# --------- hydra --------- #
hydra-core==1.1.0.dev5
@@ -19,11 +19,11 @@ wandb>=0.10.26
# --------- others --------- #
rich
python-dotenv
+pytest
pre-commit
scikit-learn
pandas
matplotlib
seaborn
# pudb
-# pytest
# dvc
diff --git a/src/callbacks/wandb_callbacks.py b/src/callbacks/wandb_callbacks.py
index 3b626c7..1c3aa72 100644
--- a/src/callbacks/wandb_callbacks.py
+++ b/src/callbacks/wandb_callbacks.py
@@ -201,7 +201,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
class ImagePredictionLogger(Callback):
"""Logs a validation batch and their predictions to wandb.
Example adapted from:
- https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
+ https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
"""
def __init__(self, num_samples: int = 8):
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..d4c82b7
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,3 @@
+def pytest_configure(config):
+ config.addinivalue_line("markers", "slow: Run slow tests.")
+ config.addinivalue_line("markers", "wandb: Run the wandb tests.")
diff --git a/tests/gpu_tests.sh b/tests/gpu_tests.sh
deleted file mode 100644
index 9c3f120..0000000
--- a/tests/gpu_tests.sh
+++ /dev/null
@@ -1,45 +0,0 @@
-# !/bin/bash
-# Quick tests for gpu
-
-# To execute:
-# bash tests/gpu_tests.sh
-
-# Method for printing test name
-echo() {
- termwidth="$(tput cols)"
- padding="$(printf '%0.1s' ={1..500})"
- printf '\e[33m%*.*s %s %*.*s\n\e[0m' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
-}
-
-# Make python hide warnings
-export PYTHONWARNINGS="ignore"
-
-
-echo "TEST 1"
-echo "Train on GPU (2 epochs)"
-python run.py trainer.gpus=-1 trainer.max_epochs=2 \
-print_config=false
-
-echo "TEST 2"
-echo "Train with 4 workers and cuda pinned memory (2 epochs)"
-python run.py trainer.gpus=-1 trainer.max_epochs=2 \
-datamodule.num_workers=4 datamodule.pin_memory=True \
-print_config=false
-
-echo "TEST 3"
-echo "Train with mixed precision (apex, amp level 01, 1 epoch)"
-python run.py trainer.gpus=-1 trainer.max_epochs=1 \
-+trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16 \
-print_config=false
-
-echo "TEST 4"
-echo "Train with mixed precision (apex, amp level 02, 1 epoch)"
-python run.py trainer.gpus=-1 trainer.max_epochs=1 \
-+trainer.amp_backend="apex" +trainer.amp_level="O2" +trainer.precision=16 \
-print_config=false
-
-echo "TEST 5"
-echo "Train with mixed precision (apex, amp level 03, 1 epoch)"
-python run.py trainer.gpus=-1 trainer.max_epochs=1 \
-+trainer.amp_backend="apex" +trainer.amp_level="O3" +trainer.precision=16 \
-print_config=false
diff --git a/tests/helpers/__init__.py b/tests/helpers/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/helpers/module_available.py b/tests/helpers/module_available.py
new file mode 100644
index 0000000..50688c2
--- /dev/null
+++ b/tests/helpers/module_available.py
@@ -0,0 +1,34 @@
+import platform
+from importlib.util import find_spec
+
+"""
+Adapted from:
+ https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pytorch_lightning/utilities/imports.py
+"""
+
+
+def _module_available(module_path: str) -> bool:
+ """
+ Check if a path is available in your environment.
+
+ >>> _module_available('os')
+ True
+ >>> _module_available('bla.bla')
+ False
+
+ """
+ try:
+ return find_spec(module_path) is not None
+ except AttributeError:
+ # Python 3.6
+ return False
+ except ModuleNotFoundError:
+ # Python 3.7+
+ return False
+
+
+_IS_WINDOWS = platform.system() == "Windows"
+_APEX_AVAILABLE = _module_available("apex.amp")
+_DEEPSPEED_AVAILABLE = not _IS_WINDOWS and _module_available("deepspeed")
+_FAIRSCALE_AVAILABLE = not _IS_WINDOWS and _module_available("fairscale.nn")
+_RPC_AVAILABLE = not _IS_WINDOWS and _module_available("torch.distributed.rpc")
diff --git a/tests/helpers/run_command.py b/tests/helpers/run_command.py
new file mode 100644
index 0000000..1670988
--- /dev/null
+++ b/tests/helpers/run_command.py
@@ -0,0 +1,15 @@
+from typing import List
+
+import pytest
+import sh
+
+
+def run_command(command: List[str]):
+ """Default method for executing shell commands with pytest."""
+ msg = None
+ try:
+ sh.python(command)
+ except sh.ErrorReturnCode as e:
+ msg = e.stderr.decode()
+ if msg:
+ pytest.fail(msg=msg)
diff --git a/tests/helpers/runif.py b/tests/helpers/runif.py
new file mode 100644
index 0000000..9c66ff4
--- /dev/null
+++ b/tests/helpers/runif.py
@@ -0,0 +1,120 @@
+import sys
+from typing import Optional
+
+import pytest
+import torch
+from packaging.version import Version
+from pkg_resources import get_distribution
+
+"""
+Adapted from:
+ https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/helpers/runif.py
+"""
+
+
+from tests.helpers.module_available import (
+ _APEX_AVAILABLE,
+ _DEEPSPEED_AVAILABLE,
+ _FAIRSCALE_AVAILABLE,
+ _IS_WINDOWS,
+ _RPC_AVAILABLE,
+)
+
+
+class RunIf:
+ """
+ RunIf wrapper for simple marking specific cases, fully compatible with pytest.mark::
+
+ @RunIf(min_torch="0.0")
+ @pytest.mark.parametrize("arg1", [1, 2.0])
+ def test_wrapper(arg1):
+ assert arg1 > 0.0
+ """
+
+ def __new__(
+ self,
+ min_gpus: int = 0,
+ min_torch: Optional[str] = None,
+ max_torch: Optional[str] = None,
+ min_python: Optional[str] = None,
+ amp_apex: bool = False,
+ skip_windows: bool = False,
+ rpc: bool = False,
+ fairscale: bool = False,
+ deepspeed: bool = False,
+ **kwargs,
+ ):
+ """
+ Args:
+ min_gpus: min number of gpus required to run test
+ min_torch: minimum pytorch version to run test
+ max_torch: maximum pytorch version 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 (typically fo some limited torch functionality)
+ rpc: requires Remote Procedure Call (RPC)
+ fairscale: if `fairscale` module is required to run the test
+ deepspeed: if `deepspeed` module is required to run the test
+ kwargs: native pytest.mark.skipif keyword arguments
+ """
+ conditions = []
+ reasons = []
+
+ if min_gpus:
+ conditions.append(torch.cuda.device_count() < min_gpus)
+ reasons.append(f"GPUs>={min_gpus}")
+
+ if min_torch:
+ torch_version = get_distribution("torch").version
+ conditions.append(Version(torch_version) < Version(min_torch))
+ reasons.append(f"torch>={min_torch}")
+
+ if max_torch:
+ torch_version = get_distribution("torch").version
+ conditions.append(Version(torch_version) >= Version(max_torch))
+ reasons.append(f"torch<{max_torch}")
+
+ if min_python:
+ py_version = (
+ f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
+ )
+ conditions.append(Version(py_version) < Version(min_python))
+ reasons.append(f"python>={min_python}")
+
+ if amp_apex:
+ conditions.append(not _APEX_AVAILABLE)
+ reasons.append("NVIDIA Apex")
+
+ if skip_windows:
+ conditions.append(_IS_WINDOWS)
+ reasons.append("does not run on Windows")
+
+ if rpc:
+ conditions.append(not _RPC_AVAILABLE)
+ reasons.append("RPC")
+
+ if fairscale:
+ conditions.append(not _FAIRSCALE_AVAILABLE)
+ reasons.append("Fairscale")
+
+ if deepspeed:
+ conditions.append(not _DEEPSPEED_AVAILABLE)
+ reasons.append("Deepspeed")
+
+ reasons = [rs for cond, rs in zip(conditions, reasons) if cond]
+ return pytest.mark.skipif(
+ condition=any(conditions),
+ reason=f"Requires: [{' + '.join(reasons)}]",
+ **kwargs,
+ )
+
+
+@RunIf(min_torch="99")
+def test_always_skip():
+ exit(1)
+
+
+@pytest.mark.parametrize("arg1", [0.5, 1.0, 2.0])
+@RunIf(min_torch="0.0")
+def test_wrapper(arg1: float):
+ assert arg1 > 0.0
diff --git a/tests/smoke_tests.sh b/tests/smoke_tests.sh
deleted file mode 100644
index 39a8a0a..0000000
--- a/tests/smoke_tests.sh
+++ /dev/null
@@ -1,75 +0,0 @@
-# !/bin/bash
-# These are just a couple of quick experiments to test if your model doesn't crash under different conditions
-
-# To execute:
-# bash tests/quick_tests.sh
-
-# Method for printing test name
-echo() {
- termwidth="$(tput cols)"
- padding="$(printf '%0.1s' ={1..500})"
- printf '\e[33m%*.*s %s %*.*s\n\e[0m' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
-}
-
-# Make python hide warnings
-export PYTHONWARNINGS="ignore"
-
-
-echo "TEST 1"
-echo "Debug mode (run 1 train, val and test loop using 1 batch)"
-python run.py trainer=debug_trainer debug=True \
-print_config=false
-
-echo "TEST 2"
-echo "Overfit to 10 batches (10 epochs)"
-python run.py trainer=debug_trainer trainer.overfit_batches=10 \
-trainer.min_epochs=10 trainer.max_epochs=10 \
-print_config=false
-
-echo "TEST 3"
-echo "Train on CPU (1 epoch)"
-python run.py trainer=debug_trainer trainer.gpus=0 trainer.max_epochs=1 \
-print_config=false
-
-echo "TEST 4"
-echo "Train on 25% of data (1 epoch)"
-python run.py trainer=debug_trainer trainer.max_epochs=1 \
-trainer.limit_train_batches=0.25 trainer.limit_val_batches=0.25 trainer.limit_test_batches=0.25 \
-print_config=false
-
-echo "TEST 5"
-echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)"
-python run.py trainer=debug_trainer trainer.max_epochs=1 \
-trainer.limit_train_batches=15 trainer.limit_val_batches=10 trainer.limit_test_batches=5 \
-print_config=false
-
-echo "TEST 6"
-echo "Run all experiment configs (2 epochs)"
-python run.py -m trainer=debug_trainer '+experiment=glob(*)' trainer.max_epochs=2 \
-print_config=false
-
-echo "TEST 7"
-echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
-python run.py -m trainer=debug_trainer datamodule.batch_size=32,64 model.lr=0.001,0.003 \
-debug=True \
-print_config=false
-
-echo "TEST 8"
-echo "Run with gradient accumulation (1 epoch)"
-python run.py trainer=debug_trainer trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \
-print_config=false
-
-echo "TEST 9"
-echo "Run validation loop twice per epoch (1 epoch)"
-python run.py trainer=debug_trainer trainer.max_epochs=1 trainer.val_check_interval=0.5 \
-print_config=false
-
-echo "TEST 10"
-echo "Run with CSVLogger (3 epochs)"
-python run.py trainer=debug_trainer logger=csv trainer.max_epochs=2 trainer.limit_train_batches=10 \
-print_config=false
-
-echo "TEST 11"
-echo "Run with TensorBoardLogger (3 epochs)"
-python run.py trainer=debug_trainer logger=tensorboard trainer.max_epochs=2 trainer.limit_train_batches=10 \
-print_config=false
diff --git a/tests/smoke_tests/__init__.py b/tests/smoke_tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/smoke_tests/test_commands.py b/tests/smoke_tests/test_commands.py
new file mode 100644
index 0000000..4e29be7
--- /dev/null
+++ b/tests/smoke_tests/test_commands.py
@@ -0,0 +1,103 @@
+from tests.helpers.run_command import run_command
+from tests.helpers.runif import RunIf
+
+
+def test_default_cpu():
+ """Test default configuration on CPU."""
+ command = ["run.py", "trainer.max_epochs=1", "trainer.gpus=0"]
+ run_command(command)
+
+
+@RunIf(min_gpus=1)
+def test_default_gpu():
+ """Test default configuration on GPU."""
+ command = [
+ "run.py",
+ "trainer.max_epochs=1",
+ "trainer.gpus=1",
+ "datamodule.pin_memory=True",
+ ]
+ run_command(command)
+
+
+def test_fast_dev_run():
+ """Run 1 train, val, test batch."""
+ command = ["run.py", "trainer=default", "trainer.fast_dev_run=true"]
+ run_command(command)
+
+
+def test_experiments():
+ """Train 1 epoch with all experiment configs."""
+ command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"]
+ run_command(command)
+
+
+def test_limit_batches():
+ """Train 1 epoch on 25% of data."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "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)
+
+
+def test_gradient_accumulation():
+ """Train 1 epoch with gradient accumulation."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.max_epochs=1",
+ "trainer.accumulate_grad_batches=10",
+ ]
+ run_command(command)
+
+
+def test_double_validation_loop():
+ """Train 1 epoch with validation loop twice per epoch."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.max_epochs=1",
+ "trainer.val_check_interval=0.5",
+ ]
+ run_command(command)
+
+
+def test_csv_logger():
+ """Train 5 epochs with 5 batches with CSVLogger."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.max_epochs=5",
+ "trainer.limit_train_batches=5",
+ "logger=csv",
+ ]
+ run_command(command)
+
+
+def test_tensorboard_logger():
+ """Train 5 epochs with 5 batches with TensorboardLogger."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.max_epochs=5",
+ "trainer.limit_train_batches=5",
+ "logger=tensorboard",
+ ]
+ run_command(command)
+
+
+def test_overfit_batches():
+ """Overfit to 10 batches over 10 epochs."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.min_epochs=10",
+ "trainer.max_epochs=10",
+ "trainer.overfit_batches=10",
+ ]
+ run_command(command)
diff --git a/tests/smoke_tests/test_mixed_precision.py b/tests/smoke_tests/test_mixed_precision.py
new file mode 100644
index 0000000..4e4637b
--- /dev/null
+++ b/tests/smoke_tests/test_mixed_precision.py
@@ -0,0 +1,47 @@
+from tests.helpers.run_command import run_command
+from tests.helpers.runif import RunIf
+
+
+@RunIf(amp_apex=True)
+def test_apex_01():
+ """Test mixed-precision level 01."""
+ 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_02():
+ """Test mixed-precision level 02."""
+ 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_03():
+ """Test mixed-precision level 03."""
+ 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)
diff --git a/tests/smoke_tests/test_sweeps.py b/tests/smoke_tests/test_sweeps.py
new file mode 100644
index 0000000..00f13d2
--- /dev/null
+++ b/tests/smoke_tests/test_sweeps.py
@@ -0,0 +1,32 @@
+from tests.helpers.run_command import run_command
+
+
+def test_default_sweep():
+ """Test default Hydra sweeper."""
+ command = [
+ "run.py",
+ "-m",
+ "datamodule.batch_size=64,128",
+ "model.lr=0.01,0.02",
+ "trainer=default",
+ "trainer.fast_dev_run=true",
+ ]
+ run_command(command)
+
+
+def test_optuna_sweep():
+ """Test Optuna sweeper."""
+ command = [
+ "run.py",
+ "-m",
+ "hparams_search=mnist_optuna",
+ "trainer=default",
+ "trainer.fast_dev_run=true",
+ ]
+ run_command(command)
+
+
+# def test_ax_sweep():
+# """Test Ax sweeper."""
+# command = ["run.py", "-m", "hparams_search=mnist_ax", "trainer.fast_dev_run=true"]
+# run_command(command)
diff --git a/tests/smoke_tests/test_wandb.py b/tests/smoke_tests/test_wandb.py
new file mode 100644
index 0000000..88041d6
--- /dev/null
+++ b/tests/smoke_tests/test_wandb.py
@@ -0,0 +1,39 @@
+import pytest
+
+from tests.helpers.run_command import run_command
+
+"""
+Use the following command to skip wandb tests:
+ pytest -k "not wandb"
+"""
+
+
+@pytest.mark.wandb
+def test_wandb_optuna_sweep():
+ """Test wandb logging with Optuna sweep."""
+ command = [
+ "run.py",
+ "-m",
+ "hparams_search=mnist_optuna",
+ "trainer=default",
+ "trainer.max_epochs=10",
+ "trainer.limit_train_batches=20",
+ "logger=wandb",
+ "logger.wandb.project=template-tests",
+ "logger.wandb.group=Optuna_SimpleDenseNet_MNIST",
+ "hydra.sweeper.n_trials=5",
+ ]
+ run_command(command)
+
+
+def test_wandb_callbacks():
+ """Test wandb callbacks."""
+ command = [
+ "run.py",
+ "trainer=default",
+ "trainer.max_epochs=3",
+ "logger=wandb",
+ "logger.wandb.project=template-tests",
+ "callbacks=wandb",
+ ]
+ run_command(command)
diff --git a/tests/sweep_tests.sh b/tests/sweep_tests.sh
deleted file mode 100644
index 9ef3cd9..0000000
--- a/tests/sweep_tests.sh
+++ /dev/null
@@ -1,33 +0,0 @@
-# !/bin/bash
-# Test hyperparameter sweeps
-
-# To execute:
-# bash tests/sweep_tests.sh
-
-# Method for printing test name
-echo() {
- termwidth="$(tput cols)"
- padding="$(printf '%0.1s' ={1..500})"
- printf '\e[33m%*.*s %s %*.*s\n\e[0m' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
-}
-
-# Make python hide warnings
-export PYTHONWARNINGS="ignore"
-
-
-echo "TEST 1"
-echo "Default hydra sweep with wandb logging"
-python run.py -m \
-+experiment=exp_example_simple \
-datamodule.batch_size=64,128 model.lr=0.001,0.003 \
-trainer.gpus=-1 trainer.max_epochs=2 \
-datamodule.num_workers=12 datamodule.pin_memory=True \
-logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"
-
-echo "TEST 2"
-echo "Optuna sweep with wandb logging"
-python run.py -m --config-name config_optuna.yaml \
-+experiment=exp_example_simple \
-trainer.gpus=-1 trainer.max_epochs=5 \
-datamodule.num_workers=12 datamodule.pin_memory=True \
-logger=wandb logger.wandb.project="env_tests" logger.wandb.group="Optuna_MNIST_SimpleDenseNet"
diff --git a/tests/unit_tests/__init__.py b/tests/unit_tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/tests/unit_tests/test_sth.py b/tests/unit_tests/test_sth.py
new file mode 100644
index 0000000..fc905a0
--- /dev/null
+++ b/tests/unit_tests/test_sth.py
@@ -0,0 +1,11 @@
+import pytest
+
+
+def test_something1():
+ """Some test description."""
+ assert True is True
+
+
+def test_something2():
+ """Some test description."""
+ assert 1 + 1 == 2