/pytorch-ie-hydra

PyTorch-IE Hydra Template

Primary LanguagePython

PyTorch-IE-Hydra-Template

Python PyTorch Lightning Config: hydra Code style: black

A clean and scalable template to kickstart your deep learning based information extraction project πŸš€βš‘πŸ”₯
Click on Use this template to initialize new repository.
This project is heavily inspired by Lightning-Hydra-Template.

Suggestions are always welcome!


πŸ“Œ Introduction

Why you should use it:

  • Convenient all-in-one technology stack for deep learning based information extraction prototyping - allows you to rapidly iterate over new models, datasets and tasks on different hardware accelerators like CPUs, multi-GPUs or TPUs.
  • A collection of best practices for efficient workflow and reproducibility.
  • Thoroughly commented - you can use this repo as a reference and educational resource.

Why you shouldn't use it:

  • Not fitted for data engineering - the template configuration setup is not designed for building data processing pipelines that depend on each other.
  • Limits you as much as PyTorch-IE limits you.
  • PyTorch-IE and Hydra are still evolving and integrate many libraries, which means sometimes things break - for the list of currently known problems visit this page.

Main Technologies

PyTorch-IE - a lightweight information extraction (IE) technology stack built on top of PyTorch Lightning, Huggingface Datasets and Huggingface Hub for reproducible high-performance AI research.

Hydra - a framework for elegantly configuring 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.


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:

