PyTorch Lightning + Hydra. A feature-rich template for rapid, scalable and reproducible ML experimentation with best practices. ⚑πŸ”₯⚑

Overview

Lightning-Hydra-Template

Python PyTorch Lightning Config: hydra Code style: black

A clean and scalable template to kickstart your deep learning project πŸš€ ⚑ πŸ”₯
Click on Use this template to initialize new repository.

Suggestions are always welcome!



πŸ“Œ   Introduction

This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in src/train.py.

Effective usage of this template requires learning of a couple of technologies: PyTorch, PyTorch Lightning and Hydra. Knowledge of some experiment logging framework like Weights&Biases, Neptune or MLFlow is also recommended.

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. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task. See #Limitations for more.

Why PyTorch Lightning?

PyTorch Lightning is a lightweight PyTorch wrapper for high-performance AI research. It makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.

Why Hydra?

Hydra is an open-source Python framework that simplifies the development of research and other complex applications. The key feature is the ability to dynamically create a hierarchical configuration by composition and override it through config files and the command line. It allows you to conveniently manage experiments and provides many useful plugins, like Optuna Sweeper for hyperparameter search, or Ray Launcher for running jobs on a cluster.


Main Ideas Of This Template

  • Predefined Structure: clean and scalable so that work can easily be extended and replicated | #Project Structure
  • Rapid Experimentation: thanks to automating pipeline with config files and hydra command line superpowers | #Your Superpowers
  • Reproducibility: obtaining similar results is supported in multiple ways | #Reproducibility
  • Little Boilerplate: so pipeline can be easily modified | #How It Works
  • Main Configuration: main config file specifies default training configuration | #Main Project Configuration
  • Experiment Configurations: can be composed out of smaller configs and override chosen hyperparameters | #Experiment Configuration
  • Workflow: comes down to 4 simple steps | #Workflow
  • Experiment Tracking: many logging frameworks can be easily integrated, like Tensorboard, MLFlow or W&B | #Experiment Tracking
  • Logs: all logs (checkpoints, data from loggers, hparams, etc.) are stored in a convenient folder structure imposed by Hydra | #Logs
  • Hyperparameter Search: made easier with Hydra built-in plugins like Optuna Sweeper | #Hyperparameter Search
  • Tests: unit tests and shell/command based tests for speeding up the development | #Tests
  • Best Practices: a couple of recommended tools, practices and standards for efficient workflow and reproducibility | #Best Practices

Project Structure

The directory structure of new project looks like this:

β”œβ”€β”€ bash                    <- Bash scripts
β”‚   └── schedule.sh             <- Schedule execution of many runs
β”‚
β”œβ”€β”€ configs                 <- Hydra configuration files
β”‚   β”œβ”€β”€ callbacks               <- Callbacks configs
β”‚   β”œβ”€β”€ datamodule              <- Datamodule configs
β”‚   β”œβ”€β”€ experiment              <- Experiment configs
β”‚   β”œβ”€β”€ hparams_search          <- Hyperparameter search configs
β”‚   β”œβ”€β”€ local                   <- Local configs
β”‚   β”œβ”€β”€ logger                  <- Logger configs
β”‚   β”œβ”€β”€ mode                    <- Running mode configs
β”‚   β”œβ”€β”€ model                   <- Model configs
β”‚   β”œβ”€β”€ trainer                 <- Trainer configs
β”‚   β”‚
β”‚   └── config.yaml             <- Main project configuration file
β”‚
β”œβ”€β”€ data                    <- Project data
β”‚
β”œβ”€β”€ logs                    <- Logs generated by Hydra and PyTorch Lightning loggers
β”‚
β”œβ”€β”€ notebooks               <- Jupyter notebooks. Naming convention is a number (for ordering),
β”‚                              the creator's initials, and a short `-` delimited description, e.g.
β”‚                              `1.0-jqp-initial-data-exploration.ipynb`.
β”‚
β”œβ”€β”€ tests                   <- Tests of any kind
β”‚   β”œβ”€β”€ helpers                 <- A couple of testing utilities
β”‚   β”œβ”€β”€ shell                   <- Shell/command based tests
β”‚   └── unit                    <- Unit tests
β”‚
β”œβ”€β”€ src
β”‚   β”œβ”€β”€ callbacks               <- Lightning callbacks
β”‚   β”œβ”€β”€ datamodules             <- Lightning datamodules
β”‚   β”œβ”€β”€ models                  <- Lightning models
β”‚   β”œβ”€β”€ utils                   <- Utility scripts
β”‚   β”œβ”€β”€ vendor                  <- Third party code that cannot be installed using PIP/Conda
β”‚   β”‚
β”‚   └── train.py                <- Training pipeline
β”‚
β”œβ”€β”€ run.py                  <- Run pipeline with chosen experiment configuration
β”‚
β”œβ”€β”€ .env.example            <- Template of the file for storing private environment variables
β”œβ”€β”€ .gitignore              <- List of files/folders ignored by git
β”œβ”€β”€ .pre-commit-config.yaml <- Configuration of automatic code formatting
β”œβ”€β”€ setup.cfg               <- Configurations of linters and pytest
β”œβ”€β”€ requirements.txt        <- File for installing python dependencies
└── README.md

πŸš€   Quickstart

# clone project
git clone https://github.com/ashleve/lightning-hydra-template
cd lightning-hydra-template

# [OPTIONAL] create conda environment
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

Template contains example with MNIST classification.
When running python run.py you should see something like this:

⚑   Your Superpowers

(click to expand)

Override any config parameter from command line

Hydra allows you to easily overwrite any parameter defined in your config.

python run.py trainer.max_epochs=20 model.lr=1e-4

You can also add new parameters with + sign.

python run.py +model.new_param="uwu"
Train on CPU, GPU, multi-GPU and TPU

PyTorch Lightning makes it easy to train your models on different hardware.

# train on CPU
python run.py trainer.gpus=0

# train on 1 GPU
python run.py trainer.gpus=1

# train on TPU
python run.py +trainer.tpu_cores=8

# train with DDP (Distributed Data Parallel) (4 GPUs)
python run.py trainer.gpus=4 +trainer.strategy=ddp

# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp
Train with mixed precision
# 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. Using wandb requires you to setup account first. After that just complete the config as below.
> Click here to see example wandb dashboard generated with this template.

# set project and entity names in `configs/logger/wandb`
wandb:
  project: "your_project_name"
  entity: "your_wandb_team_name"
# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
python run.py logger=wandb
Use different running modes
# debug mode changes logging folder to `logs/debug/`
# also enables default trainer debugging options from `configs/trainer/debug.yaml`
# also sets level of all command line loggers to 'DEBUG'
python run.py mode=debug

# experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/`
# name is also used by loggers
python run.py mode=exp name='my_new_experiment_253'
Train model with chosen experiment config

Experiment configurations are placed in configs/experiment/.

python run.py experiment=example_simple
Attach some callbacks to run

Callbacks can be used for things such as as model checkpointing, early stopping and many more.
Callbacks configurations are placed in configs/callbacks/.

python run.py callbacks=default
Use different tricks available in Pytorch Lightning

PyTorch Lightning provides about 40+ useful trainer flags.

# gradient clipping may be enabled to avoid exploding gradients
python run.py +trainer.gradient_clip_val=0.5

# stochastic weight averaging can make your models generalize better
python run.py +trainer.stochastic_weight_avg=true

# run validation loop 4 times during a training epoch
python run.py +trainer.val_check_interval=0.25

# accumulate gradients
python run.py +trainer.accumulate_grad_batches=10

# terminate training after 12 hours
python run.py +trainer.max_time="00:12:00:00"
Easily debug
# 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 execution time profiling after training ends
python run.py +trainer.profiler="simple"

# try overfitting to 1 batch
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20

# use only 20% of the data
python run.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2

