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