β”œβ”€β”€ configs                   <- Hydra configuration files
β”‚   β”œβ”€β”€ callbacks                <- Callbacks configs
β”‚   β”œβ”€β”€ datamodule               <- Datamodule configs
β”‚   β”œβ”€β”€ dataset                  <- Dataset configs
β”‚   β”œβ”€β”€ debug                    <- Debugging configs
β”‚   β”œβ”€β”€ experiment               <- Experiment configs
β”‚   β”œβ”€β”€ hparams_search           <- Hyperparameter search configs
β”‚   β”œβ”€β”€ local                    <- Local configs
β”‚   β”œβ”€β”€ logger                   <- Logger configs
β”‚   β”œβ”€β”€ model                    <- Model configs
β”‚   β”œβ”€β”€ paths                    <- Project paths configs
β”‚   β”œβ”€β”€ taskmodule               <- Taskmodule configs
β”‚   β”œβ”€β”€ trainer                  <- Trainer configs
β”‚   β”‚
β”‚   β”œβ”€β”€ predict.yaml          <- Main config for inference
β”‚   β”œβ”€β”€ evaluate.yaml         <- Main config for testing
β”‚   └── train.yaml            <- Main config for training
β”‚
β”œβ”€β”€ data                   <- Project data
β”‚
β”œβ”€β”€ dataset_builders       <- dataset builders
β”‚   β”œβ”€β”€ hf                   <- Huggingface
β”‚   └── pie                  <- PyTorch-IE
β”‚
β”œβ”€β”€ logs                   <- Logs generated by Hydra and PyTorch Lightning loggers
β”‚   (created on demand)
β”‚
β”œβ”€β”€ models                 <- Per default (see config parameter `save_dir`), trained models and their
β”‚   (created on demand)       respective taskmodules are copied to this location in a format to easily
β”‚                             load them with pytorch_ie.Auto* classes.
β”‚
β”œβ”€β”€ 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`.
β”‚
β”œβ”€β”€ scripts                <- Shell scripts
β”‚
β”œβ”€β”€ src                    <- Source code
β”‚   β”œβ”€β”€ datamodules              <- Lightning datamodules
β”‚   β”œβ”€β”€ models                   <- Pytorch-IE models
β”‚   β”œβ”€β”€ taskmodules              <- Pytorch-IE taskmodules
β”‚   β”œβ”€β”€ utils                    <- Utility scripts
β”‚   β”œβ”€β”€ vendor                   <- Third party code that cannot be installed using PIP/Conda
β”‚   β”‚
β”‚   β”œβ”€β”€ eval.py                  <- Run evaluation
β”‚   β”œβ”€β”€ predict.py               <- Run inference
β”‚   └── train.py                 <- Run training
β”‚
β”œβ”€β”€ tests                  <- Tests of any kind
β”‚
β”œβ”€β”€ .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 pre-commit hooks for code formatting
β”œβ”€β”€ Makefile                  <- Makefile with commands like `make train` or `make test`
β”œβ”€β”€ requirements.txt          <- File for installing python dependencies
β”œβ”€β”€ setup.cfg                 <- Configuration of linters and pytest
β”œβ”€β”€ setup.py                  <- File for installing project as a package
└── README.md

πŸš€  Quickstart

# clone project
git clone https://github.com/ChristophAlt/pytorch-ie-hydra-template.git
cd pytorch-ie-hydra-template

# [OPTIONAL] create conda environment
conda create -n myenv python=3.9
conda activate myenv

# install pytorch according to instructions
# https://pytorch.org/get-started/

# install requirements
pip install -r requirements.txt

# [OPTIONAL] symlink log directories and the default model directory to
# "$HOME/experiments/my-project" since they can grow a lot
bash setup_symlinks.sh $HOME/experiments/my-project

# [OPTIONAL] set any environment variables by creating an .env file
# 1. copy the provided example file:
cp .env.example .env
# 2. edit the .env file for your needs!

Template contains example with CONLL2003 Named Entity Recognition.
When running python train.py you should see something like this:

⚑  Your Superpowers

Override any config parameter from command line

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

python train.py trainer.max_epochs=20 model.learning_rate=1e-4

You can also add new parameters with + sign.

python train.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 train.py trainer=cpu

# train on 1 GPU
python train.py trainer=gpu

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

# train with DDP (Distributed Data Parallel) (4 GPUs)
python train.py trainer=ddp trainer.devices=4

# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python train.py trainer=ddp trainer.devices=4 trainer.num_nodes=2

# simulate DDP on CPU processes
python train.py trainer=ddp_sim trainer.devices=2

# accelerate training on mac
python train.py trainer=mps

Warning: Currently there are problems with DDP mode, read this issue to learn more.

Train with mixed precision
# train with pytorch native automatic mixed precision (AMP)
python train.py trainer=gpu +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 train.py logger=wandb

Note: Lightning provides convenient integrations with most popular logging frameworks. Learn more here.

Note: Using wandb requires you to setup account first. After that just complete the config as below.

Note: Click here to see example wandb dashboard generated with this template.

Train model with chosen experiment config
python train.py experiment=example

Note: Experiment configs are placed in configs/experiment/.

Attach some callbacks to run
python train.py callbacks=default

Note: Callbacks can be used for things such as as model checkpointing, early stopping and many more.

Note: Callbacks configs are placed in configs/callbacks/.

Use different tricks available in Pytorch Lightning
# gradient clipping may be enabled to avoid exploding gradients
python train.py +trainer.gradient_clip_val=0.5

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

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

# terminate training after 12 hours
python train.py +trainer.max_time="00:12:00:00"

Note: PyTorch Lightning provides about 40+ useful trainer flags.

Easily debug
# runs 1 epoch in default debugging mode
# changes logging directory to `logs/debugs/...`
# sets level of all command line loggers to 'DEBUG'
# enforces debug-friendly configuration
python train.py debug=default

# run 1 train, val and test loop, using only 1 batch
python train.py debug=fdr

# print execution time profiling
python train.py debug=profiler

# try overfitting to 1 batch
python train.py debug=overfit

# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
python train.py +trainer.detect_anomaly=true

# log second gradient norm of the model
python train.py +trainer.track_grad_norm=2

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

Note: Visit configs/debug/ for different debugging configs.

Resume training from checkpoint
python train.py ckpt_path="/path/to/ckpt/name.ckpt"

Note: Checkpoint can be either path or URL.

Note: Currently loading ckpt doesn't resume logger experiment, but it will be supported in future Lightning release.

Evaluate checkpoint on test dataset
python eval.py ckpt_path="/path/to/ckpt/name.ckpt"

Note: Checkpoint can be either path or URL.

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 train.py -m datamodule.batch_size=32,64,128 model.learning_rate=0.001,0.0005

Note: Hydra composes configs lazily at job launch time. If you change code or configs after launching a job/sweep, the final composed configs might be impacted.

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/conll2003_optuna.yaml`
# over chosen experiment config
python train.py -m hparams_search=conll2003_optuna experiment=conll2003

