A clean template to kickstart your deep learning project 🚀⚡🔥
Click on Use this template to initialize new repository.
Suggestions are always welcome!
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.
✅ 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.
❌ 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.
- Rapid Experimentation: thanks to hydra command line superpowers
- Minimal Boilerplate: thanks to automating pipelines with config instantiation
- Main Configs: allow you to specify default training configuration
- Experiment Configs: allow you to override chosen hyperparameters and version control experiments
- Workflow: comes down to 4 simple steps
- Experiment Tracking: Tensorboard, W&B, and CSVLogger
- Logs: all logs (checkpoints, configs, etc.) are stored in a dynamically generated folder structure
- Hyperparameter Search: simple search is effortless with Hydra plugins like Optuna Sweeper
- Tests: generic, easy-to-adapt smoke tests for speeding up the development
- Continuous Integration: automatically test and lint your repo with Github Actions
- Best Practices: a couple of recommended tools, practices and standards
The directory structure of new project looks like this:
├── .github <- Github Actions workflows
│
├── data <- Project data
│
├── logs <- Logs generated by hydra and 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`.
│
├── scripts <- Shell scripts
│
├── src <- Source code
│ └── lightning_hydra_template <- Package directory
│ │
│ ├── configs <- Hydra configs
│ │ ├── callbacks <- Callbacks configs
│ │ ├── data <- Data configs
│ │ ├── debug <- Debugging configs
│ │ ├── experiment <- Experiment configs
│ │ ├── extras <- Extra utilities configs
│ │ ├── hparams_search <- Hyperparameter search configs
│ │ ├── hydra <- Hydra configs
│ │ ├── local <- Local configs
│ │ ├── logger <- Logger configs
│ │ ├── model <- Model configs
│ │ ├── paths <- Project paths configs
│ │ ├── trainer <- Trainer configs
│ │ │
│ │ ├── eval.yaml <- Main config for evaluation
│ │ └── train.yaml <- Main config for training
│ │
│ ├── data <- Data scripts
│ ├── models <- Model scripts
│ ├── utils <- Utility scripts
│ │
│ ├── eval.py <- Run evaluation
│ └── train.py <- Run training
│
├── tests <- Tests of any kind
│
├── .env.example <- Example of file for storing private environment variables
├── .gitignore <- List of files ignored by git
├── .pre-commit-config.yaml <- Configuration of pre-commit hooks for code formatting
├── pyproject.toml <- Project management and tools configuration (also used to infer project root directory)
├── README.md
└── uv.lock <- Lock file specifying the exact versions of dependencies in uv environment
# clone the project
git clone https://github.com/nathanpainchaud/lightning-hydra-template
cd lightning-hydra-template
# use uv to create a virtual environment and install the project and its dependencies
# you must specify as extra the desired compute platform for PyTorch (i.e. CPU/CUDA)
# Supported values are: cpu, cu124, cu121, cu118
# [OPTIONAL] you can also specify other extras for more functionalities
# Supported values are: wandb (for W&B integration)
uv sync --extra cpu --extra wandb
Template contains example with MNIST classification.
When running python src/lightning_hydra_template/train.py
you should see something like this:
Override any config parameter from command line
python src/lightning_hydra_template/train.py trainer.max_epochs=20 model.optimizer.lr=1e-4
# [OPTIONAL] call the script using the defined entrypoint
template-train trainer.max_epochs=20 model.optimizer.lr=1e-4
[!NOTE] You can also add new parameters with
+
sign.
python src/lightning_hydra_template/train.py +model.new_param="owo"
Train on CPU, GPU, and TPU
# train on CPU
python src/lightning_hydra_template/train.py trainer=cpu
# train on 1 GPU
python src/lightning_hydra_template/train.py trainer=gpu
# train on TPU
python src/lightning_hydra_template/train.py +trainer.tpu_cores=8
Train with mixed precision
# train with pytorch native automatic mixed precision (AMP)
python src/lightning_hydra_template/train.py trainer=gpu +trainer.precision=16
Train model with any logger available in PyTorch Lightning, like W&B or Tensorboard
# 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 src/lightning_hydra_template/train.py logger=wandb
[!NOTE] Lightning provides convenient integrations with most popular logging frameworks. Learn more here.
[!IMPORTANT] Using wandb requires you to setup account first. After that just complete the config as below.
[!TIP] Click here to see example wandb dashboard generated with this template.
Train model with chosen experiment config
python src/lightning_hydra_template/train.py experiment=example
[!TIP] Experiment configs are placed in configs/experiment/.
Attach some callbacks to run
python src/lightning_hydra_template/train.py callbacks=default
[!NOTE] Callbacks can be used for things such as model checkpointing, early stopping and many more.
[!TIP] Callbacks configs are placed in configs/callbacks/.
Use different tricks available in Pytorch Lightning
# gradient clipping may be enabled to avoid exploding gradients
python src/lightning_hydra_template/train.py +trainer.gradient_clip_val=0.5
# run validation loop 4 times during a training epoch
python src/lightning_hydra_template/train.py +trainer.val_check_interval=0.25
# accumulate gradients
python src/lightning_hydra_template/train.py +trainer.accumulate_grad_batches=10
# terminate training after 12 hours
python src/lightning_hydra_template/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 src/lightning_hydra_template/train.py debug=default
# run 1 train, val and test loop, using only 1 batch
python src/lightning_hydra_template/train.py debug=fdr
# print execution time profiling
python src/lightning_hydra_template/train.py debug=profiler
# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
python src/lightning_hydra_template/train.py +trainer.detect_anomaly=true
# use only 20% of the data
python src/lightning_hydra_template/train.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
[!TIP] Visit configs/debug/ for different debugging configs.
Resume training from checkpoint
python src/lightning_hydra_template/train.py ckpt_path="/path/to/ckpt/name.ckpt"
[!NOTE] Checkpoint can be either path or URL.
[!WARNING] Currently loading ckpt doesn't resume logger experiment, but it will be supported in future Lightning release.
Evaluate checkpoint on test dataset
python src/lightning_hydra_template/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 src/lightning_hydra_template/train.py -m data.batch_size=32,64,128 model.lr=0.001,0.0005
[!WARNING] 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
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python src/lightning_hydra_template/train.py -m hparams_search=mnist_optuna experiment=example
[!NOTE] Using Optuna Sweeper doesn't require you to add any boilerplate to your code, everything is defined in a single config file.
[!WARNING] Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).
Execute all experiments from folder
python src/lightning_hydra_template/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 run for multiple different seeds
python src/lightning_hydra_template/train.py -m seed=1,2,3,4,5 trainer.deterministic=True logger=csv tags=["benchmark"]
[!WARNING]
trainer.deterministic=True
makes pytorch more deterministic but impacts the performance.
Execute sweep on a SLURM cluster
This should be achievable with either the right lightning trainer flags or simple config using Submitit launcher for Hydra. Example is not yet 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.
Update pre-commit hook versions in .pre-commit-config.yaml
with:
pre-commit autoupdate
Run tests
# run all tests
pytest
# run a test package
pytest tests/integration
# run tests from a specific file
pytest tests/integration/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 src/lightning_hydra_template/train.py tags=["mnist","experiment_X"]
[!NOTE] You might need to escape the bracket characters in your shell with
python src/lightning_hydra_template/train.py tags=\["mnist","experiment_X"\]
.
If no tags are provided, you will be asked to input them from command line:
>>> python src/lightning_hydra_template/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 src/lightning_hydra_template/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 :(
All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:
_target_: lightning_hydra_template.models.mnist_module.MNISTLitModule
lr: 0.001
net:
_target_: lightning_hydra_template.models.components.simple_dense_net.SimpleDenseNet
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
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 datamodules with command line arguments:
python src/lightning_hydra_template/train.py model=mnist
Example pipeline managing the instantiation logic: src/lightning_hydra_template/train.py.
Location: configs/train.yaml
Main project config contains default training configuration.
It determines how config is composed when simply executing command python src/lightning_hydra_template/train.py
.
Show main project config
# order of defaults determines the order in which configs override each other
defaults:
- data: mnist.yaml
- model: mnist.yaml
- callbacks: default.yaml
- logger: null # set logger here or use command line (e.g. `python src/lightning_hydra_template/train.py logger=csv`)
- 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 datamodule
- 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 src/lightning_hydra_template/train.py debug=default)
- debug: null
- _self_
# task name, determines output directory path
task_name: "train"
# tags to help you identify your experiments
# you can overwrite this in experiment configs
# overwrite from command line with `python src/lightning_hydra_template/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: True
# simply provide checkpoint path to resume training
ckpt_path: null
# seed for random number generators in pytorch, numpy and python.random
seed: null
Location: configs/experiment
Experiment configs allow you to overwrite parameters from main config.
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 src/lightning_hydra_template/train.py experiment=example
defaults:
- override /data: mnist.yaml
- override /model: mnist.yaml
- override /callbacks: default.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
tags: ["mnist", "simple_dense_net"]
seed: 12345
trainer:
min_epochs: 10
max_epochs: 10
gradient_clip_val: 0.5
model:
optimizer:
lr: 0.002
net:
lin1_size: 128
lin2_size: 256
lin3_size: 64
data:
batch_size: 64
logger:
wandb:
tags: ${tags}
group: "mnist"
- Write your PyTorch Lightning module (see models/mnist_module.py for example)
- Write your PyTorch Lightning datamodule (see data/mnist_datamodule.py for example)
- Write your experiment config, containing paths to model and datamodule
- Run training with chosen experiment config:
python src/lightning_hydra_template/train.py experiment=experiment_name.yaml
Say you want to execute many runs to plot how accuracy changes in respect to batch size.
-
Execute the runs with some config parameter that allows you to identify them easily, like tags:
python src/lightning_hydra_template/train.py -m logger=csv data.batch_size=16,32,64,128 tags=["batch_size_exp"]
-
Write a script or notebook that searches over the
logs/
folder and retrieves csv logs from runs containing given tags in config. Plot the results.
Hydra creates new output directory for every executed run.
Default logging structure:
├── logs
│ ├── task_name
│ │ ├── runs # Logs generated by single runs
│ │ │ ├── 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 # Logs generated by multiruns
│ │ ├── 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.
PyTorch Lightning supports many 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 src/lightning_hydra_template/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 or take a look at MNIST example.
Template comes with generic tests implemented with pytest
.
# run all tests
pytest
# run a test package
pytest tests/integration
# run tests from a specific file
pytest tests/integration/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.
You can define hyperparameter search by adding new config file to configs/hparams_search.
Show example hyperparameter search config
# @package _global_
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/acc_best"
# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
hydra:
sweeper:
_target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
# 'minimize' or 'maximize' the objective
direction: maximize
# total number of runs that will be executed
n_trials: 20
# choose Optuna hyperparameter sampler
# 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 hyperparameter search space
params:
model.optimizer.lr: interval(0.0001, 0.1)
data.batch_size: choice(32, 64, 128, 256)
model.net.lin1_size: choice(64, 128, 256)
model.net.lin2_size: choice(64, 128, 256)
model.net.lin3_size: choice(32, 64, 128, 256)
Next, execute it with: python src/lightning_hydra_template/train.py -m hparams_search=mnist_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/task_name/multirun
folder.
This approach doesn't support resuming interrupted search and advanced techniques like pruning - for more sophisticated search and workflows, you should probably write a dedicated optimization task (without multirun feature).
Template comes with CI workflows implemented in Github Actions:
.github/workflows/code-quality-main.yaml
: running pre-commits on main branch for all files.github/workflows/code-quality-pr.yaml
: running pre-commits on pull requests for modified files only.github/workflows/run-pytest.yaml
: running all tests with pytest and uploading coverage report to Codecov
The simplest way is to pass datamodule attribute directly to model on initialization:
# ./src/lightning_hydra_template/train.py
datamodule = hydra.utils.instantiate(config.data)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
Important
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/lightning_hydra_template/train.py
model = hydra.utils.instantiate(config.model, dm_conf=config.data, _recursive_=False)
You can also pass a datamodule config parameter to your model through variable interpolation:
# ./configs/model/my_model.yaml
_target_: lightning_hydra_template.models.my_module.MyLitModule
lr: 0.01
some_param: ${data.some_param}
Another approach is to access datamodule in LightningModule directly through Trainer:
# ./src/lightning_hydra_template/models/mnist_module.py
def on_train_start(self):
self.some_param = self.trainer.datamodule.some_param
Warning
This only works after the training starts since otherwise trainer won't be yet available in LightningModule.
Use uv
uv
is a Python package and project manager.
It allows you to manage Python interpreters, dependencies, and project configuration in a single tool.
Compared to conda
, it's much faster and easier to use.
However, its philosophy is to create isolated environments for each project, rather than global
environments to be reused across projects.
Example installation:
curl -LsSf https://astral.sh/uv/install.sh | sh
Update uv
:
uv self update
Manually create or update virtual environment to match pyproject.toml
. Note that because of the dependencies are
configured in this template, you must specify as an extra the desired compute platform for PyTorch (i.e. CPU/CUDA):
# e.g. to create/update the virtual environment using the PyTorch version built for CPU
uv sync --extra cpu
# [OPTIONAL] you can also specify other extras for more functionalities
# e.g. to install the `wandb` extra for W&B integration
uv sync --extra cpu --extra wandb
To run a python script using the environment installed by uv
, you have two options:
# 1. Use `uv run` to run the script within the uv environment
uv run src/lightning_hydra_template/train.py ...
# or to run the defined entrypoint
uv run template-train ...
# 2. Manually activate the uv environment and then run the script or entrypoint (like in any other virtual environment)
source .venv/bin/activate
python src/lightning_hydra_template/train.py ...
For simplicity, commands in this README assume that you have activated the virtual environment by running
source .venv/bin/activate
, or that you prefix them with uv run
.
Use automatic code formatting
Use pre-commit hooks to standardize code formatting of your project and save mental energy.
Assuming you have the pre-commit package installed (either globally or in the virtual environment if you use the default
uv
environment), you can install hooks from .pre-commit-config.yaml:
pre-commit install
After that your code will be automatically reformatted on every new commit.
To reformat all files in the project use command:
pre-commit run -a
To update hook versions in .pre-commit-config.yaml use:
pre-commit autoupdate
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.
-
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):
-
Preserve the recommended method order.
class LitModel(LightningModule): def __init__(): ... def forward(): ... def training_step(): ... def training_step_end(): ... def on_train_epoch_end(): ... def validation_step(): ... def validation_step_end(): ... def on_validation_epoch_end(): ... def test_step(): ... def test_step_end(): ... def on_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 lightning_hydra_template folder to your project name.
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.data.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.
For example, you can use it for a 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
This template was inspired by:
- PyTorchLightning/deep-learning-project-template
- drivendata/cookiecutter-data-science
- lucmos/nn-template
- ashleve/lightning-hydra-template
DELETE EVERYTHING ABOVE FOR YOUR PROJECT
What it does
Important
Using this project requires a basic understanding of PyTorch Lightning and Hydra. If you do not know at least what these libraries do and how they work at a high level, you should familiarize yourself with them. We refer you to the PyTorch Lightning documentation and the Hydra documentation.
Note
uv is a Python package and project manager. It allows you to manage Python interpreters, dependencies, and project configuration in a single tool. If you don't have it installed already, you can install it (on Linux and macOS) by running:
curl -LsSf https://astral.sh/uv/install.sh | sh
- Download the repository.
git clone https://github.com/YourGithubName/your-repo-name cd your-repo-name
- Create a virtual environment and install the project and its dependencies. You must specify as an extra the desired
compute platform for PyTorch (i.e. CPU/CUDA). Supported values are:
cpu
,cu124
,cu121
,cu118
.[OPTIONAL] You can also specify other extras for additional functionalities:# e.g. to install the project with the PyTorch version built for CPU uv sync --extra cpu # e.g. to install the project with the PyTorch version built for CUDA 12.4 uv sync --extra cu124
# e.g. to install the `wandb` extra for W&B integration uv sync --extra cpu --extra wandb
- Activate the virtual environment created by
uv
.source .venv/bin/activate
- Download the repository.
git clone https://github.com/YourGithubName/your-repo-name cd your-repo-name
- Create a virtual environment and activate it.
python -m venv .venv source .venv/bin/activate
- Install PyTorch libraries (i.e.
torch
andtorchvision
) according to the official instructions. Follow the instructions forpip
and the compute platform compatible with your system.# e.g. to install the PyTorch version built for CPU pip install torch torchvision --index-url https://download.pytorch.org/whl/cpu # e.g. to install the PyTorch version built for CUDA 12.1 pip install torch torchvision --index-url https://download.pytorch.org/whl/cu121
- Install the project in editable mode.
[OPTIONAL] You can also specify other extras for additional functionalities:
pip install -e .
# e.g. to install the `wandb` extra for W&B integration pip install -e .[wandb]
Train model with default configuration
# train on CPU
python src/your_repo_name/train.py trainer=cpu
# train on GPU
python src/your_repo_name/train.py trainer=gpu
Train model with chosen experiment configuration from configs/experiment/
python src/your_repo_name/train.py experiment=experiment_name.yaml
You can override any parameter from command line like this
python src/your_repo_name/train.py trainer.max_epochs=20 data.batch_size=64