# log second gradient norm of the model
python run.py +trainer.track_grad_norm=2
Resume training from checkpoint

Checkpoint can be either path or URL. Path should be absolute!

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.

Create a sweep over hyperparameters
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python run.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005

⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).

Create a sweep over hyperparameters with Optuna

Using Optuna Sweeper plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file!

# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python run.py -m hparams_search=mnist_optuna experiment=example_simple

⚠️ Currently this sweep is not failure resistant (if one job crashes than the whole sweep crashes). Might be supported in future Hydra release.

Execute all experiments from folder

Hydra provides special syntax for controlling behavior of multiruns. Learn more here. The command below executes all experiments from folder configs/experiment/.

python run.py -m 'experiment=glob(*)'
Execute sweep on a remote AWS cluster

This should be achievable with simple config using Ray AWS launcher for Hydra. Example is not yet implemented in this template.

Use Hydra tab completion

Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing tab key. Learn more here.


🐳   Docker

First you will need to install Nvidia Container Toolkit to enable GPU support.

The template Dockerfile is provided on branch dockerfiles. Copy it to the template root folder.

To build the container use:

docker build -t <project_name> .

To mount the project to the container use:

docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name>

❀️   Contributions

Have a question? Found a bug? Missing a specific feature? Ran into a problem? Feel free to file a new issue or PR with respective title and description. If you already found a solution to your problem, don't hesitate to share it. Suggestions for new best practices and tricks are always welcome!


ℹ️   Guide

How To Get Started


How It Works

Every run is initialized by run.py file. All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:

_target_: src.models.mnist_model.MNISTLitModel
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
lr: 0.001

Using this config we can instantiate the object with the following line:

model = hydra.utils.instantiate(config.model)

This allows you to easily iterate over new models!
Every time you create a new one, just specify its module path and parameters in appriopriate config file.
The whole pipeline managing the instantiation logic is placed in src/train.py.


Main Project Configuration

Location: configs/config.yaml
Main project config contains default training configuration.
It determines how config is composed when simply executing command python run.py.
It also specifies everything that shouldn't be managed by experiment configurations.

Show main project configuration
# specify here default training configuration
defaults:
  - trainer: default.yaml
  - model: mnist_model.yaml
  - datamodule: mnist_datamodule.yaml
  - callbacks: default.yaml # set this to null if you don't want to use callbacks
  - logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)

  - mode: default.yaml

  - experiment: null
  - hparams_search: null

# 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
# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
work_dir: ${hydra:runtime.cwd}

# path to folder with data
data_dir: ${work_dir}/data/

# pretty print config at the start of the run using Rich library
print_config: True

# disable python warnings if they annoy you
ignore_warnings: True

Experiment Configuration

Location: configs/experiment
You should store all your experiment configurations in this folder.
Experiment configurations allow you to overwrite parameters from main project configuration.

Simple example

# to execute this experiment run:
# 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
  - override /callbacks: default.yaml
  - override /logger: null

# 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:
  max_epochs: 10
  gradient_clip_val: 0.5

model:
  lin1_size: 128
  lin2_size: 256
  lin3_size: 64
  lr: 0.005

datamodule:
  train_val_test_split: [55_000, 5_000, 10_000]
  batch_size: 64
Show advanced example
# to execute this experiment run:
# python run.py experiment=example_full

defaults:
  - override /mode: exp.yaml
  - override /trainer: null
  - override /model: null
  - override /datamodule: null
  - override /callbacks: null
  - override /logger: null

# we override default configurations with nulls to prevent them from loading at all
# instead we define all modules and their paths directly in this config,
# so everything is stored in one place

name: "example_full"

seed: 12345

trainer:
  _target_: pytorch_lightning.Trainer
  gpus: 0
  min_epochs: 1
  max_epochs: 10
  gradient_clip_val: 0.5

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

datamodule:
  _target_: src.datamodules.mnist_datamodule.MNISTDataModule
  data_dir: ${data_dir}
  train_val_test_split: [55_000, 5_000, 10_000]
  batch_size: 64
  num_workers: 0
  pin_memory: False

logger:
  wandb:
    _target_: pytorch_lightning.loggers.wandb.WandbLogger
    project: "lightning-hydra-template"
    name: ${name}
    tags: ["best_model", "mnist"]
    notes: "Description of this model."

Local Configuration

Location: configs/local
Some configurations are user/machine/installation specific (e.g. configuration of local cluster, or harddrive paths on a specific machine). For such scenarios, a file configs/local/default.yaml can be created which is automatically loaded but not tracked by Git.

Local Slurm cluster config example
# @package _global_

defaults:
  - override /hydra/launcher@_here_: submitit_slurm

data_dir: /mnt/scratch/data/

hydra:
  launcher:
    timeout_min: 1440
    gpus_per_task: 1
    gres: gpu:1
  job:
    env_set:
      MY_VAR: /home/user/my/system/path
      MY_KEY: asdgjhawi8y23ihsghsueity23ihwd