⚠️Warning: Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).

Execute all experiments from folder
python train.py -m 'experiment=glob(*)'

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

Execute sweep on a remote AWS cluster

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

Use Hydra tab completion

Note: Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing tab key. Read the docs.

Apply pre-commit hooks
pre-commit run -a

Note: Apply pre-commit hooks to do things like auto-formatting code and configs, performing code analysis or removing output from jupyter notebooks. See # Best Practices for more.

Run tests
# run all tests
pytest

# run tests from specific file
pytest tests/test_train.py

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

Each experiment should be tagged in order to easily filter them across files or in logger UI:

python train.py tags=["conll2003","experiment_X"]

If no tags are provided, you will be asked to input them from command line:

>>> python train.py tags=[]
[2022-07-11 15:40:09,358][src.utils.utils][INFO] - Enforcing tags! <cfg.extras.enforce_tags=True>
[2022-07-11 15:40:09,359][src.utils.rich_utils][WARNING] - No tags provided in config. Prompting user to input tags...
Enter a list of comma separated tags (dev):

If no tags are provided for multirun, an error will be raised:

>>> python train.py -m +x=1,2,3 tags=[]
ValueError: Specify tags before launching a multirun!

Note: Appending lists from command line is currently not supported in hydra :(


❀️  Contributions

Before making an issue, please verify that:

  • The problem still exists on the current main branch.
  • Your python dependencies are updated to recent versions.

Suggestions for improvements are always welcome!


How To Get Started


How It Works

All PyTorch-IE modules are dynamically instantiated from module paths specified in config. Example model config:

_target_: pytorch_ie.models.transformer_token_classification.TransformerTokenClassificationModel

model_name_or_path: bert-base-uncased
learning_rate: 0.005

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 appropriate config file.

Switch between models and datasets with command line arguments:

python train.py model=transformer_token_classification

The whole pipeline managing the instantiation logic is placed in src/train.py.


Main Configuration

Location: configs/train.yaml
Main project config contains default training configuration.
It determines how config is composed when simply executing command python train.py.

Show main project config
# @package _global_

# specify here default configuration
# order of defaults determines the order in which configs override each other
defaults:
  - _self_
  - dataset: conll2003.yaml
  - datamodule: default.yaml
  - taskmodule: transformer_token_classification.yaml
  - model: transformer_token_classification.yaml
  - callbacks: default.yaml
  - logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
  - trainer: default.yaml
  - paths: default.yaml
  - extras: default.yaml
  - hydra: default.yaml

  # experiment configs allow for version control of specific hyperparameters
  # e.g. best hyperparameters for given model and taskmodule
  - experiment: null

  # config for hyperparameter optimization
  - hparams_search: null

  # optional local config for machine/user specific settings
  # it's optional since it doesn't need to exist and is excluded from version control
  - optional local: default.yaml

  # debugging config (enable through command line, e.g. `python train.py debug=default)
  - debug: null

# task name, determines output directory path
pipeline_type: "training"

# default name for the experiment, determines output directory path
# (you can overwrite this in experiment configs)
name: "default"

# tags to help you identify your experiments
# you can overwrite this in experiment configs
# overwrite from command line with `python train.py tags="[first_tag, second_tag]"`
# appending lists from command line is currently not supported :(
# https://github.com/facebookresearch/hydra/issues/1547
tags: ["dev"]

# 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: False

# seed for random number generators in pytorch, numpy and python.random
seed: null

# simply provide checkpoint path to resume training
ckpt_path: null

# push the model and taskmodule to the huggingface model hub when training has finished
push_to_hub: False

# where to save the trained model and taskmodule
save_dir: models/${name}/${now:%Y-%m-%d_%H-%M-%S}

Experiment Configuration

Location: configs/experiment
Experiment configs allow you to overwrite parameters from main project configuration.
For example, you can use them to version control best hyperparameters for each combination of model and dataset.

Show example experiment config
# @package _global_

# to execute this experiment run:
# python train.py experiment=conll2003

defaults:
  - override /dataset: conll2003.yaml
  - override /datamodule: default.yaml
  - override /taskmodule: transformer_token_classification.yaml
  - override /model: transformer_token_classification.yaml
  - override /callbacks: default.yaml
  - override /logger: aim.yaml
  - override /trainer: default.yaml

# 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
name: "conll2003/transformer_token_classification"

tags: ["dataset=conll2003", "model=transformer_token_classification"]

seed: 12345

trainer:
  min_epochs: 5
  max_epochs: 20
  # gradient_clip_val: 0.5

datamodule:
  batch_size: 32

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.

Show example local Slurm cluster config
# @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

Before creating your own setup, have a look into the Pytorch-IE documentation to make yourself familiar with the Pytorch-IE core concepts like the document, model, and taskmodule.

  1. Write your PyTorch-IE dataset loader (see dataset_builders/pie/conll2003/conll2003.py for an example) or try out one of the PIE datasets hosted at huggingface.co/pie.
  2. Write your PyTorch-IE model (see src/models/transformer_token_classification.py for an example) or use one of the implementations from pytorch-ie or pie-modules.
  3. Write your PyTorch-IE taskmodule (see src/taskmodules/transformer_token_classification.py for example) or use one of the implementations from pytorch-ie or pie-modules.
  4. Write your experiment config, containing paths to your model, taskmodule and dataset (see configs/experiment/conll2003.yaml for example). You may need to also write configs for your model, taskmodule and dataset, if you do not want to use the default ones.
  5. If necessary, define additional_model_kwargs for your model class in the train.py (see line with # NOTE: MODIFY THE additional_model_kwargs IF YOUR MODEL REQUIRES ...").
  6. Execute a dev run for your setup to ensure that everything works as expected (assuming that configs/experiments/experiment_name.yaml is your experiment config file): python src/train.py experiment=experiment_name +trainer.fast_dev_run=true
  7. Run training with chosen experiment config on the GPU: python src/train.py experiment=experiment_name trainer=gpu

Logs

Hydra creates new working directory for every executed run. By default, logs have the following structure:

β”œβ”€β”€ logs
β”‚   β”œβ”€β”€ pipeline_type                     # Folder for the logs generated by type of pipeline, i.e. training, evaluation, or prediction
β”‚   β”‚   β”œβ”€β”€ runs                          # Folder for single runs
β”‚   β”‚   β”‚   β”œβ”€β”€ experiment_name             # Experiment name
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS       # Datetime of the run
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ .hydra                  # Hydra logs
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ csv                     # Csv logs
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ wandb                   # Weights&Biases logs
β”‚   β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ checkpoints             # Training checkpoints
β”‚   β”‚   β”‚   β”‚   β”‚   └── ...                     # Any other thing saved during training
β”‚   β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   β”‚
β”‚   β”‚   └── multiruns                     # Folder for multiruns
β”‚   β”‚       β”œβ”€β”€ experiment_name             # Experiment name
β”‚   β”‚       β”‚   β”œβ”€β”€ YYYY-MM-DD_HH-MM-SS       # Datetime of the multirun
β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€1                        # Multirun job number
β”‚   β”‚       β”‚   β”‚   β”œβ”€β”€2
β”‚   β”‚       β”‚   β”‚   └── ...
β”‚   β”‚       β”‚   └── ...
β”‚   β”‚       └── ...
β”‚   β”‚
β”‚   └── debugs                            # Logs generated when debugging config is attached
β”‚       └── ...

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


Experiment Tracking

PyTorch-IE is based on PyTorch Lightning which supports many popular logging frameworks:
**Weights&Biases Β· Neptune Β· Comet Β· MLFlow Β· Tensorboard Β· Aim **

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 train.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 TransformerTokenClassification example.


Tests

Template comes with generic tests implemented with pytest.

# run all tests
pytest

# run tests from specific file
pytest tests/test_train.py

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

Most of the implemented tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can execute them once in a while to speed up the development.

Currently, the tests cover cases like:

  • running 1 train, val and test step
  • running 1 epoch on 1% of data, saving ckpt and resuming for the second epoch
  • running 2 epochs on 1% of data, with DDP simulated on CPU

And many others. You should be able to modify them easily for your use case.

There is also @RunIf decorator implemented, that allows you to run tests only if certain conditions are met, e.g. GPU is available or system is not windows. See the examples.


Hyperparameter Search

You can define hyperparameter search by adding new config file to configs/hparams_search.

Show example hyperparameter search config
# @package _global_

# example hyperparameter optimization of some experiment with Optuna:
# python train.py -m hparams_search=conll2003_optuna experiment=conll2003

defaults:
  - override /hydra/sweeper: optuna

# choose metric which will be optimized by Optuna
# make sure this is the correct name of some metric logged in lightning module!
optimized_metric: "val/f1"

# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
# docs: https://hydra.cc/docs/next/plugins/optuna_sweeper
hydra:
  mode: "MULTIRUN" # set hydra to multirun by default if this config is attached

  sweeper:
    _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper

    # storage URL to persist optimization results
    # for example, you can use SQLite if you set 'sqlite:///example.db'
    storage: null

    # name of the study to persist optimization results
    study_name: null

    # number of parallel workers
    n_jobs: 1

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

    # total number of runs that will be executed
    n_trials: 20

    # choose Optuna hyperparameter sampler
    # you can choose bayesian sampler (tpe), random search (without optimization), grid sampler, and others
    # docs: https://optuna.readthedocs.io/en/stable/reference/samplers.html
    sampler:
      _target_: optuna.samplers.TPESampler
      seed: 1234
      n_startup_trials: 10 # number of random sampling runs before optimization starts

    # define range of hyperparameters
    # More information here : https://hydra.cc/docs/plugins/optuna_sweeper/#search-space-configuration
    params:
      datamodule.batch_size: choice(32,64,128)
      model.learning_rate: interval(0.0001, 0.2)

# This is a dummy value necessary to allow overwriting it in the sweep.
model:
  learning_rate: 0.00001

Next, you can execute it with: python train.py -m hparams_search=conll2003_optuna

Using this approach doesn't require adding any boilerplate to code, everything is defined in a single config file. The only necessary thing is to return the optimized metric value from the launch file.

You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.

The optimization_results.yaml will be available under logs/pipeline_type/multirun folder.

This approach doesn't support advanced techniques like prunning - for more sophisticated search, you should probably write a dedicated optimization task (without multirun feature).


Continuous Integration

Template comes with CI workflows implemented in Github Actions:

  • .github/workflows/tests.yaml: running tests that are not marked as "slow"
  • .github/workflows/pre-commit.yaml: running code quality checks, see .pre-commit-config.yaml for configured entries

Note: You need to enable the GitHub Actions from the settings in your repository.


Distributed 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 the lightning docs.

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

python train.py trainer=ddp

Note: When using DDP you have to be careful how you write your models - read the docs.


Accessing Datamodule Attributes In Model

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)

Note: Not a very robust solution, since it assumes all your datamodules have some_param attribute available.

Similarly, you can pass a whole datamodule config as an init parameter:

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

You can also pass a datamodule config parameter to your model through variable interpolation:

# ./configs/model/my_model.yaml
_target_: src.models.my_module.MyLitModule
lr: 0.01
some_param: ${datamodule.some_param}

Another approach is to access datamodule in LightningModule directly through Trainer:

# ./src/models/mnist_module.py
def on_train_start(self):
  self.some_param = self.trainer.datamodule.some_param

Note: This only works after the training starts since otherwise trainer won't be yet available in LightningModule.


Inference

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

Show example
from dataclasses import dataclass

from pytorch_ie.annotations import LabeledSpan
from pytorch_ie.auto import AutoPipeline
from pytorch_ie.core import AnnotationList, annotation_field
from pytorch_ie.documents import TextDocument

@dataclass
class ExampleDocument(TextDocument):
    entities: AnnotationList[LabeledSpan] = annotation_field(target="text")


def predict():
   """
   Example of inference with trained model.
   It loads pretrained NER model. Then it
   creates an example document (PyTorch-IE Document) and predicts
   entities from the text in the document.
   """
   document = ExampleDocument(
       "β€œMaking a super tasty alt-chicken wing is only half of it,” said Po Bronson, general partner at SOSV and managing director of IndieBio."
   )

   # model path can be set to a location at huggingface as shown below or local path to the training result serialized to out_path
   ner_pipeline = AutoPipeline.from_pretrained("pie/example-ner-spanclf-conll03", device=-1, num_workers=0)

   ner_pipeline(document)

   for entity in document.entities.predictions:
       print(f"{entity} -> {entity.label}")

if __name__ == "__main__":
    predict()

# Result:
# IndieBio -> ORG
# Po Bronson -> PER
# SOSV -> ORG

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

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 access 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)
  • pyupgrade (upgrading python syntax to newer version)
  • docformatter (python docstring formatting)
  • flake8 (python pep8 code analysis)
  • prettier (yaml formatting)
  • nbstripout (clearing output from jupyter notebooks)
  • bandit (python security linter)
  • mdformat (markdown formatting)
  • codespell (word spellling linter)

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 train.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 complete the setup.py file.

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_module import MNISTLitModule
from project_name.datamodules.mnist_datamodule import MNISTDataModule
Keep local configs out of code versioning

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.

