Release/1.0 (#156)

* update to Hydra 1.1
* add bash folder with scripts for conda setup and run scheduling
* add saving seed in `log_hyperparameters()` method
* redesign Dockerfile to make it weight less
* add `test_after_training` parameter to config
* add inheritance to trainer configs
* remove forcing ddp-friendly configuration
* refactor tests
* remove conda_env_gpu.yaml
* remove default langage version from pre-commit config
* add mnist datamodule unit test
* rename test folder from 'smoke' to 'shell'
* remove wandb import from utils.py
* change 'use_artifact' to 'log_artifact' in wandb callbacks
* add rank zero decorator to wandb callbacks
* add dumping rich tree config to file
* get rid of `=` character in ckpt names
* update requirements.txt
* update LICENSE
* update README.md
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-07-21 03:37:45 +02:00
1 parent 362a4beebb
commit d45f604bc8
35 files changed
+398 -424

No files matched your search

-3
View File
@@ -1,6 +1,3 @@
default_language_version:
python: python3.8
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.4.0 rev: v3.4.0
+48 -14
View File
@@ -1,23 +1,57 @@
# Build: docker build -t project_name . # Build: sudo docker build -t <project_name> .
# Run: docker run -v $(pwd):/workspace/project --gpus all -it --rm project_name # Run: sudo docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name>
FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04
ENV CONDA_ENV_NAME=myenv
ENV PYTHON_VERSION=3.8
# Basic setup
RUN apt update
RUN apt install -y bash \
build-essential \
git \
curl \
ca-certificates \
wget \
&& rm -rf /var/lib/apt/lists
# Build from official Nvidia PyTorch image
# GPU-ready with Apex for mixed-precision support
# https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
# https://docs.nvidia.com/deeplearning/frameworks/support-matrix/
FROM nvcr.io/nvidia/pytorch:21.05-py3
# Set working directory # Set working directory
WORKDIR /workspace/project WORKDIR /workspace/project
# Copy files to create conda environment # Install Miniconda and create main env
COPY conda_env_gpu.yaml requirements.txt ./ ADD https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh miniconda3.sh
RUN /bin/bash miniconda3.sh -b -p /conda \
&& echo export PATH=/conda/bin:$PATH >> .bashrc \
&& rm miniconda3.sh
ENV PATH="/conda/bin:${PATH}"
RUN conda create -n ${CONDA_ENV_NAME} python=${PYTHON_VERSION}
# Create myenv # Switch to bash shell
RUN conda env create -f conda_env_gpu.yaml -n myenv \ SHELL ["/bin/bash", "-c"]
&& conda init bash
# Set myenv to default virtual environment
RUN echo "source activate myenv" >> ~/.bashrc # Install requirements
COPY requirements.txt ./
RUN source activate ${CONDA_ENV_NAME} \
&& pip install --no-cache-dir -r requirements.txt \
&& rm requirements.txt
# Uncomment this to install Apex for mixed-precision support
# RUN source activate ${CONDA_ENV_NAME} \
# && git clone https://github.com/NVIDIA/apex \
# && cd apex \
# && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ \
# && cd .. \
# && rm -r apex
# Set ${CONDA_ENV_NAME} to default virutal environment
RUN echo "source activate ${CONDA_ENV_NAME}" >> ~/.bashrc
+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2020 KINoAI Copyright (c) 2020 ashleve
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
+40 -40
View File
@@ -3,17 +3,17 @@
# Lightning-Hydra-Template # Lightning-Hydra-Template
<a href="https://pytorch.org/get-started/locally/"><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.6--3.9-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.8+-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-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.3+-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-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>
<!-- <a href="https://hub.docker.com/r/ashlev/lightning-hydra"><img alt="Docker" src="https://img.shields.io/badge/docker-257bd6?style=for-the-badge&logo=docker&logoColor=white"></a> --> <!-- <a href="https://hub.docker.com/r/ashlev/lightning-hydra"><img alt="Docker" src="https://img.shields.io/badge/docker-257bd6?style=for-the-badge&logo=docker&logoColor=white"></a> -->
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br> A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository. Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.
*Currently uses dev version of Hydra.<br>Suggestions are always welcome!* *Suggestions are always welcome!*
</div> </div>
<br><br> <br><br>
@@ -56,7 +56,7 @@ It makes your code neatly organized and provides lots of useful features, like a
- **Experiment Tracking**: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking)) - **Experiment Tracking**: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))
- **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))
- **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 smoke tests (see [#Tests](#tests)) - **Tests**: unit tests and command based tests (see [#Tests](#tests))
- **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features)) - **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features))
- **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>
@@ -65,6 +65,10 @@ It makes your code neatly organized and provides lots of useful features, like a
## Project Structure ## Project Structure
The directory structure of new project looks like this: The directory structure of new project looks like this:
``` ```
├── bash <- Bash scripts
│ ├── setup_conda.sh <- Setup conda environment
│ └── schedule.sh <- Schedule execution of many runs
│
├── configs <- Hydra configuration files ├── configs <- Hydra configuration files
│ ├── callbacks <- Callbacks configs │ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs │ ├── datamodule <- Datamodule configs
@@ -86,8 +90,9 @@ The directory structure of new project looks like this:
│ `1.0-jqp-initial-data-exploration.ipynb`. │ `1.0-jqp-initial-data-exploration.ipynb`.
│ │
├── tests <- Tests of any kind ├── tests <- Tests of any kind
│ ├── smoke │ ├── helpers <- A couple of testing utilities
│ └── unit │ ├── shell <- Shell/command based tests
│ └── unit <- Unit tests
│ │
├── src ├── src
│ ├── callbacks <- Lightning callbacks │ ├── callbacks <- Lightning callbacks
@@ -97,15 +102,14 @@ The directory structure of new project looks like this:
│ │ │ │
│ └── train.py <- Training pipeline │ └── train.py <- Training pipeline
│ │
├── run.py <- Run any pipeline with chosen experiment configuration ├── run.py <- Run pipeline with chosen experiment configuration
│ │
├── .env.example <- Template of the file for storing private environment variables ├── .env.example <- Template of the file for storing private environment variables
├── .gitignore <- List of files/folders ignored by git ├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting ├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── conda_env_gpu.yaml <- File for installing conda environment ├── setup.cfg <- Configurations of linters and pytest
├── Dockerfile <- File for building docker container ├── Dockerfile <- File for building docker container
├── requirements.txt <- File for installing python dependencies ├── requirements.txt <- File for installing python dependencies
├── setup.cgf <- Configurations of linters and pytest
├── LICENSE ├── LICENSE
└── README.md └── README.md
``` ```
@@ -119,8 +123,7 @@ 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
conda env create -f conda_env_gpu.yaml -n myenv bash bash/setup_conda.sh
conda activate myenv
# install requirements # install requirements
pip install -r requirements.txt pip install -r requirements.txt
@@ -363,8 +366,7 @@ python run.py -m 'experiment=glob(*)'
## 🐳&nbsp;&nbsp;Docker ## 🐳&nbsp;&nbsp;Docker
I recommend the official [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags). First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support. <br>
To build the container from provided Dockerfile use: To build the container from provided Dockerfile use:
```bash ```bash
docker build -t <project_name> . docker build -t <project_name> .
@@ -373,8 +375,7 @@ To mount the project to the container use:
```bash ```bash
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.
Others dockerfiles are provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). You can use them as a starting point for building more complicated images.
<br><br><br> <br><br><br>
@@ -389,7 +390,7 @@ Have a question? Found a bug? Missing a specific feature? Ran into a problem? Fe
### How To Get Started ### How To Get Started
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) - 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) - Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/) and [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/)
<br> <br>
@@ -426,7 +427,7 @@ It also specifies everything that shouldn't be managed by experiment configurati
```yaml ```yaml
# specify here default training configuration # specify here default training configuration
defaults: defaults:
- trainer: minimal.yaml - trainer: default.yaml
- model: mnist_model.yaml - model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml - datamodule: mnist_datamodule.yaml
- callbacks: default.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
@@ -455,7 +456,6 @@ print_config: True
# disable python warnings if they annoy you # disable python warnings if they annoy you
ignore_warnings: True ignore_warnings: True
``` ```
</details> </details>
@@ -473,7 +473,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 /trainer: minimal.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
- override /callbacks: default.yaml - override /callbacks: default.yaml
@@ -760,12 +760,12 @@ To execute them simply run:
pytest pytest
# run tests from specific file # run tests from specific file
pytest tests/smoke_tests/test_commands.py pytest tests/shell/test_basic_commands.py
# run all tests except the ones marked as slow # run all tests except the ones marked as slow
pytest -k "not slow" pytest -k "not slow"
``` ```
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 tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests](tests/smoke_tests) folder. 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 tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/shell](tests/shell) 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). 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><br> <br><br>
@@ -803,13 +803,10 @@ python run.py trainer.gpus=4 +trainer.accelerator="ddp"
### Extra Features ### Extra Features
List of extra utilities available in the template: List of extra utilities available in the template:
- loading environment variables from [.env](.env.template) file - loading environment variables from [.env](.env.example) file
- pretty printing config with [Rich](https://github.com/willmcgugan/rich) library - pretty printing config with [Rich](https://github.com/willmcgugan/rich) library
- disabling python warnings - disabling python warnings
- easier access to debug mode - debug mode
- forcing debug friendly configuration
- forcing multi-gpu friendly configuration
- method for logging hyperparameters to loggers
<!-- - (TODO) resuming latest run --> <!-- - (TODO) resuming latest run -->
You can easily remove any of those by modifying [run.py](run.py) and [src/train.py](src/train.py). You can easily remove any of those by modifying [run.py](run.py) and [src/train.py](src/train.py).
@@ -840,10 +837,9 @@ Example installation:
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh
``` ```
Create environment from file provided in the template: Create environment using bash script provided in the template:
```yaml ```yaml
conda env create -f conda_env_gpu.yaml -n myenv bash bash/setup_conda.sh
conda activate myenv
``` ```
</details> </details>
@@ -861,7 +857,7 @@ Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
pre-commit install pre-commit install
``` ```
After that your code will be automatically reformatted on every new commit.<br> After that your code will be automatically reformatted on every new commit.<br>
Currently template contains configurations of **Black** (python code formatting) and **Isort** (python import sorting). You can exclude chosen files from automatic formatting, by modifying [.pre-commit-config.yaml](.pre-commit-config.yaml).<br> Currently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **flake8** (python code analysis) and **prettier** (yaml formating). <br>
To reformat all files in the project use command: To reformat all files in the project use command:
```yaml ```yaml
@@ -875,7 +871,7 @@ pre-commit run -a
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.<br> System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.<br>
Template contains `.env.template` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore). Template contains `.env.example` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore).
You should use it for storing environment variables like this: You should use it for storing environment variables like this:
```yaml ```yaml
MY_VAR=/home/user/my_system_path MY_VAR=/home/user/my_system_path
@@ -1045,6 +1041,13 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule
``` ```
</details> </details>
<!-- <details>
<summary><b>Make notebooks independent from other files</b></summary>
It's a good practice for jupyter notebooks to be portable. Try to make them independent from src files. If you need to access external code, try to embed it inside the notebook.
</details> -->
<br> <br>
@@ -1112,7 +1115,7 @@ from omegaconf import OmegaConf
# you can place this snippet in your datamodule __init__() # you can place this snippet in your datamodule __init__()
resolver_name = "datamodule" resolver_name = "datamodule"
OmegaConf.register_resolver( OmegaConf.register_new_resolver(
resolver_name, resolver_name,
lambda name: getattr(self, name), lambda name: getattr(self, name),
use_cache=False use_cache=False
@@ -1160,14 +1163,12 @@ This template was inspired by:
</details> </details>
<details> <!-- <details>
<summary><b>List of repositories using this template</b></summary> <summary><b>List of repositories using this template</b></summary>
- [ashleve/graph_classification](https://github.com/ashleve/graph_classification) - benchmarking graph neural network architectures on graph classification datasets (Open Graph Benchmarks and image classification from superpixels) - [ashleve/graph_classification](https://github.com/ashleve/graph_classification) - benchmarking graph neural network architectures on graph classification datasets (Open Graph Benchmarks and image classification from superpixels)
> if you'd like to share your project and add it to the list, feel free to make a PR! </details> -->
</details>
<!-- ## :star:&nbsp; Stargazers Over Time <!-- ## :star:&nbsp; Stargazers Over Time
@@ -1192,7 +1193,7 @@ This template was inspired by:
# Your Project Name # Your Project Name
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a> <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch&logoColor=white"></a>
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5"></a> <a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white"></a>
<a href="https://hydra.cc/"><img alt="Config: Hydra" src="https://img.shields.io/badge/Config-Hydra-89b8cd"></a> <a href="https://hydra.cc/"><img alt="Config: Hydra" src="https://img.shields.io/badge/Config-Hydra-89b8cd"></a>
<a href="https://github.com/ashleve/lightning-hydra-template"><img alt="Template" src="https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=gray"></a><br> <a href="https://github.com/ashleve/lightning-hydra-template"><img alt="Template" src="https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=gray"></a><br>
[![Paper](http://img.shields.io/badge/paper-arxiv.1001.2234-B31B1B.svg)](https://www.nature.com/articles/nature14539) [![Paper](http://img.shields.io/badge/paper-arxiv.1001.2234-B31B1B.svg)](https://www.nature.com/articles/nature14539)
@@ -1211,8 +1212,7 @@ 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
conda env create -f conda_env_gpu.yaml -n myenv bash bash/setup_conda.sh
conda activate myenv
# install requirements # install requirements
pip install -r requirements.txt pip install -r requirements.txt
+9
View File
@@ -0,0 +1,9 @@
#!/bin/bash
# Shedule execution of many runs
# Run from root folder with: bash bash/schedule.sh
python run.py trainer.max_epochs=5
python run.py trainer.max_epochs=5 experiment=example_simple
python run.py trainer.max_epochs=5 experiment=example_full
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
# Run from root folder with: bash bash/setup_conda.sh
# check if conda is installed
if ! command -v conda &> /dev/null
then
echo "The 'conda' command could not be found. Exiting..."
exit
fi
# This line is needed for enabling conda env activation
source ~/miniconda3/etc/profile.d/conda.sh
# Configure conda env
read -rp "Enter environment name: " env_name
read -rp "Enter python version (recommended '3.8') " python_version
read -rp "Enter cuda version (recommended '10.2', or 'none' for CPU only): " cuda_version
read -rp "Enter pytorch version (recommended '1.8.1'): " pytorch_version
# Create conda env
conda create -y -n "$env_name" python="$python_version"
conda activate "$env_name"
# Install pytorch
if [ "$cuda_version" == "none" ]; then
conda install -y pytorch=$pytorch_version torchvision torchaudio cpuonly -c pytorch
else
conda install -y pytorch=$pytorch_version torchvision torchaudio cudatoolkit=$cuda_version -c pytorch
fi
echo "\n"
echo "To activate this environment, use:"
echo "conda activate $env_name"
-14
View File
@@ -1,14 +0,0 @@
name: myenv
channels:
- pytorch
- conda-forge
dependencies:
- python=3.8
- pip
- cudatoolkit
- pytorch=1.8.1
- torchvision=0.9.1
- pip:
- -r requirements.txt
+4 -3
View File
@@ -1,16 +1,17 @@
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"
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
mode: "max" # can be "max" or "min"
verbose: False verbose: False
dirpath: "checkpoints/" dirpath: "checkpoints/"
filename: "{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" # 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
patience: 100 # how many epochs of not improving until training stops
mode: "max" # can be "max" or "min" mode: "max" # can be "max" or "min"
patience: 100 # how many 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
+5 -1
View File
@@ -2,7 +2,7 @@
# specify here default training configuration # specify here default training configuration
defaults: defaults:
- trainer: minimal.yaml - trainer: default.yaml
- model: mnist_model.yaml - model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml - datamodule: mnist_datamodule.yaml
- callbacks: default.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
@@ -37,3 +37,7 @@ 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
# lightning chooses best model based on metric specified in checkpoint callback
test_after_training: True
-1
View File
@@ -30,7 +30,6 @@ model:
_target_: src.models.mnist_model.MNISTLitModel _target_: src.models.mnist_model.MNISTLitModel
lr: 0.001 lr: 0.001
weight_decay: 0.00005 weight_decay: 0.00005
architecture: SimpleDenseNet
input_size: 784 input_size: 784
lin1_size: 256 lin1_size: 256
lin2_size: 256 lin2_size: 256
+1 -1
View File
@@ -4,7 +4,7 @@
# python run.py experiment=example_simple.yaml # python run.py experiment=example_simple.yaml
defaults: defaults:
- override /trainer: minimal.yaml # choose trainer from 'configs/trainer/' - override /trainer: default.yaml # choose trainer from 'configs/trainer/'
- override /model: mnist_model.yaml - override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml - override /datamodule: mnist_datamodule.yaml
- override /callbacks: default.yaml - override /callbacks: default.yaml
+1 -1
View File
@@ -2,7 +2,7 @@
neptune: neptune:
_target_: pytorch_lightning.loggers.neptune.NeptuneLogger _target_: pytorch_lightning.loggers.neptune.NeptuneLogger
api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is laoded from environment variable api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is loaded from environment variable
project_name: your_name/template-tests project_name: your_name/template-tests
close_after_fit: True close_after_fit: True
offline_mode: False offline_mode: False
+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
+2 -1
View File
@@ -1,4 +1,5 @@
_target_: pytorch_lightning.Trainer defaults:
- default.yaml
gpus: 4 gpus: 4
accelerator: ddp accelerator: ddp
+3 -2
View File
@@ -1,4 +1,5 @@
_target_: pytorch_lightning.Trainer defaults:
- default.yaml
gpus: 0 gpus: 0
@@ -11,8 +12,8 @@ weights_summary: null
profiler: null profiler: null
# debugs # debugs
num_sanity_val_steps: 2
fast_dev_run: False fast_dev_run: False
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
+7 -46
View File
@@ -1,50 +1,11 @@
_target_: pytorch_lightning.Trainer _target_: pytorch_lightning.Trainer
# default values for all trainer parameters # set `1` to train on GPU, `0` to train on CPU only
checkpoint_callback: True gpus: 0
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 min_epochs: 1
max_steps: null max_epochs: 10
min_steps: null
limit_train_batches: 1.0 weights_summary: null
limit_val_batches: 1.0 progress_bar_refresh_rate: 5
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 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
-11
View File
@@ -1,11 +0,0 @@
_target_: pytorch_lightning.Trainer
# set `1` to train on GPU, `0` to train on CPU only
gpus: 0
min_epochs: 1
max_epochs: 10
weights_summary: null
progress_bar_refresh_rate: 10
# resume_from_checkpoint: null
+22 -24
View File
@@ -1,37 +1,35 @@
# --------- pytorch --------- # # --------- pytorch --------- #
torch==1.8.1 torch>=1.8.1
torchvision==0.9.1 torchvision>=0.9.1
pytorch-lightning>=1.3.2 pytorch-lightning>=1.3.8
torchmetrics>=0.3.2
# --------- hydra --------- # # --------- hydra --------- #
hydra-core==1.1.0.rc1 hydra-core==1.1.0
hydra-colorlog==1.1.0.dev1 hydra-colorlog==1.1.0
hydra-optuna-sweeper==1.1.0.dev2 hydra-optuna-sweeper==1.1.0
# hydra-ax-sweeper==1.1.0 # hydra-ax-sweeper
# hydra-ray-launcher==0.1.2 # hydra-ray-launcher
# hydra-submitit-launcher==1.1.0 # hydra-submitit-launcher
# --------- loggers --------- # # --------- loggers --------- #
wandb>=0.10.30 wandb
# neptune-client # neptune-client
# mlflow # mlflow
# comet-ml # comet-ml
# torch_tb_profiler # torch_tb_profiler
# --------- linters --------- # # --------- linters --------- #
pre-commit pre-commit # hooks for applying linters on commit
black black # code formatting
isort isort # import sorting
flake8 flake8 # code analysis
# --------- others --------- # # --------- others --------- #
jupyterlab python-dotenv # loading env variables from .env file
python-dotenv rich # beautiful text formatting in terminal
rich pytest # tests
pytest sh # for running bash commands in some tests
sh scikit-learn # used in some callbacks
scikit-learn seaborn # used in some callbacks
seaborn jupyterlab # better jupyter notebooks
pudb pudb # debugger
# dvc
-1
View File
@@ -19,7 +19,6 @@ def main(config: DictConfig):
# - disabling python warnings # - disabling python warnings
# - easier access to debug mode # - easier access to debug mode
# - forcing debug friendly configuration # - forcing debug friendly configuration
# - forcing multi-gpu friendly configuration
# You can safely get rid of this line if you don't want those # You can safely get rid of this line if you don't want those
utils.extras(config) utils.extras(config)
+3
View File
@@ -21,6 +21,8 @@ ignore =
F401 # Module imported but unused F401 # Module imported but unused
W504 # Line break occurred after a binary operator W504 # Line break occurred after a binary operator
F841 # Local variable name is assigned to but never used F841 # Local variable name is assigned to but never used
F403 # from module import *
E501 # Line too long
exclude = exclude =
.git .git
__pycache__ __pycache__
@@ -41,3 +43,4 @@ addopts =
--doctest-modules --doctest-modules
filterwarnings = filterwarnings =
ignore::DeprecationWarning ignore::DeprecationWarning
ignore::UserWarning
+6 -2
View File
@@ -8,6 +8,7 @@ import torch
import wandb import wandb
from pytorch_lightning import Callback, Trainer from pytorch_lightning import Callback, Trainer
from pytorch_lightning.loggers import LoggerCollection, WandbLogger from pytorch_lightning.loggers import LoggerCollection, WandbLogger
from pytorch_lightning.utilities import rank_zero_only
from sklearn import metrics from sklearn import metrics
from sklearn.metrics import f1_score, precision_score, recall_score from sklearn.metrics import f1_score, precision_score, recall_score
@@ -35,6 +36,7 @@ class WatchModel(Callback):
self.log = log self.log = log
self.log_freq = log_freq self.log_freq = log_freq
@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)
@@ -46,6 +48,7 @@ class UploadCodeAsArtifact(Callback):
def __init__(self, code_dir: str): def __init__(self, code_dir: str):
self.code_dir = code_dir self.code_dir = code_dir
@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)
experiment = logger.experiment experiment = logger.experiment
@@ -54,7 +57,7 @@ class UploadCodeAsArtifact(Callback):
for path in glob.glob(os.path.join(self.code_dir, "**/*.py"), recursive=True): for path in glob.glob(os.path.join(self.code_dir, "**/*.py"), recursive=True):
code.add_file(path) code.add_file(path)
experiment.use_artifact(code) experiment.log_artifact(code)
class UploadCheckpointsAsArtifact(Callback): class UploadCheckpointsAsArtifact(Callback):
@@ -64,6 +67,7 @@ class UploadCheckpointsAsArtifact(Callback):
self.ckpt_dir = ckpt_dir self.ckpt_dir = ckpt_dir
self.upload_best_only = upload_best_only self.upload_best_only = upload_best_only
@rank_zero_only
def on_train_end(self, trainer, pl_module): def on_train_end(self, trainer, pl_module):
logger = get_wandb_logger(trainer=trainer) logger = get_wandb_logger(trainer=trainer)
experiment = logger.experiment experiment = logger.experiment
@@ -76,7 +80,7 @@ class UploadCheckpointsAsArtifact(Callback):
for path in glob.glob(os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True): for path in glob.glob(os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True):
ckpts.add_file(path) ckpts.add_file(path)
experiment.use_artifact(ckpts) experiment.log_artifact(ckpts)
class LogConfusionMatrix(Callback): class LogConfusionMatrix(Callback):
+1 -2
View File
@@ -18,7 +18,7 @@ class MNISTDataModule(LightningDataModule):
- test_dataloader (the test dataloader(s)) - test_dataloader (the test dataloader(s))
This allows you to share a full dataset without explaining how to download, This allows you to share a full dataset without explaining how to download,
split, transform and process the data split, transform and process the data.
Read the docs: Read the docs:
https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html https://pytorch-lightning.readthedocs.io/en/latest/extensions/datamodules.html
@@ -31,7 +31,6 @@ class MNISTDataModule(LightningDataModule):
batch_size: int = 64, batch_size: int = 64,
num_workers: int = 0, num_workers: int = 0,
pin_memory: bool = False, pin_memory: bool = False,
**kwargs,
): ):
super().__init__() super().__init__()
-1
View File
@@ -31,7 +31,6 @@ class MNISTLitModel(LightningModule):
output_size: int = 10, output_size: int = 10,
lr: float = 0.001, lr: float = 0.001,
weight_decay: float = 0.0005, weight_decay: float = 0.0005,
**kwargs
): ):
super().__init__() super().__init__()
+9 -9
View File
@@ -31,31 +31,31 @@ def train(config: DictConfig) -> Optional[float]:
if "seed" in config: if "seed" in config:
seed_everything(config.seed, workers=True) seed_everything(config.seed, workers=True)
# Init Lightning datamodule # Init lightning datamodule
log.info(f"Instantiating datamodule <{config.datamodule._target_}>") log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule) datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
# Init Lightning model # Init lightning model
log.info(f"Instantiating model <{config.model._target_}>") log.info(f"Instantiating model <{config.model._target_}>")
model: LightningModule = hydra.utils.instantiate(config.model) model: LightningModule = hydra.utils.instantiate(config.model)
# Init Lightning callbacks # Init lightning callbacks
callbacks: List[Callback] = [] callbacks: List[Callback] = []
if "callbacks" in config: if "callbacks" in config:
for _, cb_conf in config["callbacks"].items(): for _, cb_conf in config.callbacks.items():
if "_target_" in cb_conf: if "_target_" in cb_conf:
log.info(f"Instantiating callback <{cb_conf._target_}>") log.info(f"Instantiating callback <{cb_conf._target_}>")
callbacks.append(hydra.utils.instantiate(cb_conf)) callbacks.append(hydra.utils.instantiate(cb_conf))
# Init Lightning loggers # Init lightning loggers
logger: List[LightningLoggerBase] = [] logger: List[LightningLoggerBase] = []
if "logger" in config: if "logger" in config:
for _, lg_conf in config["logger"].items(): for _, lg_conf in config.logger.items():
if "_target_" in lg_conf: if "_target_" in lg_conf:
log.info(f"Instantiating logger <{lg_conf._target_}>") log.info(f"Instantiating logger <{lg_conf._target_}>")
logger.append(hydra.utils.instantiate(lg_conf)) logger.append(hydra.utils.instantiate(lg_conf))
# Init Lightning trainer # Init lightning trainer
log.info(f"Instantiating trainer <{config.trainer._target_}>") log.info(f"Instantiating trainer <{config.trainer._target_}>")
trainer: Trainer = hydra.utils.instantiate( trainer: Trainer = hydra.utils.instantiate(
config.trainer, callbacks=callbacks, logger=logger, _convert_="partial" config.trainer, callbacks=callbacks, logger=logger, _convert_="partial"
@@ -76,8 +76,8 @@ 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 after training # Evaluate model on test set, using the best model achieved during training
if 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()
+10 -14
View File
@@ -1,13 +1,12 @@
import logging import logging
import os
import warnings import warnings
from typing import List, Sequence from typing import List, Sequence
import pytorch_lightning as pl import pytorch_lightning as pl
import rich.syntax import rich.syntax
import rich.tree import rich.tree
import wandb
from omegaconf import DictConfig, OmegaConf from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.loggers.wandb import WandbLogger
from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.utilities import rank_zero_only
@@ -30,7 +29,6 @@ def extras(config: DictConfig) -> None:
- disabling warnings - disabling warnings
- easier access to debug mode - easier access to debug mode
- forcing debug friendly configuration - forcing debug friendly configuration
- forcing multi-gpu friendly configuration
Modifies DictConfig in place. Modifies DictConfig in place.
@@ -64,15 +62,6 @@ def extras(config: DictConfig) -> None:
if config.datamodule.get("num_workers"): if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0 config.datamodule.num_workers = 0
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
accelerator = config.trainer.get("accelerator")
if accelerator in ["ddp", "ddp_spawn", "dp", "ddp2"]:
log.info(f"Forcing ddp friendly configuration! <config.trainer.accelerator={accelerator}>")
if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0
if config.datamodule.get("pin_memory"):
config.datamodule.pin_memory = False
# disable adding new keys to config # disable adding new keys to config
OmegaConf.set_struct(config, True) OmegaConf.set_struct(config, True)
@@ -100,7 +89,7 @@ def print_config(
""" """
style = "dim" style = "dim"
tree = rich.tree.Tree(":gear: CONFIG", style=style, guide_style=style) tree = rich.tree.Tree("CONFIG", style=style, guide_style=style)
for field in fields: for field in fields:
branch = tree.add(field, style=style, guide_style=style) branch = tree.add(field, style=style, guide_style=style)
@@ -114,6 +103,9 @@ def print_config(
rich.print(tree) rich.print(tree)
with open("config_tree.txt", "w") as fp:
rich.print(tree, file=fp)
def empty(*args, **kwargs): def empty(*args, **kwargs):
pass pass
@@ -140,6 +132,8 @@ 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:
hparams["seed"] = config["seed"]
if "callbacks" in config: if "callbacks" in config:
hparams["callbacks"] = config["callbacks"] hparams["callbacks"] = config["callbacks"]
@@ -173,5 +167,7 @@ def finish(
# without this sweeps with wandb logger might crash! # without this sweeps with wandb logger might crash!
for lg in logger: for lg in logger:
if isinstance(lg, WandbLogger): if isinstance(lg, pl.loggers.wandb.WandbLogger):
import wandb
wandb.finish() wandb.finish()
-3
View File
@@ -18,9 +18,6 @@ def _module_available(module_path: str) -> bool:
""" """
try: try:
return find_spec(module_path) is not None return find_spec(module_path) is not None
except AttributeError:
# Python 3.6
return False
except ModuleNotFoundError: except ModuleNotFoundError:
# Python 3.7+ # Python 3.7+
return False return False
File renamed without changes.
+58
View File
@@ -0,0 +1,58 @@
import pytest
from tests.helpers.run_command import run_command
from tests.helpers.runif import RunIf
def test_fast_dev_run():
"""Run 1 train, val, test batch."""
command = ["run.py", "++trainer.fast_dev_run=true"]
run_command(command)
def test_default_cpu():
"""Test default config on CPU."""
command = ["run.py", "++trainer.max_epochs=1", "++trainer.gpus=0"]
run_command(command)
# use RunIf to skip execution of some tests, e.g. when no gpus are available
@RunIf(min_gpus=1)
def test_default_gpu():
"""Test default config on GPU."""
command = [
"run.py",
"++trainer.max_epochs=1",
"++trainer.gpus=1",
"++datamodule.pin_memory=True",
]
run_command(command)
@pytest.mark.slow
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.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_double_validation_loop():
"""Train 1 epoch with validation loop twice per epoch."""
command = [
"run.py",
"++trainer.max_epochs=1",
"++trainer.val_check_interval=0.5",
]
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_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)
@@ -17,7 +17,7 @@ def test_default_sweep():
"datamodule.batch_size=64,128", "datamodule.batch_size=64,128",
"model.lr=0.01,0.02", "model.lr=0.01,0.02",
"trainer=default", "trainer=default",
"trainer.fast_dev_run=true", "++trainer.fast_dev_run=true",
] ]
run_command(command) run_command(command)
@@ -30,14 +30,6 @@ def test_optuna_sweep():
"-m", "-m",
"hparams_search=mnist_optuna", "hparams_search=mnist_optuna",
"trainer=default", "trainer=default",
"trainer.fast_dev_run=true", "++trainer.fast_dev_run=true",
] ]
run_command(command) run_command(command)
@pytest.mark.skip(reason="TODO: Add Ax sweep config.")
@pytest.mark.slow
def test_ax_sweep():
"""Test Ax sweeper."""
command = ["run.py", "-m", "hparams_search=mnist_ax", "trainer.fast_dev_run=true"]
run_command(command)
-106
View File
@@ -1,106 +0,0 @@
import pytest
from tests.helpers.run_command import run_command
from tests.helpers.runif import RunIf
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_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)
@pytest.mark.slow
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
@@ -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_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)
-40
View File
@@ -1,40 +0,0 @@
import pytest
from tests.helpers.run_command import run_command
"""
Use the following command to skip slow tests:
pytest -k "not slow"
"""
# @pytest.mark.slow
# 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)
# @pytest.mark.slow
# 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)
+36
View File
@@ -0,0 +1,36 @@
import os
import pytest
import torch
from src.datamodules.mnist_datamodule import MNISTDataModule
@pytest.mark.parametrize("batch_size", [32, 128])
def test_mnist_datamodule(batch_size):
datamodule = MNISTDataModule(batch_size=batch_size)
datamodule.prepare_data()
assert not datamodule.data_train and not datamodule.data_val and not datamodule.data_test
assert os.path.exists(os.path.join("data", "MNIST"))
assert os.path.exists(os.path.join("data", "MNIST", "raw"))
datamodule.setup()
assert datamodule.data_train and datamodule.data_val and datamodule.data_test
assert (
len(datamodule.data_train) + len(datamodule.data_val) + len(datamodule.data_test) == 70_000
)
assert datamodule.train_dataloader()
assert datamodule.val_dataloader()
assert datamodule.test_dataloader()
batch = next(iter(datamodule.train_dataloader()))
x, y = batch
assert len(x) == batch_size
assert len(y) == batch_size
assert x.dtype == torch.float32
assert y.dtype == torch.int64
-26
View File
@@ -1,26 +0,0 @@
import pytest
from tests.helpers.runif import RunIf
def test_something1():
"""Some test description."""
assert True is True
def test_something2():
"""Some test description."""
assert 1 + 1 == 2
@pytest.mark.parametrize("arg1", [0.5, 1.0, 2.0])
def test_something3(arg1: float):
"""Some test description."""
assert arg1 > 0
# use RunIf to skip execution of some tests, e.g. when not on windows or when no gpus are available
@RunIf(skip_windows=True, min_gpus=1)
def test_something4():
"""Some test description."""
assert True is True