Views
No views yet
Note: Keep in mind this is unofficial community project.
├── .github <- Github Actions workflows
│
├── 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 <- 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
│ ├── 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
├── .project-root <- File for inferring the position of project root directory
├── environment.yaml <- File for installing conda environment
├── Makefile <- Makefile with commands like `make train` or `make test`
├── pyproject.toml <- Configuration options for testing and linting
├── requirements.txt <- File for installing python dependencies
├── setup.py <- File for installing project as a package
└── README.md1# clone project
2git clone https://github.com/ashleve/lightning-hydra-template
3cd lightning-hydra-template
4
5# [OPTIONAL] create conda environment
6conda create -n myenv python=3.9
7conda activate myenv
8
9# install pytorch according to instructions
10# https://pytorch.org/get-started/
11
12# install requirements
13pip install -r requirements.txtpython 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"1# train on CPU
2python train.py trainer=cpu
3
4# train on 1 GPU
5python train.py trainer=gpu
6
7# train on TPU
8python train.py +trainer.tpu_cores=8
9
10# train with DDP (Distributed Data Parallel) (4 GPUs)
11python train.py trainer=ddp trainer.devices=4
12
13# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
14python train.py trainer=ddp trainer.devices=4 trainer.num_nodes=2
15
16# simulate DDP on CPU processes
17python train.py trainer=ddp_sim trainer.devices=2
18
19# accelerate training on mac
20python train.py trainer=mpsWarning: Currently there are problems with DDP mode, read this issue to learn more.
1# train with pytorch native automatic mixed precision (AMP)
2python train.py trainer=gpu +trainer.precision=161# set project and entity names in `configs/logger/wandb`
2wandb:
3 project: "your_project_name"
4 entity: "your_wandb_team_name"1# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
2python 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.
Note: Click here to see example wandb dashboard generated with this template.
python train.py experiment=exampleNote: 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.
Note: Callbacks configs are placed in configs/callbacks/.
1# gradient clipping may be enabled to avoid exploding gradients
2python train.py +trainer.gradient_clip_val=0.5
3
4# run validation loop 4 times during a training epoch
5python train.py +trainer.val_check_interval=0.25
6
7# accumulate gradients
8python train.py +trainer.accumulate_grad_batches=10
9
10# terminate training after 12 hours
11python train.py +trainer.max_time="00:12:00:00"Note: PyTorch Lightning provides about 40+ useful trainer flags.
1# runs 1 epoch in default debugging mode
2# changes logging directory to `logs/debugs/...`
3# sets level of all command line loggers to 'DEBUG'
4# enforces debug-friendly configuration
5python train.py debug=default
6
7# run 1 train, val and test loop, using only 1 batch
8python train.py debug=fdr
9
10# print execution time profiling
11python train.py debug=profiler
12
13# try overfitting to 1 batch
14python train.py debug=overfit
15
16# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
17python train.py +trainer.detect_anomaly=true
18
19# use only 20% of the data
20python train.py +trainer.limit_train_batches=0.2 \
21+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2Note: 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.
Note: 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"Note: Checkpoint can be either path or URL.
1# this will run 6 experiments one after the other,
2# each with different combination of batch_size and learning rate
3python train.py -m data.batch_size=32,64,128 model.lr=0.001,0.0005Note: 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.
1# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
2# over chosen experiment config
3python 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.
Warning: Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).
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/.
python train.py -m seed=1,2,3,4,5 trainer.deterministic=True logger=csv tags=["benchmark"]Note:trainer.deterministic=Truemakes pytorch more deterministic but impacts the performance.
Note: This should be achievable with simple config using Ray AWS launcher for Hydra. Example is not implemented in this template.
Note: Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressingtabkey. 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.
.pre-commit-config.yaml with:pre-commit autoupdate1# run all tests
2pytest
3
4# run tests from specific file
5pytest tests/test_train.py
6
7# run all tests except the ones marked as slow
8pytest -k "not slow"python train.py tags=["mnist","experiment_X"]Note: You might need to escape the bracket characters in your shell withpython train.py tags=\["mnist","experiment_X"\].
1>>> python train.py tags=[]
2[2022-07-11 15:40:09,358][src.utils.utils][INFO] - Enforcing tags! <cfg.extras.enforce_tags=True>
3[2022-07-11 15:40:09,359][src.utils.rich_utils][WARNING] - No tags provided in config. Prompting user to input tags...
4Enter a list of comma separated tags (dev):1>>> python train.py -m +x=1,2,3 tags=[]
2ValueError: Specify tags before launching a multirun!Note: Appending lists from command line is currently not supported in hydra :(
main branch.1_target_: src.models.mnist_model.MNISTLitModule
2lr: 0.001
3net:
4 _target_: src.models.components.simple_dense_net.SimpleDenseNet
5 input_size: 784
6 lin1_size: 256
7 lin2_size: 256
8 lin3_size: 256
9 output_size: 10model = hydra.utils.instantiate(config.model)python train.py model=mnistpython train.py.1# order of defaults determines the order in which configs override each other
2defaults:
3 - _self_
4 - data: mnist.yaml
5 - model: mnist.yaml
6 - callbacks: default.yaml
7 - logger: null # set logger here or use command line (e.g. `python train.py logger=csv`)
8 - trainer: default.yaml
9 - paths: default.yaml
10 - extras: default.yaml
11 - hydra: default.yaml
12
13 # experiment configs allow for version control of specific hyperparameters
14 # e.g. best hyperparameters for given model and datamodule
15 - experiment: null
16
17 # config for hyperparameter optimization
18 - hparams_search: null
19
20 # optional local config for machine/user specific settings
21 # it's optional since it doesn't need to exist and is excluded from version control
22 - optional local: default.yaml
23
24 # debugging config (enable through command line, e.g. `python train.py debug=default)
25 - debug: null
26
27# task name, determines output directory path
28task_name: "train"
29
30# tags to help you identify your experiments
31# you can overwrite this in experiment configs
32# overwrite from command line with `python train.py tags="[first_tag, second_tag]"`
33# appending lists from command line is currently not supported :(
34# https://github.com/facebookresearch/hydra/issues/1547
35tags: ["dev"]
36
37# set False to skip model training
38train: True
39
40# evaluate on test set, using best model weights achieved during training
41# lightning chooses best weights based on the metric specified in checkpoint callback
42test: True
43
44# simply provide checkpoint path to resume training
45ckpt_path: null
46
47# seed for random number generators in pytorch, numpy and python.random
48seed: null1# @package _global_
2
3# to execute this experiment run:
4# python train.py experiment=example
5
6defaults:
7 - override /data: mnist.yaml
8 - override /model: mnist.yaml
9 - override /callbacks: default.yaml
10 - override /trainer: default.yaml
11
12# all parameters below will be merged with parameters from default configurations set above
13# this allows you to overwrite only specified parameters
14
15tags: ["mnist", "simple_dense_net"]
16
17seed: 12345
18
19trainer:
20 min_epochs: 10
21 max_epochs: 10
22 gradient_clip_val: 0.5
23
24model:
25 optimizer:
26 lr: 0.002
27 net:
28 lin1_size: 128
29 lin2_size: 256
30 lin3_size: 64
31
32data:
33 batch_size: 64
34
35logger:
36 wandb:
37 tags: ${tags}
38 group: "mnist"python src/train.py experiment=experiment_name.yamlpython train.py -m logger=csv data.batch_size=16,32,64,128 tags=["batch_size_exp"]logs/ folder and retrieves csv logs from runs containing given tags in config. Plot the results.├── 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
│ └── ...python train.py logger=logger_namepytest.1# run all tests
2pytest
3
4# run tests from specific file
5pytest tests/test_train.py
6
7# run all tests except the ones marked as slow
8pytest -k "not slow"@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.1# @package _global_
2
3defaults:
4 - override /hydra/sweeper: optuna
5
6# choose metric which will be optimized by Optuna
7# make sure this is the correct name of some metric logged in lightning module!
8optimized_metric: "val/acc_best"
9
10# here we define Optuna hyperparameter search
11# it optimizes for value returned from function with @hydra.main decorator
12hydra:
13 sweeper:
14 _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
15
16 # 'minimize' or 'maximize' the objective
17 direction: maximize
18
19 # total number of runs that will be executed
20 n_trials: 20
21
22 # choose Optuna hyperparameter sampler
23 # docs: https://optuna.readthedocs.io/en/stable/reference/samplers.html
24 sampler:
25 _target_: optuna.samplers.TPESampler
26 seed: 1234
27 n_startup_trials: 10 # number of random sampling runs before optimization starts
28
29 # define hyperparameter search space
30 params:
31 model.optimizer.lr: interval(0.0001, 0.1)
32 data.batch_size: choice(32, 64, 128, 256)
33 model.net.lin1_size: choice(64, 128, 256)
34 model.net.lin2_size: choice(64, 128, 256)
35 model.net.lin3_size: choice(32, 64, 128, 256)python train.py -m hparams_search=mnist_optunaoptimization_results.yaml will be available under logs/task_name/multirun folder..github/workflows/test.yaml: running all tests with pytest.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 onlypython train.py trainer=ddpNote: When using DDP you have to be careful how you write your models - read the docs.
1# ./src/train.py
2datamodule = hydra.utils.instantiate(config.data)
3model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)Note: Not a very robust solution, since it assumes all your datamodules havesome_paramattribute available.
1# ./src/train.py
2model = hydra.utils.instantiate(config.model, dm_conf=config.data, _recursive_=False)1# ./configs/model/my_model.yaml
2_target_: src.models.my_module.MyLitModule
3lr: 0.01
4some_param: ${data.some_param}1# ./src/models/mnist_module.py
2def on_train_start(self):
3 self.some_param = self.trainer.datamodule.some_paramNote: This only works after the training starts since otherwise trainer won't be yet available in LightningModule.
1wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
2bash Miniconda3-latest-Linux-x86_64.shconda update -n base -c defaults conda1conda create -n myenv python=3.10
2conda activate myenvpip install pre-commitpre-commit installpre-commit run -apre-commit autoupdate.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.env are loaded in train.py automatically..yaml configs like this:path_to_data: ${oc.env:MY_VAR}/ character:self.log("train/loss", loss)Accuracy class like this:1from torchmetrics.classification.accuracy import Accuracy
2
3
4class LitModel(LightningModule):
5 def __init__(self)
6 self.train_acc = Accuracy()
7 self.val_acc = Accuracy()
8
9 def training_step(self, batch, batch_idx):
10 ...
11 acc = self.train_acc(predictions, targets)
12 self.log("train/acc", acc)
13 ...
14
15 def validation_step(self, batch, batch_idx):
16 ...
17 acc = self.val_acc(predictions, targets)
18 self.log("val/acc", acc)
19 ...1class LitModel(LightningModule):
2 def __init__(self, layer_size: int = 256, lr: float = 0.001):1class LitModel(LightningModule):
2
3 def __init__():
4 ...
5
6 def forward():
7 ...
8
9 def training_step():
10 ...
11
12 def training_step_end():
13 ...
14
15 def on_train_epoch_end():
16 ...
17
18 def validation_step():
19 ...
20
21 def validation_step_end():
22 ...
23
24 def on_validation_epoch_end():
25 ...
26
27 def test_step():
28 ...
29
30 def test_step_end():
31 ...
32
33 def on_test_epoch_end():
34 ...
35
36 def configure_optimizers():
37 ...
38
39 def any_extra_hook():
40 ...dvc initdvc add:dvc add data/MNIST1git add data/MNIST.dvc data/.gitignore
2git commit -m "Add raw data"src folder to your project name and complete the setup.py file.pip install -e .pip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade1from project_name.models.mnist_module import MNISTLitModule
2from project_name.data.mnist_datamodule import MNISTDataModule1# @package _global_
2
3defaults:
4 - override /hydra/launcher@_here_: submitit_slurm
5
6data_dir: /mnt/scratch/data/
7
8hydra:
9 launcher:
10 timeout_min: 1440
11 gpus_per_task: 1
12 gres: gpu:1
13 job:
14 env_set:
15 MY_VAR: /home/user/my/system/path
16 MY_KEY: asdgjhawi8y23ihsghsueity23ihwdMIT 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.1# clone project
2git clone https://github.com/YourGithubName/your-repo-name
3cd your-repo-name
4
5# [OPTIONAL] create conda environment
6conda create -n myenv python=3.9
7conda activate myenv
8
9# install pytorch according to instructions
10# https://pytorch.org/get-started/
11
12# install requirements
13pip install -r requirements.txt1# clone project
2git clone https://github.com/YourGithubName/your-repo-name
3cd your-repo-name
4
5# create conda environment and install dependencies
6conda env create -f environment.yaml -n myenv
7
8# activate conda environment
9conda activate myenv1# train on CPU
2python src/train.py trainer=cpu
3
4# train on GPU
5python src/train.py trainer=gpupython src/train.py experiment=experiment_name.yamlpython src/train.py trainer.max_epochs=20 data.batch_size=64