Example SLURM cluster config:

# @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

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

πŸš€ Quickstart

Environment Setup

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

# [OPTIONAL] create conda environment
conda create -n your-project-name python=3.9
conda activate your-project-name

# install PyTorch according to instructions
# https://pytorch.org/get-started/

# install remaining requirements
pip install -r requirements.txt

# [OPTIONAL] symlink log directories and the default model directory to
# "$HOME/experiments/your-project-name" since they can grow a lot
bash setup_symlinks.sh $HOME/experiments/your-project-name

# [OPTIONAL] set any environment variables by creating an .env file
# 1. copy the provided example file:
cp .env.example .env
# 2. edit the .env file for your needs!

Model Training

Have a look into the train.yaml config to see all available options.

Train model with default configuration

# train on CPU
python src/train.py

# train on GPU
python src/train.py trainer=gpu

Execute a fast development run (train for two steps)

python src/train.py +trainer.fast_dev_run=true

Train model with chosen experiment configuration from configs/experiment/

python src/train.py experiment=conll2003

You can override any parameter from command line like this

python train.py trainer.max_epochs=20 datamodule.batch_size=64

Start multiple runs at once (multirun):

python src/train.py seed=42,43 --multirun

Notes:

  • this will execute two experiments (one after the other), one for each seed
  • the results will be aggregated and stored in logs/multirun/, see the last logging output for the exact path

