Notes on refactoring, strategy, intuition
(Added by Jacob A Rose Monday July 26th, 2021)
Configuration & modularity Necessary data functionality should be clearly separated into:
- Pre-experiment preprocessing
A. Extraction
B. Splitting - During-experiment
A. Extraction
B. Splitting
C. Sample Loading
D. Processing
E. Sample Augmentation (train only)
F. Batch Loading
G. Batch Augmentation (train only)
(1A. vs. 2A.) and (1B. vs. 2B.) share common logic, but differ in how much they trade off experimental flexibility vs. cognitive load
I. Extracting Image paths on disk, organized into root_dir/class_subdir/image_i.jpg
format.
II. Extracting Image paths & labels from pre-compiled csv files.
For a given dataset, it might have 1, 2 or 3 root_dirs.
A. If 1 root_dir, then user must load, then split into train, val, and test subsets
B. If 2 root_dirs, then user must load train & test root_dirs, then split train into train & val subsets.
C. If 3 root_dirs, then user must simply load train, val, and test subsets as is.
At the moment, only A. and B. are really an issue. Thus, at run-time, user must be prepared to handle either a single root_dir for all data subsets, or a pair of train/
and test/
root_dirs. For consistency between experiments, clearly B.
is preferable so we're always referencing the same test set.
II. Extracting labels:
A. If simple single-label classification, then labels can be assigned by taking the image's parent dir name `class_subdir`.
B. If max flexibility is required, multi-labels can be extracted from image's filename. e.g. `"{family}_{genus}_{species}_{collection}_{catalog_number}.jpg"`
* Note: Each dataset might have its own image filename schema. Need to identify robust way of detecting this. Currently, PNAS differs from the rest.
-
Pre-experiment preprocessing
- A. Extraction: Parse on-disk image file trees to generate a main csv catalog of (path, label_0, label_1, ...) rows.
- If both train/ and test/ directories exist, create the above csv by concatenation. Create train.csv and test.csv, respectively.
- If only a single root_dir/ exists, generate main csv as-is. Then create a reproducible train-test split to ensure a constant test set.
dataset_dir/ images/ class_i/ image_0.jpg catalogs/ full_dataset.csv catalog_splits/ train.csv test.csv
- B. Splitting: User provides directory containing input csvs: train.csv and a test.csv. For each experiment, provide an output_dir to which the full train.csv, val.csv, and test.csv files will be saved.
- Output train.csv, val.csv, and test.csv into clearly labeled directory, ideally with a log file documenting their creation.
- During experiment, config file will only reference this output_dir. Thus, each set of splits must be generated prior to configuring or running any experiment. A bit more laborious/manual but my hope is this will ensure due diligence & minimize dataset configuration complexity at runtime.
- A. Extraction: Parse on-disk image file trees to generate a main csv catalog of (path, label_0, label_1, ...) rows.
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 or kaggle competitions. It's also a collection of best practices for efficient workflow and reproducibility.
Why you shouldn't use it: Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task.
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.
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.
- Predefined Structure: clean and scalable so that work can easily be extended and replicated (see #Project Structure)
- Rapid Experimentation: thanks to automating pipeline with config files and hydra command line superpowers
- Little Boilerplate: so pipeline can be easily modified (see src/train.py)
- Main Configuration: main config file specifies default training configuration (see #Main Project Configuration)
- Experiment Configurations: stored in a separate folder, they can be composed out of smaller configs, override chosen parameters or define everything from scratch (see #Experiment Configuration)
- Experiment Tracking: many logging frameworks can be easily integrated! (see #Experiment Tracking)
- Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see #Logs)
- Hyperparameter Search: made easier with Hydra built in plugins like Optuna Sweeper
- Best Practices: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see #Best Practices)
- Extra Features: optional utilities to make your life easier (see #Extra Features)
- Workflow: comes down to 4 simple steps (see #Workflow)
The directory structure of new project looks like this:
├── configs <- Hydra configuration files
│ ├── callbacks <- Callbacks configs
│ ├── datamodule <- Datamodule configs
│ ├── experiment <- Experiment configs
│ ├── hparams_search <- Hyperparameter search configs
│ ├── logger <- Logger 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
│
├── src
│ ├── callbacks <- Lightning callbacks
│ ├── datamodules <- Lightning datamodules
│ ├── models <- Lightning models
│ ├── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
│ │ └── template_utils.py <- Extra features for the template
│ │
│ └── train.py <- Training pipeline
│
├── run.py <- Run any pipeline with chosen experiment configuration
│
├── .env.template <- Template of file for storing private environment variables
├── .autoenv.template <- Template of file for automatic virtual environment setup
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── conda_env_gpu.yaml <- File for installing conda environment
├── requirements.txt <- File for installing python dependencies
├── LICENSE
└── README.md
# clone project
git clone https://github.com/ashleve/lightning-hydra-template
cd lightning-hydra-template
# [OPTIONAL] create conda environment
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
# install requirements
pip install -r requirements.txt
Template contains example with MNIST classification.
When running python run.py
you should see something like this:
(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 optimizer.lr=1e-4
You can also add new parameters with
+
sign.
python run.py +model.new_param="uwu"
Train on CPU, GPU, TPU or even with DDP and mixed precision
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.accelerator='ddp'
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
# train with mixed precision
python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
+trainer.amp_level="O2"
Train model with any logger available in PyTorch Lightning, like Weights&Biases
PyTorch Lightning provides convenient integrations with most popular logging frameworks. 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
Train model with chosen experiment config
Experiment configurations are placed in configs/experiment/.
python run.py experiment=exp_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_callbacks
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
Easily debug
# run 1 train, val and test loop, using only 1 batch
python run.py debug=true
# print full weight summary of all PyTorch modules
python run.py trainer.weights_summary="full"
# print execution time profiling after training ends
python run.py +trainer.profiler="simple"
# raise exception, if any of the parameters or the loss are NaN or +/-inf
python run.py trainer.terminate_on_nan=true
# 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
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 optimizer.lr=0.001,0.0005
⚠️ Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
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=exp_example_simple
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.
Execute sweep on a Linux SLURM cluster
This should be achievable with simple config using Submitit 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 image for the template is available for download here.
# download image
docker pull ashleve/lightning-hydra:latest
# run container from image
docker run --gpus all -it --rm ashleve/lightning-hydra
# you can also build image by yourself using Dockerfile
docker build -t lightning-hydra .
Dockerfiles are provided on branch dockerfiles
. You can use them as a starting point for building your own images.
If you want to use some popular official image instead, I recommend the nvidia ngc pytorch container, or "devel" version of pytorch/pytorch (this one doesn't have installed Apex for mixed-precision training).
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!
- First, you should probably get familiar with PyTorch Lightning
- Next, go through Hydra quick start guide, basic Hydra tutorial and docs about instantiating objects with Hydra
By design, every run is initialized by run.py file. train.py contains training pipeline. You can create different pipelines for different needs (e.g. for k-fold cross validation or for testing only).
All PyTorch Lightning modules are dynamically instantiated from module paths specified in config, e.g. the model can be instantiated 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:
_target_: src.models.mnist_model.MNISTLitModel
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
lr: 0.001
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_trainer.yaml
- model: mnist_model.yaml
- datamodule: mnist_datamodule.yaml
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
- logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)
# 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
# learn more here: 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/
# use `python run.py debug=true` for easy debugging!
# (equivalent to running `python run.py trainer.fast_dev_run=true`)
debug: False
# pretty print config at the start of the run using Rich library
print_config: True
# disable python warnings if they annoy you
disable_warnings: False
# output paths for hydra logs
hydra:
run:
dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
sweep:
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
subdir: ${hydra.job.num}
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=exp_example_simple
defaults:
- override /trainer: default_trainer.yaml
- override /model: mnist_model.yaml
- override /datamodule: mnist_datamodule.yaml
- override /callbacks: default_callbacks.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
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
Advanced example
# to execute this experiment run:
# python run.py +experiment=exp_example_full
defaults:
- 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 for more readibility
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"
tags: ["best_model", "uwu"]
notes: "Description of this model."
- Write your PyTorch Lightning model (see mnist_model.py for example)
- Write your PyTorch Lightning datamodule (see mnist_datamodule.py for example)
- Write your experiment config, containing paths to your model and datamodule
- Run training with chosen experiment config:
python run.py +experiment=experiment_name
Hydra creates new working directory for every executed run.
By default, logs have the following structure:
│
├── logs
│ ├── runs # Folder for logs generated from single runs
│ │ ├── 2021-02-15 # Date of executing run
│ │ │ ├── 16-50-49 # Hour of executing run
│ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ ├── wandb # Weights&Biases logs
│ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ └── ... # Any other thing saved during training
│ │ │ ├── ...
│ │ │ └── ...
│ │ ├── ...
│ │ └── ...
│ │
│ └── multiruns # Folder for logs generated from multiruns (sweeps)
│ ├── 2021-02-15_16-50-49 # Date and hour of executing sweep
│ │ ├── 0 # Job number
│ │ │ ├── .hydra # Hydra logs
│ │ │ ├── wandb # Weights&Biases logs
│ │ │ ├── checkpoints # Training checkpoints
│ │ │ └── ... # Any other thing saved during training
│ │ ├── 1
│ │ ├── 2
│ │ └── ...
│ ├── ...
│ └── ...
│
You can change this structure by modifying paths in main project configuration.
PyTorch Lightning supports the most popular logging frameworks:
Weights&Biases · Neptune · Comet · MLFlow · Aim · 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.
Template contains simple example of loading model from checkpoint and running predictions.
Take a look at inference_example.py.
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: WatchModelWithWandb, UploadCodeToWandbAsArtifact, UploadCheckpointsToWandbAsArtifact.
To provide examples of logging custom visualisations with callbacks only: LogConfusionMatrixToWandb, LogF1PrecRecHeatmapToWandb.
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.accelerator="ddp"
List of extra utilities available in the template:
- loading environment variables from .env file
- automatic virtual environment setup with .autoenv file
- pretty printing config with Rich library
- disabling python warnings
- easier access to debug mode
- forcing debug friendly configuration
- forcing multi-gpu friendly configuration
- method for logging hyperparameters to loggers
- (TODO) resuming latest run
You can easily remove any of those by modifying run.py and src/train.py.
(TODO)
Use Docker
Docker makes it easy to initialize the whole training environment, e.g. when you want to execute experiments in cloud or on some private computing cluster. You can extend dockerfiles provided in the template with your own instructions for building the image.
Use Miniconda
Use miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough).
It makes it easier to install some dependencies, like cudatoolkit for GPU support.
Example installation:
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
Docker image provided in the template already comes with initialized miniconda environment.
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) and Isort (python import sorting). You can exclude chosen files from automatic formatting, by modifying .pre-commit-config.yaml.
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.template
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: ${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.
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 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:
from setuptools import find_packages, setup
setup(
name="src", # you should change "src" to your project name
version="0.0.0",
description="Describe Your Cool Project",
author="",
author_email="",
# replace with your own github project link
url="https://github.com/ashleve/lightning-hydra-template",
install_requires=["pytorch-lightning>=1.2.0", "hydra-core>=1.0.6"],
packages=find_packages(),
)
Now your project can be installed from local files:
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
Write tests
(TODO)
Automatic activation of virtual environment and tab completion
Template contains .autoenv.template
file, which serves as an example. 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:
# activate conda environment
conda activate myenv
# initialize hydra tab completion for bash
eval "$(python run.py -sc install=bash)"
To setup this automation for bash, execute the following line:
echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
Explanation
This line appends your .bashrc
file with 3 commands:
autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; }
- this declares theautoenv()
function, which executes.autoenv
file if it exists in current work dircd() { builtin cd \"\$@\" ; autoenv ; }
- this extends behaviour ofcd
command, to make it executeautoenv()
function each time you change folder in terminalautoenv
this is just to ensure the function will also be called when directly openning terminal in any folder
Accessing datamodule attributes in model
The simplest way is to pass datamodule attribute directly to model on initialization:
datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
This is not a robust solution, since it assumes all your datamodules have some_param
attribute available (otherwise the run will crash).
A better solution is to add Omegaconf resolver to your datamodule:
from omegaconf import OmegaConf
# you can place this snippet in your datamodule __init__()
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 get 'datamodule.some_param' field
some_parameter: ${datamodule: some_param}
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. You also need to set resolve to false in print_config() in run.py method or it will throw errors!
template_utils.print_config(config, resolve=False)
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
- pytorch/hydra-torch - resources for configuring PyTorch classes with Hydra,
- romesco/hydra-lightning - resources for configuring PyTorch Lightning classes with Hydra
- lucmos/nn-template - similar template that's easier to start with but less scalable
List of repositories using this template
- ashleve/graph_classification - benchmarking graph neural network architectures on graph classification datasets (Open Graph Benchmarks and image classification from superpixels)
if you'd like to share your project and add it to the list, feel free to make a PR!
DELETE EVERYTHING ABOVE FOR YOUR PROJECT
What it does
Install dependencies
# clone project
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name
# [OPTIONAL] create conda environment
conda env create -f conda_env_gpu.yaml -n myenv
conda activate myenv
# install requirements
pip install -r requirements.txt
Train model with default configuration
# default
python run.py
# 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
You can override any parameter from command line like this
python run.py trainer.max_epochs=20 datamodule.batch_size=64