Workflow

  1. Write your PyTorch Lightning model (see mnist_model.py for example)
  2. Write your PyTorch Lightning datamodule (see 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.
This means your working directory is different for every run, which might not be compatible with some libraries and workflows. By default, logs have the following structure:

β”œβ”€β”€ logs
β”‚   β”œβ”€β”€ experiments           # Folder for logs generated by experiments
β”‚   β”‚   β”œβ”€β”€ experiment_name     # Name of the experiment
β”‚   β”‚   β”‚   β”œβ”€β”€ runs
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ YYYY-MM-DD        	# Date of execution
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ HH-MM-SS          # Time of execution
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ .hydra          # Hydra logs
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ wandb           # Weights&Biases logs
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ checkpoints     # Training checkpoints
β”‚   β”‚   β”‚   β”‚   β”‚   β”‚   └── ...             # Any other thing saved during training
β”‚   β”‚   β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚   β”‚
β”‚   β”‚   β”‚   └── multiruns
β”‚   β”‚   β”‚       β”œβ”€β”€ YYYY-MM-DD
β”‚   β”‚   β”‚       β”‚   β”œβ”€β”€ HH-MM-SS
β”‚   β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€ 1               # Multirun job number
β”‚   β”‚   β”‚       β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€ 2
β”‚   β”‚   β”‚       β”‚   β”‚   └── ...
β”‚   β”‚   β”‚       β”‚   └── ...
β”‚   β”‚   β”‚       └── ...
β”‚   β”‚   └── ...
β”‚   β”‚
β”‚   β”œβ”€β”€ debugs                  # Folder for logs generated during debugging
β”‚   β”‚ 	β”œβ”€β”€ runs
β”‚   β”‚   β”‚   β”œβ”€β”€ YYYY-MM-DD
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ HH-MM-SS
β”‚   β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   └── multiruns
β”‚   β”‚       β”œβ”€β”€ YYYY-MM-DD
β”‚   β”‚       β”‚   β”œβ”€β”€ HH-MM-SS
β”‚   β”‚       β”‚   └── ...
β”‚   β”‚       └─ ...
β”‚   β”‚
β”‚   β”œβ”€β”€ runs                    # Folder for logs generated by normal runs
β”‚   β”‚   β”œβ”€β”€ YYYY-MM-DD
β”‚   β”‚   β”‚   β”œβ”€β”€ HH-MM-SS
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   └── ...
β”‚   β”‚
β”‚   └── multiruns               # Folder for logs generated by normal multiruns (sweeps)
β”‚       β”œβ”€β”€ YYYY-MM-DD
β”‚       |   β”œβ”€β”€ HH-MM-SS
β”‚       |   └── ...
β”‚       └── ...
β”‚

You can change this structure by modifying paths in hydra configuration.


Experiment Tracking

PyTorch Lightning supports the most popular logging frameworks:
Weights&Biases Β· Neptune Β· Comet Β· MLFlow Β· Tensorboard

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 and run:

python run.py logger=logger_name

You can use many of them at once (see 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 or take a look at MNIST example.


Hyperparameter Search

Defining hyperparameter optimization is as easy as adding new config file to configs/hparams_search.

Show example
defaults:
  - override /hydra/sweeper: optuna

# choose metric which will be optimized by Optuna
optimized_metric: "val/acc_best"

hydra:
  # 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:
    _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
    storage: null
    study_name: null
    n_jobs: 1

    # 'minimize' or 'maximize' the objective
    direction: maximize

    # number of experiments that will be executed
    n_trials: 20

    # choose Optuna hyperparameter sampler
    # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html
    sampler:
      _target_: optuna.samplers.TPESampler
      seed: 12345
      consider_prior: true
      prior_weight: 1.0
      consider_magic_clip: true
      consider_endpoints: false
      n_startup_trials: 10
      n_ei_candidates: 24
      multivariate: false
      warn_independent_sampling: true

    # define range of hyperparameters
    search_space:
      datamodule.batch_size:
        type: categorical
        choices: [32, 64, 128]
      model.lr:
        type: float
        low: 0.0001
        high: 0.2
      model.lin1_size:
        type: categorical
        choices: [32, 64, 128, 256, 512]
      model.lin2_size:
        type: categorical
        choices: [32, 64, 128, 256, 512]
      model.lin3_size:
        type: categorical
        choices: [32, 64, 128, 256, 512]

Next, you can execute it with: python run.py -m hparams_search=mnist_optuna
Using this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file. You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad. The optimization_results.yaml will be available under logs/multirun folder.


Inference

The following code is an example of loading model from checkpoint and running predictions.

Show example
from PIL import Image
from torchvision import transforms

from src.models.mnist_model import MNISTLitModel


def predict():
    """Example of inference with trained model.
    It loads trained image classification model from checkpoint.
    Then it loads example image and predicts its label.
    """

    # ckpt can be also a URL!
    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 = MNISTLitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)

    # print model hyperparameters
    print(trained_model.hparams)

    # switch to evaluation mode
    trained_model.eval()
    trained_model.freeze()

    # load data
    img = Image.open("data/example_img.png").convert("L")  # convert to black and white
    # img = Image.open("data/example_img.png").convert("RGB")  # convert to RGB

    # preprocess
    mnist_transforms = transforms.Compose(
        [
            transforms.ToTensor(),
            transforms.Resize((28, 28)),
            transforms.Normalize((0.1307,), (0.3081,)),
        ]
    )
    img = mnist_transforms(img)
    img = img.reshape((1, *img.size()))  # reshape to form batch of size 1

    # inference
    output = trained_model(img)
    print(output)


if __name__ == "__main__":
    predict()

Tests

Template comes with example tests implemented with pytest library.
To execute them simply run:

# run all tests
pytest

# run tests from specific file
pytest tests/shell/test_basic_commands.py

# run all tests except the ones marked as slow
pytest -k "not slow"

To speed up the development, you can once in a while execute tests that run a couple of quick experiments, like training 1 epoch on 25% of data, executing single train/val/test step, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some bash commands doesn't end up in throwing exceptions. You can find them implemented in tests/shell folder.

You can easily modify the commands in the scripts for your use case. If 1 epoch is too much for your model, then make it run for a couple of batches instead (by using the right trainer flags).


Callbacks

Template contains example callbacks enabling better Weights&Biases integration, which you can use as a reference for writing your own callbacks (see wandb_callbacks.py).
To support reproducibility:

  • WatchModel
  • UploadCodeAsArtifact
  • UploadCheckpointsAsArtifact

To provide examples of logging custom visualisations with callbacks only:

  • LogConfusionMatrix
  • LogF1PrecRecHeatmap
  • LogImagePredictions

To try all of the callbacks at once, use:

python run.py logger=wandb callbacks=wandb

To see the result of all the callbacks attached, take a look at this experiment dashboard.


Multi-GPU Training

Lightning supports multiple ways of doing distributed training.
The most common one is DDP, which spawns separate process for each GPU and averages gradients between them. To learn about other approaches read lightning docs.

You can run DDP on mnist example with 4 GPUs like this:

python run.py trainer.gpus=4 +trainer.strategy=ddp

⚠️ When using DDP you have to be careful how you write your models - learn more here.


Reproducibility

What provides reproducibility:

  • Hydra manages your configs
  • Hydra manages your logging paths and makes every executed run store its hyperparameters and config overrides in a separate file in logs
  • Single seed for random number generators in pytorch, numpy and python.random
  • LightningDataModule allows you to encapsulate data split, transformations and default parameters in a single, clean abstraction
  • LightningModule separates your research code from engineering code in a clean way
  • Experiment tracking frameworks take care of logging metrics and hparams, some can also store results and artifacts in cloud
  • Pytorch Lightning takes care of creating training checkpoints
  • Example callbacks for wandb show how you can save and upload a snapshot of codebase every time the run is executed, as well as upload ckpts and track model gradients

You can load the config of previous run using:

python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml

The config.yaml from .hydra folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the hydra/ part of the config, meaning logging paths will revert to default!


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. Implementing it requires rewriting the training pipeline.
  • Pytorch Lightning might not be the best choice for scalable reinforcement learning, it's probably better to use something like Ray.
  • Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.
  • Hydra changes working directory to new logging folder for every executed run, which might not be compatible with the way some libraries work.

Useful Tricks

Accessing datamodule attributes in model
  1. The simplest way is to pass datamodule attribute directly to model on initialization:

    # ./src/train.py
    datamodule = hydra.utils.instantiate(config.datamodule)
    model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)

    This is not a very robust solution, since it assumes all your datamodules have some_param attribute available (otherwise the run will crash).

  2. If you only want to access datamodule config, you can simply pass it as an init parameter:

    # ./src/train.py
    model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule, _recursive_=False)

    Now you can access any datamodule config part like this:

    # ./src/models/my_model.py
    class MyLitModel(LightningModule):
    	def __init__(self, dm_conf, param1, param2):
    		super().__init__()
    
    		batch_size = dm_conf.batch_size
  3. If you need to access the datamodule object attributes, a little hacky solution is to add Omegaconf resolver to your datamodule:

    # ./src/datamodules/my_datamodule.py
    from omegaconf import OmegaConf
    
    class MyDataModule(LightningDataModule):
    	def __init__(self, param1, param2):
    		super().__init__()
    
    		self.param1 = param1
    
    		resolver_name = "datamodule"
    		OmegaConf.register_new_resolver(
    			resolver_name,
    			lambda name: getattr(self, name),
    			use_cache=False
    		)

    This way you can reference any datamodule attribute from your config like this:

    # this will return attribute 'param1' from datamodule object
    param1: ${datamodule: param1}

    When later accessing this field, say in your lightning model, it will get automatically resolved based on all resolvers that are registered. Remember not to access this field before datamodule is initialized or it will crash. You also need to set resolve=False in print_config() in run.py or it will throw errors:

    # ./src/run.py
    utils.print_config(config, resolve=False)
Automatic activation of virtual environment and tab completion when entering folder
  1. Create a new file called .autoenv (this name is excluded from version control in .gitignore).
    You can use it to automatically execute shell commands when entering folder. Add some commands to your .autoenv file, like in the example below:

    # activate conda environment
    conda activate myenv
    
    # activate hydra tab completion for bash
    eval "$(python run.py -sc install=bash)"
    
    # enable aliases for debugging
    alias debug='python run.py mode=debug'
    alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0'
    alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1'
    alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests'

    (these commands will be executed whenever you're openning or switching terminal to folder containing .autoenv file)

  2. To setup this automation for bash, execute the following line (it will append your .bashrc file):

    > ~/.bashrc">
    echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
  3. Lastly add execution previliges to your .autoenv file:

    chmod +x .autoenv
    

    (for safety, only .autoenv with previligies will be executed)

Explanation

The mentioned line appends your .bashrc file with 2 commands:

  1. autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } - this declares the autoenv() function, which executes .autoenv file if it exists in current work dir and has execution previligies
  2. cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv - this extends behaviour of cd command, to make it execute autoenv() function each time you change folder in terminal or open new terminal