Model evaluation

This will evaluate the model on the test set of the chosen dataset using the metrics implemented within the model. See config/dataset/ for available datasets.

Have a look into the evaluate.yaml config to see all available options.

python src/evaluate.py dataset=conll2003 model_name_or_path=pie/example-ner-spanclf-conll03

Notes:

  • add the command line parameter trainer=gpu to run on GPU

Inference

This will run inference on the given dataset and split. See config/dataset/ for available datasets. The result documents including the predicted annotations will be stored in the predictions/ directory (exact location will be printed to the console).

Have a look into the predict.yaml config to see all available options.

python src/predict.py dataset=conll2003 model_name_or_path=pie/example-ner-spanclf-conll03

Notes:

  • add the command line parameter +pipeline.device=0 to run the inference on GPU 0

Evaluate Serialized Documents

This will evaluate serialized documents including predicted annotations (see Inference) using a document metric. See config/metric/ for available metrics.

Have a look into the evaluate_documents.yaml config to see all available options

python src/evaluate_documents.py metric=f1 metric.layer=entities +dataset.data_dir=PATH/TO/DIR/WITH/SPLITS

Note: By default, this utilizes the dataset provided by the from_serialized_documents configuration. This configuration is designed to facilitate the loading of serialized documents, as generated during the Inference step. It requires to set the parameter data_dir. If you want to use a different dataset, you can override the dataset parameter as usual with any existing dataset config, e.g dataset=conll2003. But calculating the F1 score on the bare conll2003 dataset does not make much sense, because it does not contain any predictions. However, it could be used with statistical metrics such as count_text_tokens or count_entity_labels.

Development

# run pre-commit: code formatting, code analysis, static type checking, and more (see .pre-commit-config.yaml)
pre-commit run -a

# run tests
pytest -k "not slow" --cov --cov-report term-missing