* 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
30 files changed
+572 -280

No files matched your search

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