Best Practices

Use Miniconda for GPU environments

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. It also allows you to acccess your environments globally.

Example installation:

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh

Create new conda environment:

conda create -n myenv python=3.8
conda activate myenv
Use automatic code formatting

Use pre-commit hooks to standardize code formatting of your project and save mental energy.
Simply install pre-commit package with:

pip install pre-commit

Next, install hooks from .pre-commit-config.yaml:

pre-commit install

After that your code will be automatically reformatted on every new commit.
Currently template contains configurations of black (python code formatting), isort (python import sorting), flake8 (python code analysis) and prettier (yaml formating).

To reformat all files in the project use command:

pre-commit run -a
Set private environment variables in .env file

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.

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:

MY_VAR=/home/user/my_system_path

All variables from .env are loaded in run.py automatically.

Hydra allows you to reference any env variable in .yaml configs like this:

path_to_data: ${oc.env:MY_VAR}
Name metrics using '/' character

Depending on which logger you're using, it's often useful to define metric name with / character:

self.log("train/loss", loss)

This way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.

Use torchmetrics

Use official torchmetrics library to ensure proper calculation of metrics. This is especially important for multi-GPU training!

For example, instead of calculating accuracy by yourself, you should use the provided Accuracy class like this:

from torchmetrics.classification.accuracy import Accuracy


class LitModel(LightningModule):
    def __init__(self)
        self.train_acc = Accuracy()
        self.val_acc = Accuracy()

    def training_step(self, batch, batch_idx):
        ...
        acc = self.train_acc(predictions, targets)
        self.log("train/acc", acc)
        ...

    def validation_step(self, batch, batch_idx):
        ...
        acc = self.val_acc(predictions, targets)
        self.log("val/acc", acc)
        ...

Make sure to use different metric instance for each step to ensure proper value reduction over all GPU processes.

Torchmetrics provides metrics for most use cases, like F1 score or confusion matrix. Read documentation for more.

Follow PyTorch Lightning style guide

The style guide is available here.

  1. Be explicit in your init. Try to define all the relevant defaults so that the user doesn’t have to guess. Provide type hints. This way your module is reusable across projects!

    class LitModel(LightningModule):
        def __init__(self, layer_size: int = 256, lr: float = 0.001):
  2. Preserve the recommended method order.

    class LitModel(LightningModule):
    
        def __init__():
            ...
    
        def forward():
            ...
    
        def training_step():
            ...
    
        def training_step_end():
            ...
    
        def training_epoch_end():
            ...
    
        def validation_step():
            ...
    
        def validation_step_end():
            ...
    
        def validation_epoch_end():
            ...
    
        def test_step():
            ...
    
        def test_step_end():
            ...
    
        def test_epoch_end():
            ...
    
        def configure_optimizers():
            ...
    
        def any_extra_hook():
            ...
Version control your data and models with DVC

Use DVC to version control big files, like your data or trained ML models.
To initialize the dvc repository:

dvc init

To start tracking a file or directory, use dvc add:

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:

git add data/MNIST.dvc data/.gitignore
git commit -m "Add raw data"
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 add setup.py file:

=1.10.0", "pytorch-lightning>=1.4.0", "hydra-core>=1.1.0", ], packages=find_packages(), )">
from setuptools import find_packages, setup


setup(
    name="src",  # change "src" folder name to your project name
    version="0.0.0",
    description="Describe Your Cool Project",
    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(),
)

Now your project can be installed from local files:

pip install -e .

Or directly from git repository:

pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade

So any file can be easily imported into any other file like so:

from project_name.models.mnist_model import MNISTLitModel
from project_name.datamodules.mnist_datamodule import MNISTDataModule

Other Repositories

Inspirations

This template was inspired by: PyTorchLightning/deep-learninig-project-template, drivendata/cookiecutter-data-science, tchaton/lightning-hydra-seed, Erlemar/pytorch_tempest, lucmos/nn-template.

Useful repositories

License

This project is licensed under the MIT License.

MIT License

Copyright (c) 2021 ashleve

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.




DELETE EVERYTHING ABOVE FOR YOUR PROJECT


Your Project Name

PyTorch Lightning Config: Hydra Template
Paper Conference

Description

What it does

How to run

Install dependencies

# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name

# [OPTIONAL] create conda environment
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

Train model with default configuration

# train on CPU
python run.py trainer.gpus=0

# train on GPU
python run.py trainer.gpus=1

Train model with chosen experiment configuration from configs/experiment/

python run.py experiment=experiment_name.yaml

You can override any parameter from command line like this

