PyTorch Lightning + Hydra. A very user-friendly template for ML experimentation. ⚡⚡
PyTorch Lightning + Hydra. A very user-friendly template for ML experimentation. ⚡⚡
Why you might want to use it:
✅ Save on boilerplate
Easily add new models, datasets, tasks, experiments, and train on different accelerators, like multi-GPU, TPU or SLURM clusters.
✅ Education
Thoroughly commented. You can use this repo as a learning resource.
✅ Reusability
Collection of useful MLOps tools, configs, and code snippets. You can use this repo as a reference for various utilities.
Why you might not want to use it:
❌ Things break from time to time
Lightning and Hydra are still evolving and integrate many libraries, which means sometimes things break. For the list of currently known problems visit this page.
❌ Not adjusted for data engineering
Template is not really adjusted for building data pipelines that depend on each other. It's more efficient to use it for model prototyping on ready-to-use data.
❌ Overfitted to simple use case
The configuration setup is built with simple lightning training in mind. You might need to put some effort to adjust it for different use cases, e.g. lightning fabric.
❌ Might not support your workflow
For example, you can't resume hydra-based multirun or hyperparameter search.
Note: Keep in mind this is unofficial community project.
PyTorch Lightning - a lightweight PyTorch wrapper for high-performance AI research. Think of it as a framework for organizing your PyTorch code.
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.
The directory structure of new project looks like this:
…# 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.9
conda activate myenv
# install pytorch according to instructions
# https://pytorch.org/get-started/
# install requirements
pip install -r requirements.txtTemplate contains example with MNIST classification.
When running python src/train.py you should see something like this:
python train.py trainer.max_epochs=20 model.optimizer.lr=1e-4Note: You can also add new parameters with
+sign.
python train.py +model.new_param="owo"# 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=mpsTrain with mixed precisionWarning: Currently there are problems with DDP mode, read this issue to learn more.
# train with pytorch native automatic mixed precision (AMP)
python train.py trainer=gpu +trainer.precision=16# 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=wandbNote: 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.
Train model with chosen experiment configNote: Click here to see example wandb dashboard generated with this template.
python train.py experiment=exampleAttach some callbacks to runNote: Experiment configs are placed in configs/experiment/.
python train.py callbacks=defaultNote: Callbacks can be used for things such as as model checkpointing, early stopping and many more.
Use different tricks available in Pytorch LightningNote: Callbacks configs are placed in configs/callbacks/.
# 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"Easily debugNote: PyTorch Lightning provides about 40+ useful trainer flags.
…Resume training from checkpointNote: Visit configs/debug/ for different debugging configs.
python train.py ckpt_path="/path/to/ckpt/name.ckpt"Note: Checkpoint can be either path or URL.
Evaluate checkpoint on test datasetNote: Currently loading ckpt doesn't resume logger experiment, but it will be supported in future Lightning release.
python eval.py ckpt_path="/path/to/ckpt/name.ckpt"Create a sweep over hyperparametersNote: Checkpoint can be either path or URL.
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python train.py -m data.batch_size=32,64,128 model.lr=0.001,0.0005Create a sweep over hyperparameters with OptunaNote: 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.
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python train.py -m hparams_search=mnist_optuna experiment=exampleNote: Using Optuna Sweeper doesn't require you to add any boilerplate to your code, everything is defined in a single config file.
Execute all experiments from folderWarning: Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).
python train.py -m 'experiment=glob(*)'Execute run for multiple different seedsNote: Hydra provides special syntax for controlling behavior of multiruns. Learn more here. The command above executes all experiments from configs/experiment/.
python train.py -m seed=1,2,3,4,5 trainer.deterministic=True logger=csv tags=["benchmark"]Execute sweep on a remote AWS clusterNote:
trainer.deterministic=Truemakes pytorch more deterministic but impacts the performance.
Use Hydra tab completionNote: This should be achievable with simple config using Ray AWS launcher for Hydra. Example is not implemented in this template.
Apply pre-commit hooksNote: Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing
tabkey. Read the docs.
pre-commit run -aNote: 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.
Update pre-commit hook versions in .pre-commit-config.yaml with:
pre-commit autoupdate# 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"Each experiment should be tagged in order to easily filter them across files or in logger UI:
python train.py tags=["mnist","experiment_X"]Note: You might need to escape the bracket characters in your shell with
python train.py tags=\["mnist","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 :(
This project exists thanks to all the people who contribute.
Have a question? Found a bug? Missing a specific feature? Feel free to file a new issue, discussion or PR with respective title and description.
Before making an issue, please verify that:
main branch.S
No open issues yet, or sync has not completed.