* remove conda_env_cpu

* remove setup.py

* optimize tab completion by nesting imports

* add .env

* fix rich printing bug

* general improvements

* update readme
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-03-15 16:55:06 +01:00
1 parent 5f1c85e9bf
commit d571a4e2c2
22 files changed
+252 -220

No files matched your search

+1
View File
@@ -0,0 +1 @@
export MY_VAR="/home/user/my_system_path"
+6 -1
View File
@@ -3,6 +3,8 @@
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
.idea/
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
@@ -225,6 +227,9 @@ ipython_config.py
# Remove previous ipynb_checkpoints
# git rm -r .ipynb_checkpoints/
.idea/
# Template specific
data/
logs/
.env.vars
+2 -2
View File
@@ -19,7 +19,7 @@ repos:
rev: 20.8b1
hooks:
- id: black
# args: [--force-exclude, train.py]
# args: [--force-exclude, src/train.py]
# Isort (import sorting)
- repo: https://github.com/PyCQA/isort
@@ -28,7 +28,7 @@ repos:
- id: isort
# profiles: https://pycqa.github.io/isort/docs/configuration/profiles/
# other flags: https://pycqa.github.io/isort/docs/configuration/options/
args: [--profile, black, --skip, train.py, --filter-files]
args: [--profile, black, --skip, src/train.py, --filter-files]
# files: "src/.*"
# MyPy (static type checking)
+134 -81
View File
@@ -35,6 +35,7 @@ to your `README.md`.
- [Workflow](#workflow)
- [Logs](#logs)
- [Experiment Tracking](#experiment-tracking)
- [Inference](#inference)
- [Callbacks](#callbacks)
- [Best Practices](#best-practices)
- [Tricks](#tricks)
@@ -43,7 +44,7 @@ to your `README.md`.
## Introduction
This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [train.py](train.py).
This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [src/train.py](src/train.py).
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
@@ -66,7 +67,7 @@ It makes your code neatly organized and provides lots of useful features, like a
## Main Ideas Of This Template
- Predefined Structure: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure))
- Rapid Experimentation: thanks to automating pipeline with config files and hydra command line superpowers
- Little Boilerplate: so pipeline can be easily modified (see [train.py](train.py))
- Little Boilerplate: so pipeline can be easily modified (see [src/train.py](src/train.py))
- Main Configuration: main config file specifies default training configuration (see [#Main Project Configuration](#main-project-configuration))
- Experiment Configurations: stored in a separate folder, they can be composed out of smaller configs, override chosen parameters or define everything from scratch (see [#Experiment Configuration](#experiment-configuration))
- Experiment Tracking: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))
@@ -99,9 +100,6 @@ The directory structure of new project looks like this:
├── notebooks <- Jupyter notebooks
│
├── tests <- Tests of any kind
│ ├── smoke_tests.sh <- A couple of quick experiments to test if your model
│ │ doesn't crash under different training conditions
│ └── ...
│
├── src
│ ├── architectures <- PyTorch model architectures
@@ -110,20 +108,21 @@ The directory structure of new project looks like this:
│ ├── datasets <- PyTorch datasets
│ ├── models <- PyTorch Lightning models
│ ├── transforms <- Data transformations
│ └── utils <- Utility scripts
│ ├── inference_example.py <- Example of inference with trained model
│ └── template_utils.py <- Some extra template utilities
│ ├── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
│ │ └── template_utils.py <- Some extra template utilities
│ │
│ └── train.py <- Contains training pipeline
│
├── train.py <- Train model with chosen experiment configuration
├── run.py <- Run training with chosen experiment configuration
│
├── .gitignore
├── .env <- File for storing environment variables
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of hooks for automatic code formatting
├── LICENSE
├── README.md
├── conda_env_gpu.yaml <- File for installing conda env for GPU
├── conda_env_cpu.yaml <- File for installing conda env for CPU
├── conda_env_gpu.yaml <- File for installing conda environment
├── requirements.txt <- File for installing python dependencies
└── setup.py <- File for installing project as a package
├── LICENSE
└── README.md
```
<br>
@@ -142,7 +141,8 @@ conda activate testenv
pip install -r requirements.txt
```
When running `python train.py` you should see something like this:
Template contains example with MNIST classification.<br>
When running `python run.py` you should see something like this:
<div align="center">
![](https://github.com/hobogalaxy/lightning-hydra-template/blob/resources/teminal.png)
@@ -157,11 +157,11 @@ When running `python train.py` you should see something like this:
> *Hydra allows you to overwrite any parameter defined in your config, without writing any code!*
```yaml
python train.py trainer.max_epochs=20 optimizer.lr=1e-4
python run.py trainer.max_epochs=20 optimizer.lr=1e-4
```
> *You can also add new parameters with `+` sign.*
```yaml
python train.py +trainer.new_param="uwu"
python run.py +trainer.new_param="uwu"
```
@@ -171,22 +171,22 @@ python train.py +trainer.new_param="uwu"
<details>
<summary>Train on CPU, GPU, TPU or even with DDP and mixed precision</summary>
> *PyTorch Lightning makes it really easy to train your models on different hardware!*
> *PyTorch Lightning makes it really easy to train your models on different hardware.*
```yaml
# train on CPU
python train.py trainer.gpus=0
python run.py trainer.gpus=0
# train on 1 GPU
python train.py trainer.gpus=1
python run.py trainer.gpus=1
# train on TPU
python train.py +trainer.tpu_cores=8
python run.py +trainer.tpu_cores=8
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python train.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
# train with mixed precision
python train.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16
python run.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16
```
</details>
@@ -206,7 +206,7 @@ wandb:
```yaml
# train model with Weights&Biases
# link to wandb dashboard should appear in the terminal
python train.py logger=wandb
python run.py logger=wandb
```
> **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**
@@ -218,7 +218,7 @@ python train.py logger=wandb
> Experiment configurations are placed in folder `configs/experiment/`.
```yaml
python train.py +experiment=exp_example_simple
python run.py +experiment=exp_example_simple
```
</details>
@@ -230,7 +230,7 @@ python train.py +experiment=exp_example_simple
> *Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).<br>
Callbacks configurations are placed in `configs/callbacks/`.*
```yaml
python train.py callbacks=default_callbacks
python run.py callbacks=default_callbacks
```
</details>
@@ -242,16 +242,16 @@ python train.py callbacks=default_callbacks
> *PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).*
```yaml
# gradient clipping may be enabled to avoid exploding gradients
python train.py +trainer.gradient_clip_val=0.5
python run.py +trainer.gradient_clip_val=0.5
# stochastic weight averaging can make your models generalize better
python train.py +trainer.stochastic_weight_avg=True
python run.py +trainer.stochastic_weight_avg=True
# run validation loop 4 times during a training epoch
python train.py +trainer.val_check_interval=0.25
python run.py +trainer.val_check_interval=0.25
# accumulate gradients
python train.py +trainer.accumulate_grad_batches=10
python run.py +trainer.accumulate_grad_batches=10
```
@@ -263,19 +263,19 @@ python train.py +trainer.accumulate_grad_batches=10
```yaml
# run 1 train, val and test loop, using only 1 batch
python train.py debug=true
python run.py debug=true
# print full weight summary of all PyTorch modules
python train.py trainer.weights_summary="full"
python run.py trainer.weights_summary="full"
# print execution time profiling after training ends
python train.py +trainer.profiler="simple"
python run.py +trainer.profiler="simple"
# try overfitting to 1 batch
python train.py +trainer.overfit_batches=1 trainer.max_epochs=20
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
# use only 20% of the data
python train.py +trainer.limit_train_batches=0.2 \
python run.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
```
@@ -288,7 +288,7 @@ python train.py +trainer.limit_train_batches=0.2 \
```yaml
# checkpoint can be either path or URL
# path should be absolute!
python train.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
```
> *Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.*
@@ -301,7 +301,7 @@ python train.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckp
```yaml
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python train.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
python run.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
```
> *Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.*
@@ -314,7 +314,7 @@ python train.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
```yaml
# this will run hyperparameter search defined in `configs/config_optuna.yaml`
# over chosen experiment config
python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
python run.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
```
> *Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file!*
@@ -325,7 +325,7 @@ python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simp
```yaml
# execute all experiments from folder `configs/experiment/`
python train.py -m '+experiment=glob(*)'
python run.py -m '+experiment=glob(*)'
```
> *Hydra provides special syntax for controlling behavior of multiruns. Read more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run).*
@@ -350,7 +350,7 @@ python train.py -m '+experiment=glob(*)'
### Main Project Configuration
Location: [configs/config.yaml](configs/config.yaml)<br>
Main project config contains default training configuration.<br>
It determines how config is composed when simply executing command `python train.py`.<br>
It determines how config is composed when simply executing command `python run.py`.<br>
It also specifies everything that shouldn't be managed by experiment configurations.
```yaml
# specify here default training configuration
@@ -360,10 +360,10 @@ defaults:
- optimizer: adam.yaml
- datamodule: mnist_datamodule.yaml
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
# path to original working directory (that `train.py` was executed from in command line)
# path to original working directory (that `run.py` was executed from in command line)
# hydra hijacks working directory by changing it to the current log directory,
# so it's useful to have path to original working directory as a special variable
# read more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
@@ -374,8 +374,8 @@ work_dir: ${hydra:runtime.cwd}
data_dir: ${work_dir}/data/
# use `python train.py debug=true` for easy debugging!
# (equivalent to running `python train.py trainer.fast_dev_run=True`)
# use `python run.py debug=true` for easy debugging!
# (equivalent to running `python run.py trainer.fast_dev_run=True`)
debug: False
@@ -391,20 +391,13 @@ disable_warnings: False
disable_lightning_logs: False
# hydra configuration
hydra:
# output paths for hydra logs
run:
dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
sweep:
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
subdir: ${hydra.job.num}
# set your environment variables here
job:
env_set:
ENV_VAR_X: something
```
<br>
@@ -416,7 +409,7 @@ Experiment configurations allow you to overwrite parameters from main project co
#### Simple Example
```yaml
# to execute this experiment run:
# python train.py +experiment=exp_example_simple
# python run.py +experiment=exp_example_simple
defaults:
- override /trainer: default_trainer.yaml
@@ -452,7 +445,7 @@ datamodule:
#### Advanced Example
```yaml
# to execute this experiment run:
# python train.py +experiment=exp_example_full
# python run.py +experiment=exp_example_full
defaults:
- override /trainer: null
@@ -515,7 +508,7 @@ logger:
3. Write your experiment config, containing paths to your model and datamodule (see [configs/experiment](configs/experiment) for examples)
4. Run training with chosen experiment config:<br>
```yaml
python train.py +experiment=experiment_name
python run.py +experiment=experiment_name
```
<br>
@@ -567,7 +560,7 @@ PyTorch Lightning supports the most popular logging frameworks:
These tools help you keep track of hyperparameters and output metrics and allow you to compare and visualize results. To use one of them simply complete its configuration in [configs/logger](configs/logger) and run:
```yaml
python train.py logger=logger_name
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).<br>
You can also write your own logger.<br>
@@ -576,6 +569,13 @@ Lightning provides convenient method for logging custom metrics from inside Ligh
<br><br>
### Inference
Template contains simple example of loading model from checkpoint and running predictions.
Take a look at [inference_example.py](src/utils/inference_example.py).
<br><br>
### Callbacks
Template contains example callbacks for better Weights&Biases integration (see [wandb_callbacks.py](src/callbacks/wandb_callbacks.py)).<br>
@@ -592,15 +592,6 @@ To provide examples of logging custom visualisations with callbacks only:
## Best Practices
### Miniconda
Use miniconda for your python environments. Makes it easier to install some dependencies, like GPU support for PyTorch (it's usually unnecessary to install full Anaconda environment, miniconda should be enough).<br>
Example installation:
```yaml
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
### Code Formating
Use pre-commit hooks to standardize code formatting of your project and save mental energy.<br>
Simply install pre-commit package with:
@@ -612,31 +603,87 @@ Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):
pre-commit install
```
After that your code will be automatically reformatted on every new commit.<br>
Currently [.pre-commit-config.yaml](.pre-commit-config.yaml) contains configurations of **Black** (python code formatting) and **Isort** (python import sorting).
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>
To format all files in the project use command:
```yaml
pre-commit run --all-filess
pre-commit run --all-files
```
You can exclude chosen files from automatic formatting, by modifying [.pre-commit-config.yaml](.pre-commit-config.yaml).
<br>
### Miniconda
Use miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough).
It makes it easier to install some dependencies, like cudatoolkit for GPU support.<br>
Example installation:
```yaml
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
```
<br>
### Environment Variables
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users.
Template contains `.env` file which is excluded from further version control, so you can use it for setting your environment variables.
Simply add your var to `.env` like this:
``` bash
export MY_VAR=/home/user/my_system_path
```
You can use environment variables in your Hydra `.yaml` files like this:
```yaml
path_to_data: ${env:MY_VAR}
```
<br>
### Data Version Control
Use [DVC](https://dvc.org) to version control big files, like your data or trained ML models.<br>
To initialize the dvc repository:
```yaml
dvc init
```
To start tracking a file or directory, use `dvc add`:
```yaml
dvc add data/MNIST
```
DVC stores information about the added file (or a directory) in a special .dvc file named data/MNIST.dvc, a small text file with a human-readable format. This file can be easily versioned like source code with Git, as a placeholder for the original data:
```yaml
git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data"
```
<br>
### Tests
I find myself often running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. You can easily modify the commands in the script for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).<br>
Keep in mind those aren't real tests - it's simply executing commands one after the other, after which you need to take a look in terminal if some of them crashed.
Keep in mind those aren't real tests - it's simply executing commands one after the other, after which you need to take a look in terminal if some of them crashed. It's always best if you write real unit tests for your code.<br>
To execute:
```yaml
bash tests/smoke_tests.sh
```
### Environment Variables
(TODO)
<br><br>
<br>
### Support Installing Project As a Package
It allows other people to easily use your modules in their own projects.
Change name of the `src` folder to your project name and modify configuration in `setup.py`.
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
version="0.0.0",
description="Describe Your Cool Project",
author="",
author_email="",
# replace with your own github project link
url="https://github.com/hobogalaxy/lightning-hydra-template",
install_requires=["pytorch-lightning>=1.2.0", "hydra-core>=1.0.6"],
packages=find_packages(),
)
```
Now your project can be installed from local files:
```yaml
pip install -e .
@@ -650,7 +697,7 @@ So any file can be easily imported into any other file like so:
from project_name.models.mnist_model import LitModelMNIST
from project_name.datamodules.mnist_datamodule import MNISTDataModule
```
<br><br>
<br><br><br>
@@ -659,7 +706,8 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule
<!-- PrettyErrors and Rich exception handling,
k-fold cross validation, faster tab completion import trick,
choosing metric names with '/' for wandb -->
<br>
<br><br>
## Other Repositories
@@ -681,9 +729,14 @@ This template was inspired by:
### Examples Of Repositories Using This Template
(TODO)
<br><br>
## Limitations
(TODO)
<br>
<br>
@@ -727,22 +780,22 @@ pip install -r requirements.txt
Train model with default configuration
```yaml
python train.py
python run.py
```
Train model with chosen experiment configuration
```yaml
# experiment configurations are placed in folder `configs/experiment/`
python train.py +experiment=exp_example_simple
python run.py +experiment=exp_example_simple
```
You can override any parameter from command line like this
```yaml
python train.py trainer.max_epochs=20 optimizer.lr=0.0005
python run.py trainer.max_epochs=20 optimizer.lr=0.0005
```
Train on GPU
```yaml
python train.py trainer.gpus=1
python run.py trainer.gpus=1
```
<br>
-14
View File
@@ -1,14 +0,0 @@
#name: conda_env_name
channels:
- pytorch
- conda-forge
- defaults
dependencies:
- python=3.8
- pip
- notebook
- pytorch
- torchvision
- torchaudio
+6 -6
View File
@@ -7,14 +7,14 @@ defaults:
- optimizer: adam.yaml
- datamodule: mnist_datamodule.yaml
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
# enable color logging
# - override hydra/hydra_logging: colorlog
# - override hydra/job_logging: colorlog
# path to original working directory (that `train.py` was executed from in command line)
# path to original working directory (that `run.py` was executed from in command line)
# hydra hijacks working directory by changing it to the current log directory,
# so it's useful to have path to original work dir as a special variable
# read more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
@@ -25,9 +25,9 @@ work_dir: ${hydra:runtime.cwd}
data_dir: ${work_dir}/data/
# use `python train.py debug=true` for easy debugging!
# use `python run.py debug=true` for easy debugging!
# this will run 1 train, val and test loop with only 1 batch
# equivalent to running `python train.py trainer.fast_dev_run=true`
# equivalent to running `python run.py trainer.fast_dev_run=true`
# (this is placed here just for easier access from command line)
debug: False
@@ -44,7 +44,6 @@ disable_warnings: True
disable_lightning_logs: False
# # hydra configuration
hydra:
# output paths for hydra logs
run:
@@ -54,7 +53,8 @@ hydra:
subdir: ${hydra.job.num}
job:
# you can set environment variables here
# you can set here environment variables that are universal for all users
# for system specific variables (like data paths) it's better to use .env file!
env_set:
# currently there are some issues with running sweeps alongside wandb
# https://github.com/wandb/client/issues/1314
+2 -2
View File
@@ -1,7 +1,7 @@
# @package _global_
# example hyperparameter optimization of some experiment with optuna:
# python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple logger=wandb
# python run.py -m --config-name config_optuna.yaml +experiment=exp_example_simple logger=wandb
defaults:
# load everything from main config file
@@ -16,7 +16,7 @@ optimized_metric: "val/acc_best"
hydra:
# here we define optuna objective
# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
# learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper
sweeper:
+1 -1
View File
@@ -1,7 +1,7 @@
# @package _global_
# to execute this experiment run:
# python train.py +experiment=exp_example_full
# python run.py +experiment=exp_example_full
defaults:
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
+1 -1
View File
@@ -1,7 +1,7 @@
# @package _global_
# to execute this experiment run:
# python train.py +experiment=exp_example_simple
# python run.py +experiment=exp_example_simple
defaults:
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
+1 -3
View File
@@ -13,7 +13,7 @@ progress_bar_refresh_rate: null
weights_summary: null
profiler: null
# all of the parameters below are set to Lightning defaults
# all parameters below are set to Lightning defaults
# tricks
gradient_clip_val: 0
@@ -42,8 +42,6 @@ deterministic: False
resume_from_checkpoint: null
# no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
# accumulate_grad_batches: {5: 3, 10: 20}
# automatically find the largest batch size that fits into memory and is power of 2
# (requires calling trainer.tune(model=model, datamodule=datamodule))
+2 -34
View File
@@ -1,42 +1,10 @@
_target_: pytorch_lightning.Trainer
# set -1 to train on all GPUs available
# set 0 to train on CPU only
# set `1` to train on GPU, `0` to train on CPU only
gpus: 0
min_epochs: 1
max_epochs: 10
# prints
# progress_bar_refresh_rate: null
weights_summary: null
# profiler: null
# all of the parameters below are set to Lightning defaults
# tricks
# gradient_clip_val: 0
# accumulate_grad_batches: 1
# val_check_interval: 1.0
# check_val_every_n_epoch: 1
# stochastic_weight_avg: False
# debug
# num_sanity_val_steps: 2
# fast_dev_run: False
# overfit_batches: 0
# limit_train_batches: 1.0
# limit_val_batches: 1.0
# limit_test_batches: 1.0
# track_grad_norm: -1
# others
# amp_backend: "native"
# amp_level: "02"
# precision: 32
# accelerator: null
# num_nodes: 1
# tpu_cores: null
# deterministic: False
# resume_from_checkpoint: null
progress_bar_refresh_rate: 10
+7 -5
View File
@@ -1,7 +1,7 @@
# --------- pytorch --------- #
torch>=1.8.0
torchvision>=0.9.0
torchaudio>=0.8.0
torch>=1.7.1
torchvision>=0.8.2
torchaudio>=0.7.2
pytorch-lightning>=1.2.2
# --------- hydra --------- #
@@ -25,5 +25,7 @@ pre-commit
# --------- others --------- #
rich>=9.12.3
scikit-learn>=0.24.1
pandas>=1.2.2
python-dotenv
dvc
# scikit-learn
# pandas
+35
View File
@@ -0,0 +1,35 @@
import hydra
from omegaconf import DictConfig
@hydra.main(config_path="configs/", config_name="config.yaml")
def main(config: DictConfig):
# Imports should be nested inside @hydra.main to optimize tab completion
# Learn more here: https://github.com/facebookresearch/hydra/issues/934
import dotenv
from src.train import train
from src.utils import template_utils
# load environment variables from `.env` file
dotenv.load_dotenv(dotenv_path=".env", override=True)
# A couple of optional utilities:
# - disabling python warnings
# - disabling lightning logs
# - easier access to debug mode
# - forcing debug friendly configuration
# You can safely get rid of this line if you don't want those
template_utils.extras(config)
# Pretty print config using Rich library
if config.get("print_config"):
hydra.utils.log.info(f"Pretty printing config with Rich! <{config.print_config=}>")
template_utils.print_config(config, resolve=True)
# Train model
return train(config)
if __name__ == "__main__":
main()
-13
View File
@@ -1,13 +0,0 @@
#!/usr/bin/env python
from setuptools import find_packages, setup
setup(
name="src", # you should probably change "src" to your project name
version="0.0.0",
description="Describe Your Cool Project",
author="",
author_email="",
url="https://github.com/hobogalaxy/lightning-hydra-template", # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
install_requires=["pytorch-lightning>=1.2.1", "hydra-core>=1.0.6"],
packages=find_packages(),
)
-1
View File
@@ -1 +0,0 @@
# makes 'src' a Python module
+22 -35
View File
@@ -9,42 +9,38 @@ from hydra.utils import log
import hydra
# normal imports
from typing import List
from typing import List, Optional
# src imports
from src.utils import template_utils as utils
from src.utils import template_utils
def train(config: DictConfig):
def train(config: DictConfig) -> Optional[float]:
"""Contains training pipeline.
Instantiates all PyTorch Lightning objects from config.
# A couple of optional utilities:
# - disabling warnings
# - disabling lightning logs
# - easier access to debug mode
# - forcing debug friendly configuration
# You can safely get rid of this line if you don't want those
utils.extras(config)
Args:
config (DictConfig): Configuration composed by Hydra.
# Pretty print config using Rich library
if config.get("print_config"):
log.info(f"Pretty printing config with Rich! <{config.print_config=}>")
utils.print_config(config, resolve=True)
Returns:
Optional[float]: Metric score for hyperparameter optimization.
"""
# Set seed for random number generators in pytorch, numpy and python.random
if "seed" in config:
seed_everything(config.seed)
# Init Lightning datamodule ⚡
# Init Lightning datamodule
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
# Init Lightning model ⚡
# Init Lightning model
log.info(f"Instantiating model <{config.model._target_}>")
model: LightningModule = hydra.utils.instantiate(
config.model, optimizer=config.optimizer, _recursive_=False
)
# Init Lightning callbacks ⚡
# Init Lightning callbacks
callbacks: List[Callback] = []
if "callbacks" in config:
for _, cb_conf in config["callbacks"].items():
@@ -52,7 +48,7 @@ def train(config: DictConfig):
log.info(f"Instantiating callback <{cb_conf._target_}>")
callbacks.append(hydra.utils.instantiate(cb_conf))
# Init Lightning loggers ⚡
# Init Lightning loggers
logger: List[LightningLoggerBase] = []
if "logger" in config:
for _, lg_conf in config["logger"].items():
@@ -60,15 +56,15 @@ def train(config: DictConfig):
log.info(f"Instantiating logger <{lg_conf._target_}>")
logger.append(hydra.utils.instantiate(lg_conf))
# Init Lightning trainer ⚡
# Init Lightning trainer
log.info(f"Instantiating trainer <{config.trainer._target_}>")
trainer: Trainer = hydra.utils.instantiate(
config.trainer, callbacks=callbacks, logger=logger
)
# Send some parameters from config to all lightning loggers
log.info(f"Logging hyperparameters!")
utils.log_hyperparameters(
log.info("Logging hyperparameters!")
template_utils.log_hyperparameters(
config=config,
model=model,
datamodule=datamodule,
@@ -77,18 +73,18 @@ def train(config: DictConfig):
logger=logger,
)
# Train the model ⚡
log.info(f"Starting training!")
# Train the model
log.info("Starting training!")
trainer.fit(model=model, datamodule=datamodule)
# Evaluate model on test set after training
if not config.trainer.get("fast_dev_run"):
log.info(f"Starting testing!")
log.info("Starting testing!")
trainer.test()
# Make sure everything closed properly
log.info(f"Finalizing!")
utils.finish(
log.info("Finalizing!")
template_utils.finish(
config=config,
model=model,
datamodule=datamodule,
@@ -101,12 +97,3 @@ def train(config: DictConfig):
optimized_metric = config.get("optimized_metric")
if optimized_metric:
return trainer.callback_metrics[optimized_metric]
@hydra.main(config_path="configs/", config_name="config.yaml")
def main(config: DictConfig):
return train(config)
if __name__ == "__main__":
main()
+1 -1
View File
@@ -5,5 +5,5 @@ mnist_train_transforms = transforms.Compose(
)
mnist_test_transforms = transforms.Compose(
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
[transforms.ToTensor(), transforms.Resize((28, 28)), transforms.Normalize((0.1307,), (0.3081,))]
)
+6 -1
View File
@@ -11,11 +11,16 @@ def predict():
"""
# ckpt can be also a URL!
CKPT_PATH = "epoch=0.ckpt"
CKPT_PATH = "last.ckpt"
# load model from checkpoint
# model __init__ parameters will be loaded from ckpt automatically
# you can also pass some parameter explicitly to override it
trained_model = LitModelMNIST.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# print model hyperparameters
print(trained_model.hparams)
# switch to evaluation mode
trained_model.eval()
trained_model.freeze()
+6 -1
View File
@@ -90,6 +90,8 @@ def print_config(
# TODO print main config path and experiment config path
# print(f"Main config path: [link file://{directory}]{directory}")
# TODO refactor the whole method
style = "dim"
tree = Tree(f":gear: CONFIG", style=style, guide_style=style)
@@ -111,7 +113,10 @@ def print_config(
cfg_str = OmegaConf.to_yaml(nested_config_section, resolve=resolve)
nested_branch.add(Syntax(cfg_str, "yaml"))
else:
cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
if isinstance(config_section, DictConfig):
cfg_str = OmegaConf.to_yaml(config_section, resolve=resolve)
else:
cfg_str = str(config_section)
branch.add(Syntax(cfg_str, "yaml"))
print(tree)
+5 -5
View File
@@ -17,29 +17,29 @@ export PYTHONWARNINGS="ignore"
echo "TEST 1"
echo "Train on GPU (2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
python run.py trainer.gpus=-1 trainer.max_epochs=2 \
print_config=false
echo "TEST 2"
echo "Train with 4 workers and cuda pinned memory (2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
python run.py trainer.gpus=-1 trainer.max_epochs=2 \
datamodule.num_workers=4 datamodule.pin_memory=True \
print_config=false
echo "TEST 3"
echo "Train with 16-bit precision (1 epoch)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
python run.py trainer.gpus=-1 trainer.max_epochs=2 \
+trainer.precision=16 \
print_config=false
echo "TEST 4"
echo "Train with mixed precision (apex, amp level 01, 2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
python run.py trainer.gpus=-1 trainer.max_epochs=2 \
+trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16 \
print_config=false
echo "TEST 5"
echo "Train with mixed precision (apex, amp level 02, 2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
python run.py trainer.gpus=-1 trainer.max_epochs=2 \
+trainer.amp_backend="apex" +trainer.amp_level="O2" +trainer.precision=16 \
print_config=false
+11 -11
View File
@@ -17,59 +17,59 @@ export PYTHONWARNINGS="ignore"
echo "TEST 1"
echo "Debug mode (run 1 train, val and test loop using 1 batch)"
python train.py trainer=debug_trainer debug=True \
python run.py trainer=debug_trainer debug=True \
print_config=false
echo "TEST 2"
echo "Overfit to 10 batches (10 epochs)"
python train.py trainer=debug_trainer trainer.overfit_batches=10 \
python run.py trainer=debug_trainer trainer.overfit_batches=10 \
trainer.min_epochs=10 trainer.max_epochs=10 \
print_config=false
echo "TEST 3"
echo "Train on CPU (1 epoch)"
python train.py trainer=debug_trainer trainer.gpus=0 trainer.max_epochs=1 \
python run.py trainer=debug_trainer trainer.gpus=0 trainer.max_epochs=1 \
print_config=false
echo "TEST 4"
echo "Train on 25% of data (1 epoch)"
python train.py trainer=debug_trainer trainer.max_epochs=1 \
python run.py trainer=debug_trainer trainer.max_epochs=1 \
trainer.limit_train_batches=0.25 trainer.limit_val_batches=0.25 trainer.limit_test_batches=0.25 \
print_config=false
echo "TEST 5"
echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)"
python train.py trainer=debug_trainer trainer.max_epochs=1 \
python run.py trainer=debug_trainer trainer.max_epochs=1 \
trainer.limit_train_batches=15 trainer.limit_val_batches=10 trainer.limit_test_batches=5 \
print_config=false
echo "TEST 6"
echo "Run all experiment configs (2 epochs)"
python train.py -m trainer=debug_trainer '+experiment=glob(*)' trainer.max_epochs=2 \
python run.py -m trainer=debug_trainer '+experiment=glob(*)' trainer.max_epochs=2 \
print_config=false
echo "TEST 7"
echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
python train.py -m trainer=debug_trainer datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \
python run.py -m trainer=debug_trainer datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \
debug=True \
print_config=false
echo "TEST 8"
echo "Run with gradient accumulation (1 epoch)"
python train.py trainer=debug_trainer trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \
python run.py trainer=debug_trainer trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \
print_config=false
echo "TEST 9"
echo "Run validation loop twice per epoch (2 epochs)"
python train.py trainer=debug_trainer trainer.max_epochs=2 trainer.val_check_interval=0.5 \
python run.py trainer=debug_trainer trainer.max_epochs=2 trainer.val_check_interval=0.5 \
print_config=false
echo "TEST 10"
echo "Run with CSVLogger (2 epochs)"
python train.py trainer=debug_trainer logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \
python run.py trainer=debug_trainer logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false
echo "TEST 11"
echo "Run with TensorBoardLogger (2 epochs)"
python train.py trainer=debug_trainer logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \
python run.py trainer=debug_trainer logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false
+3 -2
View File
@@ -17,15 +17,16 @@ export PYTHONWARNINGS="ignore"
echo "TEST 1"
echo "Default hydra sweep with wandb logging"
python train.py -m datamodule.batch_size=64,128 model.lr=0.001,0.003 \
python run.py -m \
+experiment=exp_example_simple \
datamodule.batch_size=64,128 optimizer.lr=0.001,0.003 \
trainer.gpus=-1 trainer.max_epochs=2 \
datamodule.num_workers=12 datamodule.pin_memory=True \
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"
echo "TEST 2"
echo "Optuna sweep with wandb logging"
python train.py -m --config-name config_optuna.yaml \
python run.py -m --config-name config_optuna.yaml \
+experiment=exp_example_simple \
trainer.gpus=-1 trainer.max_epochs=5 \
datamodule.num_workers=12 datamodule.pin_memory=True \