python run.py trainer.max_epochs=20 datamodule.batch_size=64
Comments
  • MultiGPU Error

    MultiGPU Error

    (update to indicate the bug version is V1.1)

    Thanks for your awesome work!

    Reproduce

    Directly download the main code (ReleaseV1.1) and execute this line(or any line using multiple GPUs)

    python run.py trainer.gpus=[0,1]
    

    Environment

    Machine

    1080Ti x 4, Ubuntu18.04

    conda env showed with pip list

    Package                           Version
    --------------------------------- ---------
    absl-py                           0.15.0
    aiohttp                           3.8.0
    aiosignal                         1.2.0
    alembic                           1.6.5
    antlr4-python3-runtime            4.8
    anyio                             3.3.4
    argon2-cffi                       21.1.0
    async-timeout                     4.0.0
    attrs                             21.2.0
    autopage                          0.4.0
    Babel                             2.9.1
    backcall                          0.2.0
    backports.entry-points-selectable 1.1.0
    backports.functools-lru-cache     1.6.4
    black                             21.10b0
    bleach                            4.1.0
    brotlipy                          0.7.0
    cachetools                        4.2.4
    certifi                           2021.10.8
    cffi                              1.15.0
    cfgv                              3.3.1
    chardet                           4.0.0
    charset-normalizer                2.0.7
    click                             8.0.3
    cliff                             3.9.0
    cmaes                             0.8.2
    cmd2                              2.2.0
    colorama                          0.4.4
    colorlog                          6.5.0
    commonmark                        0.9.1
    conda                             4.10.3
    conda-package-handling            1.7.3
    configparser                      5.0.2
    cryptography                      35.0.0
    cycler                            0.10.0
    debugpy                           1.5.1
    decorator                         5.1.0
    defusedxml                        0.7.1
    distlib                           0.3.3
    docker-pycreds                    0.4.0
    entrypoints                       0.3
    filelock                          3.3.1
    flake8                            4.0.1
    frozenlist                        1.2.0
    fsspec                            2021.10.1
    future                            0.18.2
    gitdb                             4.0.9
    GitPython                         3.1.24
    google-auth                       2.3.3
    google-auth-oauthlib              0.4.6
    googledrivedownloader             0.4
    greenlet                          1.1.2
    grpcio                            1.41.0
    hydra-colorlog                    1.1.0
    hydra-core                        1.1.1
    hydra-optuna-sweeper              1.1.1
    identify                          2.3.3
    idna                              3.3
    importlib-resources               5.4.0
    iniconfig                         1.1.1
    ipykernel                         6.4.1
    ipython                           7.28.0
    ipython-genutils                  0.2.0
    ipywidgets                        7.6.5
    isodate                           0.6.0
    isort                             5.9.3
    jedi                              0.18.0
    Jinja2                            3.0.2
    joblib                            1.1.0
    json5                             0.9.6
    jsonschema                        4.1.0
    jupyter-client                    7.0.6
    jupyter-core                      4.8.1
    jupyter-server                    1.11.1
    jupyterlab                        3.2.0
    jupyterlab-pygments               0.1.2
    jupyterlab-server                 2.8.2
    jupyterlab-widgets                1.0.2
    kiwisolver                        1.3.2
    llvmlite                          0.37.0
    Mako                              1.1.5
    mamba                             0.17.0
    Markdown                          3.3.4
    MarkupSafe                        2.0.1
    matplotlib                        3.4.3
    matplotlib-inline                 0.1.3
    mccabe                            0.6.1
    mistune                           0.8.4
    mkl-fft                           1.3.0
    mkl-random                        1.2.2
    mkl-service                       2.4.0
    msgpack                           1.0.2
    multidict                         5.2.0
    mypy-extensions                   0.4.3
    nbclassic                         0.3.2
    nbclient                          0.5.4
    nbconvert                         6.2.0
    nbformat                          5.1.3
    nest-asyncio                      1.5.1
    networkx                          2.6.3
    nodeenv                           1.6.0
    notebook                          6.4.4
    numba                             0.54.1
    numpy                             1.20.3
    oauthlib                          3.1.1
    olefile                           0.46
    omegaconf                         2.1.1
    optuna                            2.10.0
    packaging                         21.0
    pandas                            1.3.4
    pandocfilters                     1.5.0
    parso                             0.8.2
    pathspec                          0.9.0
    pathtools                         0.1.2
    pbr                               5.6.0
    pexpect                           4.8.0
    pickleshare                       0.7.5
    Pillow                            8.3.1
    pip                               21.3.1
    platformdirs                      2.4.0
    plotly                            5.3.1
    pluggy                            1.0.0
    pre-commit                        2.15.0
    prettytable                       2.2.1
    prometheus-client                 0.11.0
    promise                           2.3
    prompt-toolkit                    3.0.20
    protobuf                          3.18.1
    psutil                            5.8.0
    ptyprocess                        0.7.0
    pudb                              2021.2.2
    py                                1.10.0
    pyasn1                            0.4.8
    pyasn1-modules                    0.2.8
    pycodestyle                       2.8.0
    pycosat                           0.6.3
    pycparser                         2.20
    pyDeprecate                       0.3.1
    pyflakes                          2.4.0
    Pygments                          2.10.0
    PyGSP                             0.5.1
    pyOpenSSL                         21.0.0
    pyparsing                         2.4.7
    pyperclip                         1.8.2
    pyrsistent                        0.18.0
    PySocks                           1.7.1
    pytest                            6.2.5
    python-dateutil                   2.8.2
    python-dotenv                     0.19.1
    python-editor                     1.0.4
    pytorch-lightning                 1.5.0
    pytz                              2021.3
    PyYAML                            6.0
    pyzmq                             22.3.0
    ray                               1.7.0
    rdflib                            6.0.2
    redis                             3.5.3
    regex                             2021.11.1
    requests                          2.26.0
    requests-oauthlib                 1.3.0
    requests-unixsocket               0.2.0
    rich                              10.12.0
    rsa                               4.7.2
    ruamel-yaml-conda                 0.15.80
    scikit-learn                      1.0
    scikit-sparse                     0.4.6
    scikit-umfpack                    0.3.2
    scipy                             1.7.1
    seaborn                           0.11.2
    Send2Trash                        1.8.0
    sentry-sdk                        1.4.3
    setuptools                        58.0.4
    sh                                1.14.2
    shortuuid                         1.0.1
    six                               1.16.0
    sklearn                           0.0
    smmap                             5.0.0
    sniffio                           1.2.0
    SQLAlchemy                        1.4.26
    stevedore                         3.5.0
    subprocess32                      3.5.4
    tenacity                          8.0.1
    tensorboard                       2.7.0
    tensorboard-data-server           0.6.1
    tensorboard-plugin-wit            1.8.0
    termcolor                         1.1.0
    terminado                         0.12.1
    testpath                          0.5.0
    thgsp                             0.1.0
    threadpoolctl                     3.0.0
    toml                              0.10.2
    tomli                             1.2.2
    torch                             1.8.2
    torch-cluster                     1.5.9
    torch-geometric                   2.0.1
    torch-scatter                     2.0.8
    torch-sparse                      0.6.12
    torch-spline-conv                 1.2.1
    torchaudio                        0.8.2
    torchmetrics                      0.5.1
    torchvision                       0.9.2
    tornado                           6.1
    tqdm                              4.62.3
    traitlets                         5.1.0
    typing-extensions                 3.10.0.2
    urllib3                           1.26.7
    urwid                             2.1.2
    urwid-readline                    0.13
    virtualenv                        20.10.0
    wandb                             0.12.6
    wcwidth                           0.2.5
    webencodings                      0.5.1
    websocket-client                  1.2.1
    Werkzeug                          2.0.2
    wheel                             0.37.0
    widgetsnbextension                3.5.1
    yacs                              0.1.8
    yarl                              1.7.2
    yaspin                            2.1.0
    zipp                              3.6.0
    

    Error Info

    raceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/multiprocessing/spawn.py", line 116, in spawn_main
        exitcode = _main(fd, parent_sentinel)
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/multiprocessing/spawn.py", line 125, in _main
        prepare(preparation_data)
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/multiprocessing/spawn.py", line 236, in prepare
        _fixup_main_from_path(data['init_main_from_path'])
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/multiprocessing/spawn.py", line 287, in _fixup_main_from_path
        main_content = runpy.run_path(main_path,
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/runpy.py", line 264, in run_path
        code, fname = _get_code_from_file(run_name, path_name)
      File "/home/amax/anaconda3/envs/pyg18/lib/python3.8/runpy.py", line 234, in _get_code_from_file
        with io.open_code(decoded_path) as f:
    FileNotFoundError: [Errno 2] No such file or directory: '/data/dbw/projects/lightning-hydra-template-main/logs/runs/2021-11-04/10-14-23/run.py'
    
    bug 
    opened by bwdeng20 11
  • Code quality workflow

    Code quality workflow

    Hi, Thank you for the great template, I use it a lot 😁

    I enhanced the check code formatting to run only on the changed files, and move it to separate a workflow file. From experience, sometimes pre-commit's output is large, so IMHO the separation is needed :)

    I also fixed a small English mistake.

    Thank you, Eli

    Edit: consider badging the repository with pre-commit ;)

    opened by elisim 9
  • `mode=debug` is not overriding the defaults list when running alongside an experiment config

    `mode=debug` is not overriding the defaults list when running alongside an experiment config

    When I use python run.py experiment=something mode=debug, I expect the trainer to be overridden by the debug.yaml one, but in fact this doesn't happen (looking at the config tree reveals that the default.yaml is being used. Additionally, I am also trying to disable loggers and callbacks in this mode, by setting them to null or none.yaml. However, they are also still being loaded.

    I assume that this is because the experiment config also has an - override /trainer, but my knowledge of hydra is not enough to figure out why this isn't working.

    enhancement investigation 
    opened by mariomeissner 9
  • hydra + multirun + ddp error

    hydra + multirun + ddp error

    Hello. I found that the combination of multi-run and DDP doesn't work with the following command.

    python run.py -m datamodule.batch_size=32,64 trainer=ddp trainer.max_epochs=2

    Can you have a look at this?

    bug 
    opened by shim94kr 9
  • Instantiate model using Hydra

    Instantiate model using Hydra

    Hydra allows us to recursively instantiate classes, which means we don't need to pass SimpleDenseNet parameters to MNISTLitModel, but can let Hydra create the class for us.

    This cleans up the code, makes it more modular and reusable, and neatly groups the parameters together.

    This leaves one open question though: what happens in

    self.save_hyperparameters(logger=False)
    

    Does it pick up on those nested hyper parameters?

    opened by nils-werner 9
  • Multi-GPU training on DDP mode will log multiple times

    Multi-GPU training on DDP mode will log multiple times

    I notice when I use +trainer.accelerator="ddp", the log file have repeated logs(The number of repeats is equal to the number of GPUs), refer to official docs, "Lightning implementation of DDP calls your script under the hood multiple times with the correct environment variables:". So we need a solution to handle this problem since DDP mode is much faster than DDP_spawn.

    bug enhancement help wanted 
    opened by LuoXin-s 9
  • Update wandb_callbacks.py

    Update wandb_callbacks.py

    UploadCodeAsArtifact: Add the functionality to use git to decide which files are source files. Can upload all files that are not ignored by git instead of all '*.py' file. UploadCodeAsArtifact: Add @rank_zero_only UploadCheckpointsAsArtifact: Add @rank_zero_only UploadCheckpointsAsArtifact: ckpts are output of the run, so use experiment.log_artifact(ckpts) instead

    opened by zhengyu-yang 8
  • Multi-GPU bugs, AttributeError: Can't pickle local object 'log_hyperparameters.<locals>.<lambda>'

    Multi-GPU bugs, AttributeError: Can't pickle local object 'log_hyperparameters..'

    When I use Multi-GPU with 4 3090, I ran into AttributeError: Can't pickle local object 'log_hyperparameters..', it seems due to trainer.logger.log_hyperparams = lambda params: None trick in log_hyperparameters.

    Traceback (most recent call last): File "/ghome/luoxin/projects/liif-lightning-hydra/run.py", line 34, in main return train(config) File "/ghome/luoxin/projects/liif-lightning-hydra/src/train.py", line 78, in train trainer.fit(model=model, datamodule=datamodule) File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 499, in fit self.dispatch() File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/trainer/trainer.py", line 546, in dispatch self.accelerator.start_training(self) File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/accelerators/accelerator.py", line 73, in start_training self.training_type_plugin.start_training(trainer) File "/opt/conda/lib/python3.8/site-packages/pytorch_lightning/plugins/training_type/ddp_spawn.py", line 108, in start_training mp.spawn(self.new_process, **self.mp_spawn_kwargs) File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 230, in spawn return start_processes(fn, args, nprocs, join, daemon, start_method='spawn') File "/opt/conda/lib/python3.8/site-packages/torch/multiprocessing/spawn.py", line 179, in start_processes process.start() File "/opt/conda/lib/python3.8/multiprocessing/process.py", line 121, in start self._popen = self._Popen(self) File "/opt/conda/lib/python3.8/multiprocessing/context.py", line 284, in _Popen return Popen(process_obj) File "/opt/conda/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 32, in init super().init(process_obj) File "/opt/conda/lib/python3.8/multiprocessing/popen_fork.py", line 19, in init self._launch(process_obj) File "/opt/conda/lib/python3.8/multiprocessing/popen_spawn_posix.py", line 47, in _launch reduction.dump(process_obj, fp) File "/opt/conda/lib/python3.8/multiprocessing/reduction.py", line 60, in dump ForkingPickler(file, protocol).dump(obj) AttributeError: Can't pickle local object 'log_hyperparameters..'

    bug 
    opened by LuoXin-s 7
  • Testing best model checkpoint after training model with multiple GPUs

    Testing best model checkpoint after training model with multiple GPUs

    Hello.

    First off, I am a huge fan of this project and want to thank its maintainers for their diligent efforts!

    I noticed that in the default train.py example, the maintainers of this project would have users call trainer.test() on the best model checkpoint resulting from (single/multi) GPU training beforehand (if the test CLI argument is set to True). In such a case, I am a bit concerned about how Lightning will attempt to report its test results to users through the use of a logging tool like WandB. For example, I believe it is typically recommended to run a trained PyTorch/Lightning model on the test dataset(s) using only a single GPU to avoid any misreporting of test results.

    Is such an option available with this project layout?

    question 
    opened by amorehead 6
  • Can you share a method for NLP users to deal with Vocab Size?

    Can you share a method for NLP users to deal with Vocab Size?

    Hi,

    This is a great template!

    However, I have yet to find a way to deal with vocab_size which is derived from datasets and cannot be preset in advance.

    Do you know an elegant way to do it?

    question 
    opened by yipliu 6
  • Refactor dockerfile

    Refactor dockerfile

    Hello, I am learning PyTorch Lightning and Hydra and come across finding this repo. Really useful and great work!

    I made some changes in Dockerfile so the changes on the host machine can reflect within the container. When developing/training a model, mounting the files into the container instead of copying is more convenient and time-saving as all the changes I made and all the generated logs will be saved in the host machine.

    Do you think it worth merging to the main branch or should be added to the dockerfiles branch?

    opened by HotThoughts 6
  • Pytorch 2.0

    Pytorch 2.0

    New feature Pytorch 2.0 compile Change pytorch-lightning(deprecated) to lightning Pytorch 1.13.1 compatible with python 3.11 Only blocked tests torchvision but they are working to compatible with Python 3.11 Deleted Python 3.7 tests(very deprecated)

    opened by johnnynunez 2
  • Assign stage flag from `train.yaml`

    Assign stage flag from `train.yaml`

    There is a def setup(self, stage: Optional[str] = None): stage flag in the datamodule, will it be possible to initiate stage -> train or stage-> test from train.yaml If look in train.yaml

    # set False to skip model training
    train: True
    
    # evaluate on test set, using best model weights achieved during training
    # lightning chooses best weights based on the metric specified in checkpoint callback
    test: True
    

    Just to save memory

    opened by abhijeetdhakane 0
  • `train.log` doesn't show training progress bar

    `train.log` doesn't show training progress bar

    Awesome project honestly! I'm using your project right now but having some issues while training with SLURM, since I can't see the terminal of the scheduled nodes, I can only check train.log or slurm.log; but both of those log doesn't show the training progress bar (stop at Start training or some DDP warnings); but there are still logs on tensorboard and new ckpts. I've tried to disable colorlogs too but it still doesn't show up. image

    opened by bomcon123456 0
  • Support Intel Arc

    Support Intel Arc

    You can add new device: intel arc now is supported by Pytorch: https://github.com/intel/intel-extension-for-pytorch/releases/tag/v1.10.200%2Bgpu python -m pip install intel_extension_for_pytorch intel-extension-for-pytorch

    enhancement 
    opened by johnnynunez 2
  • How to define a conditional search space ?

    How to define a conditional search space ?

    Hi!

    I want to search the best optimizer for the given "mnist_example" from SGD and Adam. However, for SGD, I also want to know which momentum value is the best (which Adam doesn't need), but for Adam, I need search beta.

    Therefore, how can we define such a hparams_search/name.yaml file?

    hydra:
      ...
      sweeper:
      ...
        params:
          model.optimizer._target_: choice("torch.optim.SGD", "torch.optim.Adam")
           ......
    

    Thanks so much!

    enhancement question 
    opened by tianshuocong 8
  • Add Custom Dataloader Example into template

    Add Custom Dataloader Example into template

    @ashleve this is an excellent template. But if you add some files, then it will be usable for a lot many audiences. I felt a little tedious for data modules. The template has an MNIST data module which is 'standard.' In many used cases people use custom Dataset, If you add those, then it will be more helpful.

    Just an example I tried:

    datamodule -> component -> dataloader.py

    class FaceLandmarksDataset(Dataset):
        """Face Landmarks dataset."""
    
        def __init__(self, csv_file, root_dir, transform=None):
            """
            Args:
                csv_file (string): Path to the csv file with annotations.
                root_dir (string): Directory with all the images.
                transform (callable, optional): Optional transform to be applied
                    on a sample.
            """
            self.landmarks_frame = pd.read_csv(csv_file)
            self.root_dir = root_dir
            self.transform = transform
    
        def __len__(self):
            return len(self.landmarks_frame)
    
        def __getitem__(self, idx):
            if torch.is_tensor(idx):
                idx = idx.tolist()
    
            img_name = os.path.join(self.root_dir,
                                    self.landmarks_frame.iloc[idx, 0])
            image = io.imread(img_name)
            landmarks = self.landmarks_frame.iloc[idx, 1:]
            landmarks = np.array([landmarks])
            landmarks = landmarks.astype('float').reshape(-1, 2)
            sample = {'image': image, 'landmarks': landmarks}
    
            if self.transform:
                sample = self.transform(sample)
    
            return sample
    

    from https://pytorch.org/tutorials/beginner/data_loading_tutorial.html

    then datamodules -> XYZ_datamodule.py

    A DataModule implements 5 key methods:
            def prepare_data(self):
                # things to do on 1 GPU/TPU (not on every GPU/TPU in DDP)
                # download data, pre-process, split, save to disk, etc...
            def setup(self, stage):
                # things to do on every process in DDP
                # load data, set variables, etc...
            def train_dataloader(self):
                # return train dataloader
            def val_dataloader(self):
                # return validation dataloader
            def test_dataloader(self):
                # return test dataloader
            def teardown(self):
                # called on every process in DDP
                # clean up after fit or test
    

    I ran into errors while doing the above, my datamodule_XYZ.yaml like:

    _target_:src.datamodules.XYZ_datamodule.XZYDataModule
    datasets:
           train:
           _target_: src.datamodules.components.dataloader.FaceLandmarksDataset
           csv_file: ...
           root_dir: ...
           transform:
               _target_: ...
    
          val:
    
          test:
    
    batches:
       train:10
       val:10
       test:10
    

    ...

    enhancement 
    opened by abhijeetdhakane 3
Releases(v1.4.0)
  • v1.4.0(Jul 16, 2022)

    What's Changed

    • Adapt template to hydra 1.2 - no more changing the working directory by default
    • Rename test.py and test.yaml to eval.py and eval.yaml (so as to avoid confusion with project tests)
    • Move train.py and eval.py inside src/
    • Add pyrootutils package for standardizing the project root setup in train.py and eval.py
    • Rename pipelines to tasks
    • Create a separate folder for tasks
    • Add task_name to main config, which determines hydra output folder path
    • Introduce @task_wrapper decorator for applying utilities before and after the task is executed
    • Standardize what is returned from tasks: Tuple[metric_dict, object_dict]
    • Add SimpleDenseNet config to model config with recursive instantiation
    • Add optimizer config to model config using _partial_: true
    • Remove _convert_=partial from trainer instantiation (no longer needed since recent lightning release)
    • Add ckpt_path to main config, trainer.fit() and trainer.test(), for compatibility with recent lightning release
    • Add resetting val_acc_best metric at the start of the training to prevent storing results from validation sanity checks
    • Add verifying logger is not None before logging hparams
    • Add tags to main config
    • Add prompting user to input tags when none are provide to utils.extras()
    • Remove experiment name (since tags and task_name are enough)
    • Rename config to cfg since it's the standard naming convention in hydra
    • Split utils into multiple files: utils.py, rich_utils.py, pylogger.py
    • Add utils.instantiate_callbacks() and utils.instantiate_loggers() to reduce the boilerplate in tasks
    • Add utils.get_metric_value() for safely retrieving optimized metric.
    • Rename utils.finish() to utils.close_loggers()
    • Move extra config utils to configs/extras/default.yaml
    • Replace deprecated trainer.gpus argument with trainer.accelerator and trainer.devices
    • Add separate trainer configs for GPU, CPU, simulating DDP on CPU and MPS accelerator (Accelerated PyTorch Training on Mac)
    • Add hydra.mode=MULTIRUN to mnist_optuna.yaml config (so using -m is no longer needed when attaching this config)
    • Update mnist_opuna.yaml for compatibility with new search space syntax in hydra 1.2
    • Disable callbacks in debug configs by default (fixes debug/overfit.yaml)
    • Disable hydra command line debug logger in debug configs by default
    • Split callbacks config into multiple files
    • Replace setup.cfg with pyproject.toml since it's a more versatile standard (PEP 518)
    • Add pre-commit hooks: pyupgrade (automatically upgrading python syntax to newer version), bandit (security linter), codespell (spelling linter), mdformat (markdown formatting)
    • Redesign testing and add tests covering ddp, multirun, loggers, resuming training and evaluation
    • Implement CI workflows with GitHub Actions: executing pytest, test code coverage measuring, code quality testing for main branch and PRs
    • Add depandabot
    • Add pull request template
    • Add setup.py
    • Add Makefile
    • Update README.md

    Contributors

    @nils-werner @johnnynunez @elisim @yu-xiang-wang @yipliu @Gxinhu @binlee52

    Source code(tar.gz)
    Source code(zip)
  • v1.3(Feb 19, 2022)

    The template has been significantly refactored.

    List of changes:

    • Introduce multiple pipelines, to showcase example of how one can separate training from evaluation, run.py has been replaced by train.py and test.py
    • The mode group config has been removed since it was confusing, now every run is treated as an experiment, and debugging is moved to a separate config group
    • Introduce debug config group
    • Introduce log_dir config group
    • Move wandb callbacks to the branch wandb-callbacks to make template logger-agnostic
    • Refactor rich config printing, now all config groups are always printed instead of just the pre-selected ones, but you can still decide on the print order
    • Add nbstripout to pre-commit hooks, for automatic clearing of jupyter notebooks outputs before commit
    • Update packages in requirements.txt and pre-commit-config.yaml to newest versions
    • Remove some of the unimportant default optuna parameters in mnist_optuna.yaml and add more explanatory comments
    • Remove no longer needed utilities from utils.extras()
    • Add config flag for skipping training
    • Fix hydra package versions in requirements.txt for mac compatibility
    • Remove redundant parts in filenames: mnist_model.yaml -> mnist.yaml, mnist_datamodule.yaml -> datamodule.yaml
    • Change mnist_model.py -> mnist_module.py and MNISTLitModel -> MNISTLitModule
    • Rename folder modules/ to components/
    • Change accelerator="ddp" to strategy="ddp" since it was depracated by lightning
    • Remove trainer arguments depracated by lightning: weight summary and progress_bar_refresh_rate
    • Specify black profile for isort inside .pre-commit-config.yaml just in case someone deletes the setup.cfg
    • Specify testpath in setup.cfg so pytest knows all test files are placed only in tests/ folder
    • Allow for using relative checkpoint paths
    • Rename folder bash to scripts
    • Introduce vendor dir as a "best practice" for storing third party code
    • Introduce local config files in configs/local/, which can be used for storing machine/user specific configurations, e.g. configuration of slurm cluster
    • Unify logging directories structure
    • Add RichModelSummary to default callbacks
    • Fix missing parameter in "Accessing datamodule attributes" trick in README.md
    • General README.md improvements

    Special thanks to: @nils-werner @charlesincharge @Steve-Tod for their PRs.

    Source code(tar.gz)
    Source code(zip)
  • v1.2(Nov 19, 2021)

    List of changes:

    • Update template for compatibility with lightning v1.5 and pytorch v1.10
    • General documentation improvements
    • Move LICENSE to README.md
    • Add manual resetting of metrics at the end of every epoch, to make sure no one makes hard to spot calculation mistakes
    • Add experiment mode to all experiment configs
    • Improve logging paths for experiment mode
    • Add MaxMetric to model, for computation of best so far validation accuracy
    • Add RichProgressBar to default callbacks for the pretty formatted progress bar
    • Get rid of the trick for preventing auto hparam logging, since lightning now supports it with self.save_hyperparameters(logger=False)
    • Add self.save_hyperparameters() to datamodule since lightinng now supports it
    • Deprecate Apex support since native pytorch mixed-precision is better
    • Deprecate bash script for conda setup since installation commands change too often to maintain it
    • Change trainer.terminate_on_nan debug option to trainer.detect_anomaly for compatibility with lightning v1.5
    • Specify model and datamodule during trainer.test(), for compatibility with lightning v1.5
    • Remove configs/trainer/all_params.yaml
    • Make hyperparameter optimization compatible with lightning v1.5
    • Specify that EarlyStopping patience is counted in validation epochs and not in training epochs.
    • Add a new way for accessing datamodule attributes to the README.md
    • Make debug mode automatically set the level of all command-line loggers to DEBUG
    • Make debug mode automatically set the trainer config to debug.yaml
    • Add generator seed to prevent test data leaking to train data in datamodule.setup() when seed is not set up
    • Move Dockerfile to dockerfiles branch
    • Modifiy configs/trainer/debug.yaml to enable some debug options
    • Remove unused if config.get("debug"): in extras

    Special thanks for PRs to: @CharlesGaydon, @eungbean, @gscriva

    Source code(tar.gz)
    Source code(zip)
  • v1.1(Sep 28, 2021)

    • introduce different running modes: default, debug, experiment
    • fix pytorch installation in setup_conda.sh
    • fix incorrect calculation of precision, recall and f1 score in wandb callback
    • add _self_ to config.yaml for compatibility with hydra1.1
    • fix setting seed in train.py so it's skipped when seed=null
    • add exception message when trying to use wandb callbacks with trainer.fast_dev_run=true
    • change axis=-1 to dim=-1 in LogImagePredictions callback
    • add 'Reproducibilty' section to README.md
    • UploadCodeAsArtifact: now uploads all files that are not ignored by git instead of all *.py files.
    • UploadCheckpointsAsArtifact: now uses experiment.log_artifact(ckpts) and uploads also on keyboard interrupt
    Source code(tar.gz)
    Source code(zip)
  • v1.0(Jul 21, 2021)

    • 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 README.md
    Source code(tar.gz)
    Source code(zip)
Owner
Łukasz Zalewski
CS student here. Coding for fun. Mostly reinventing the wheel. Investigating the science of intelligence.
Łukasz Zalewski
MlTr: Multi-label Classification with Transformer

MlTr: Multi-label Classification with Transformer This is official implement of "MlTr: Multi-label Classification with Transformer". Abstract The task

η¨‹ζ˜Ÿ 38 Nov 08, 2022
My coursework for Machine Learning (2021 Spring) at National Taiwan University (NTU)

Machine Learning 2021 Machine Learning (NTU EE 5184, Spring 2021) Instructor: Hung-yi Lee Course Website : (https://speech.ee.ntu.edu.tw/~hylee/ml/202

100 Dec 26, 2022
Code Repository for The Kaggle Book, Published by Packt Publishing

The Kaggle Book Data analysis and machine learning for competitive data science Code Repository for The Kaggle Book, Published by Packt Publishing "Lu

Packt 1.6k Jan 07, 2023
Replication Package for "An Empirical Study of the Effectiveness of an Ensemble of Stand-alone Sentiment Detection Tools for Software Engineering Datasets"

Replication Package for "An Empirical Study of the Effectiveness of an Ensemble of Stand-alone Sentiment Detection Tools for Software Engineering Data

2 Oct 06, 2022
This repository contains the implementation of the paper Contrastive Instance Association for 4D Panoptic Segmentation using Sequences of 3D LiDAR Scans

Contrastive Instance Association for 4D Panoptic Segmentation using Sequences of 3D LiDAR Scans This repository contains the implementation of the pap

Photogrammetry & Robotics Bonn 40 Dec 01, 2022
Code for "The Intrinsic Dimension of Images and Its Impact on Learning" - ICLR 2021 Spotlight

dimensions Estimating the instrinsic dimensionality of image datasets Code for: The Intrinsic Dimensionaity of Images and Its Impact On Learning - Phi

Phil Pope 41 Dec 10, 2022
Code for the paper "Zero-shot Natural Language Video Localization" (ICCV2021, Oral).

Zero-shot Natural Language Video Localization (ZSNLVL) by Pseudo-Supervised Video Localization (PSVL) This repository is for Zero-shot Natural Languag

Computer Vision Lab. @ GIST 37 Dec 27, 2022
A tool for making map images from OpenTTD save games

OpenTTD Surveyor A tool for making map images from OpenTTD save games. This is not part of the main OpenTTD codebase, nor is it ever intended to be pa

Aidan Randle-Conde 9 Feb 15, 2022
Real Time Object Detection and Classification using Yolo Algorithm.

Real time Object detection & Classification using YOLO algorithm. Real Time Object Detection and Classification using Yolo Algorithm. What is Object D

Ketan Chawla 1 Apr 17, 2022
Code repository for "Stable View Synthesis".

Stable View Synthesis Code repository for "Stable View Synthesis". Setup Install the following Python packages in your Python environment - numpy (1.1

Intelligent Systems Lab Org 195 Dec 24, 2022
Acoustic mosquito detection code with Bayesian Neural Networks

HumBugDB Acoustic mosquito detection with Bayesian Neural Networks. Extract audio or features from our large-scale dataset on Zenodo. This repository

31 Nov 28, 2022
[CVPRW 21] "BNN - BN = ? Training Binary Neural Networks without Batch Normalization", Tianlong Chen, Zhenyu Zhang, Xu Ouyang, Zechun Liu, Zhiqiang Shen, Zhangyang Wang

BNN - BN = ? Training Binary Neural Networks without Batch Normalization Codes for this paper BNN - BN = ? Training Binary Neural Networks without Bat

VITA 40 Dec 30, 2022
A Fast and Accurate One-Stage Approach to Visual Grounding, ICCV 2019 (Oral)

One-Stage Visual Grounding ***** New: Our recent work on One-stage VG is available at ReSC.***** A Fast and Accurate One-Stage Approach to Visual Grou

Zhengyuan Yang 118 Dec 05, 2022
A new test set for ImageNet

ImageNetV2 The ImageNetV2 dataset contains new test data for the ImageNet benchmark. This repository provides associated code for assembling and worki

186 Dec 18, 2022
Position detection system of mobile robot in the warehouse enviroment

Autonomous-Forklift-System About | GUI | Tests | Starting | License | Author | 🎯 About An application that run the autonomous forklift paletization a

Kamil GoΕ› 1 Nov 24, 2021
Vision Transformer for 3D medical image registration (Pytorch).

ViT-V-Net: Vision Transformer for Volumetric Medical Image Registration keywords: vision transformer, convolutional neural networks, image registratio

Junyu Chen 192 Dec 20, 2022
This repo is the code release of EMNLP 2021 conference paper "Connect-the-Dots: Bridging Semantics between Words and Definitions via Aligning Word Sense Inventories".

Connect-the-Dots: Bridging Semantics between Words and Definitions via Aligning Word Sense Inventories This repo is the code release of EMNLP 2021 con

12 Nov 22, 2022
FcaNet: Frequency Channel Attention Networks

FcaNet: Frequency Channel Attention Networks PyTorch implementation of the paper "FcaNet: Frequency Channel Attention Networks". Simplest usage Models

327 Dec 27, 2022
LightHuBERT: Lightweight and Configurable Speech Representation Learning with Once-for-All Hidden-Unit BERT

LightHuBERT LightHuBERT: Lightweight and Configurable Speech Representation Learning with Once-for-All Hidden-Unit BERT | Github | Huggingface | SUPER

WangRui 46 Dec 29, 2022
Codebase for testing whether hidden states of neural networks encode discrete structures.

structural-probes Codebase for testing whether hidden states of neural networks encode discrete structures. Based on the paper A Structural Probe for

John Hewitt 349 Dec 17, 2022