* add smoke tests implemented with pytest

* add sweep tests, wandb tests and mixed-precision tests

* update requirements.txt

* remove .autoenv.template file

* update readme
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-04-26 23:06:50 +02:00
1 parent 5cc767a595
commit e0293193f5
29 files changed
+571 -279

No files matched your search

-15
View File
@@ -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)"
+73 -45
View File
@@ -26,7 +26,7 @@ to your `README.md`.
<br><br>
-->
## Introduction
## :pushpin:&nbsp; Introduction
This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [src/train.py](src/train.py).
> 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))
<br>
@@ -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
```
</details>
@@ -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).<br>
Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).
```yaml
python run.py callbacks=default_callbacks
python run.py callbacks=default
```
</details>
@@ -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
```
</details>
@@ -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:&nbsp; 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)
<br>
@@ -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)).<br>
To support reproducibility: **WatchModelWithWandb**, **UploadCodeToWandbAsArtifact**, **UploadCheckpointsToWandbAsArtifact**.<br>
To provide examples of logging custom visualisations with callbacks only: **LogConfusionMatrixToWandb**, **LogF1PrecRecHeatmapToWandb**.<br>
To support reproducibility:
- **WatchModel**
- **UploadCodeAsArtifact**
- **UploadCheckpointsAsArtifact**
To provide examples of logging custom visualisations with callbacks only:
- **LogConfusionMatrix**
- **LogF1PrecRecHeatmap**
- **ImagePredictionLogger**
<br>
@@ -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
<details>
<summary><b>Write unit tests and smoke tests</b></summary>
Template comes with example tests implemented with pytest library. <br>
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).<br>
</details>
<details>
<summary><b>Use Docker</b></summary>
@@ -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
```
</details>
@@ -840,38 +875,23 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule
</details>
<details>
<summary><b>Write tests</b></summary>
(TODO)
</details>
<!--
<details>
<summary><b>Use Miniconda</b></summary>
I find myself often running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. You can easily modify the commands in the script for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).<br>
Keep in mind those aren't real tests - it's simply executing commands one after the other, after which you need to take a look in terminal if some of them crashed. It's always best if you write real unit tests for your code.<br>
To execute:
```yaml
bash tests/smoke_tests.sh
```
<summary><b>Use torchmetrics</b></summary>
</details>
-->
<br>
## Tricks
<details>
<summary><b>Automatic activation of virtual environment and tab completion</b></summary>
<summary><b>Automatic activation of virtual environment and tab completion when entering folder</b></summary>
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**<br>
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
</details>
@@ -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
</details>
@@ -970,6 +993,11 @@ This template was inspired by:
</details>
<!-- ## :star:&nbsp; Stargazers Over Time
[![Stargazers over time](https://starchart.cc/ashleve/lightning-hydra-template.svg)](https://starchart.cc/ashleve/lightning-hydra-template) -->
<br>
<br>
@@ -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
File renamed without changes.
@@ -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
+2 -2
View File
@@ -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
@@ -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
@@ -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
+5
View File
@@ -0,0 +1,5 @@
_target_: pytorch_lightning.Trainer
gpus: 4
accelerator: ddp
+21
View File
@@ -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
-49
View File
@@ -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'
+50
View File
@@ -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
@@ -9,4 +9,4 @@ max_epochs: 10
weights_summary: null
progress_bar_refresh_rate: 10
terminate_on_nan: False
# resume_from_checkpoint: null
+2 -2
View File
@@ -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
View File
Whitespace-only changes.
+3
View File
@@ -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.")
-45
View File
@@ -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
View File
Whitespace-only changes.
+34
View File
@@ -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")
+15
View File
@@ -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)
+120
View File
@@ -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
-75
View File
@@ -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
View File
Whitespace-only changes.
+103
View File
@@ -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)
+47
View File
@@ -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)
+32
View File
@@ -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)
+39
View File
@@ -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)
-33
View File
@@ -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"
View File
Whitespace-only changes.
+11
View File
@@ -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