diff --git a/README.md b/README.md index 390991a..d3698a7 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,18 @@ # Lightning-Hydra-Template - Python PyTorch Lightning Config: hydra Code style: black + A clean and scalable template to kickstart your deep learning project πŸš€βš‘πŸ”₯
Click on [Use this template](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository. -*Suggestions are always welcome!* +_Suggestions are always welcome!_

@@ -26,27 +26,29 @@ to your `README.md`. --> ## πŸ“Œ  Introduction + 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](src/train.py). > Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) 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, kaggle competitions or small-team research projects. 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. +**Why you shouldn't use it:** this template is not fitted to be a production environment, should be used more as a fast experimentation tool. Apart from that, Lightning and Hydra are not yet very 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. ### Why PyTorch Lightning? + [PyTorch Lightning](https://github.com/PyTorchLightning/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. - ### Why Hydra? -[Hydra](https://github.com/facebookresearch/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](https://hydra.cc/docs/next/plugins/optuna_sweeper) for hyperparameter search, or [Ray Launcher](https://hydra.cc/docs/next/plugins/ray_launcher) for running jobs on a cluster. -
-
-
+[Hydra](https://github.com/facebookresearch/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](https://hydra.cc/docs/next/plugins/optuna_sweeper) for hyperparameter search, or [Ray Launcher](https://hydra.cc/docs/next/plugins/ray_launcher) for running jobs on a cluster. +
+
+
## Main Ideas Of This Template + - **Predefined Structure**: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure)) - **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers (see [#Your Superpowers](#your-superpowers)) - **Little Boilerplate**: so pipeline can be easily modified (see [src/train.py](src/train.py)) @@ -57,13 +59,14 @@ It makes your code neatly organized and provides lots of useful features, like a - **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - **Hyperparameter Search**: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) (see [#Hyperparameter Search](#hyperparameter-search)) - **Tests**: unit tests and command based tests (see [#Tests](#tests)) -- **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features)) +- **Extra Features**: optional utilities to make your life easier - **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices)) -
- +
## Project Structure + The directory structure of new project looks like this: + ``` β”œβ”€β”€ bash <- Bash scripts β”‚ β”œβ”€β”€ setup_conda.sh <- Setup conda environment @@ -111,10 +114,11 @@ The directory structure of new project looks like this: β”œβ”€β”€ requirements.txt <- File for installing python dependencies └── README.md ``` +
- ## πŸš€  Quickstart + ```yaml # clone project git clone https://github.com/ashleve/lightning-hydra-template @@ -129,6 +133,7 @@ pip install -r requirements.txt Template contains example with MNIST classification.
When running `python run.py` you should see something like this: +
![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png) @@ -136,27 +141,31 @@ When running `python run.py` you should see something like this:
### ⚑  Your Superpowers + (click to expand)
Override any config parameter from command line > Hydra allows you to easily overwrite any parameter defined in your config. + ```yaml python run.py trainer.max_epochs=20 model.lr=1e-4 ``` + > You can also add new parameters with `+` sign. + ```yaml python run.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. + ```yaml # train on CPU python run.py trainer.gpus=0 @@ -176,7 +185,6 @@ python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp'
-
Train with mixed precision @@ -192,17 +200,16 @@ python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
-
Train model with any logger available in PyTorch Lightning, like Weights&Biases -> PyTorch Lightning provides convenient integrations with most popular logging frameworks, like Tensorboard, Neptune or simple csv files. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below.
-**Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.** +> PyTorch Lightning provides convenient integrations with most popular logging frameworks, like Tensorboard, Neptune or simple csv files. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below.
> **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.** + ```yaml # set project and entity names in `configs/logger/wandb` wandb: - project: "your_project_name" - entity: "your_wandb_team_name" + project: "your_project_name" + entity: "your_wandb_team_name" ``` ```yaml @@ -212,7 +219,6 @@ python run.py logger=wandb
-
Use different running modes @@ -229,34 +235,34 @@ python run.py mode=exp name='my_new_experiment_253'
-
Train model with chosen experiment config > Experiment configurations are placed in [configs/experiment/](configs/experiment/). + ```yaml python run.py experiment=example_simple ```
-
Attach some callbacks to run > Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).
-Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/). +> Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/). + ```yaml python run.py callbacks=default ```
-
Use different tricks available in Pytorch Lightning > PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags). + ```yaml # gradient clipping may be enabled to avoid exploding gradients python run.py +trainer.gradient_clip_val=0.5 @@ -276,7 +282,6 @@ python run.py +trainer.max_time="00:12:00:00"
-
Easily debug @@ -310,19 +315,19 @@ python run.py +trainer.track_grad_norm=2
-
Resume training from checkpoint > Checkpoint can be either path or URL. Path should be absolute! + ```yaml 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 @@ -331,27 +336,31 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt" # each with different combination of batch_size and learning rate python run.py -m datamodule.batch_size=32,64,128 model.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. + +> ⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).
-
Create a sweep over hyperparameters with Optuna > Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a [single config file](configs/hparams_search/mnist_optuna.yaml)! + ```yaml # 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=example_simple ``` +> ⚠️ Currently this sweep is not failure resistant (if one job crashes than the whole sweep crashes). Might be supported in future Hydra release. +
Execute all experiments from folder > Hydra provides special syntax for controlling behavior of multiruns. Learn more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run). The command below executes all experiments from folder [configs/experiment/](configs/experiment/). + ```yaml python run.py -m 'experiment=glob(*)' ``` @@ -372,7 +381,6 @@ python run.py -m 'experiment=glob(*)'
--> -
Use Hydra tab completion @@ -381,41 +389,44 @@ python run.py -m 'experiment=glob(*)'

- ## 🐳  Docker -First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
+ +First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder. To build the container use: + ```bash docker build -t . ``` + To mount the project to the container use: + ```bash docker run -v $(pwd):/workspace/project --gpus all -it --rm ``` + Uncomment Apex in Dockerfile for mixed-precision support.


- - ## ❀️  Contributions + 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!



- - ## ℹ️  Guide ### How To Get Started + - First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) - Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/) and [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) -
- +
### How it works + By design, every run is initialized by [run.py](run.py) file. All PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config: + ```yaml _target_: src.models.mnist_model.MNISTLitModel input_size: 784 @@ -425,39 +436,42 @@ lin3_size: 256 output_size: 10 lr: 0.001 ``` + Using this config we can instantiate the object with the following line: + ```python 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.
The whole pipeline managing the instantiation logic is placed in [src/train.py](src/train.py).
- ### Main Project Configuration + Location: [configs/config.yaml](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 ```yaml # specify here default training configuration defaults: - - trainer: default.yaml - - model: mnist_model.yaml - - datamodule: mnist_datamodule.yaml - - callbacks: default.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`) + - trainer: default.yaml + - model: mnist_model.yaml + - datamodule: mnist_datamodule.yaml + - callbacks: default.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`) - - mode: default.yaml - - - experiment: null - - hparams_search: null + - mode: default.yaml + - experiment: null + - hparams_search: null # path to original working directory # hydra hijacks working directory by changing it to the current log directory, @@ -465,15 +479,12 @@ defaults: # 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/ - # pretty print config at the start of the run using Rich library print_config: True - # disable python warnings if they annoy you ignore_warnings: True ``` @@ -481,23 +492,24 @@ ignore_warnings: True

- ### Experiment Configuration + Location: [configs/experiment](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** + ```yaml # to execute this experiment run: # python run.py experiment=example_simple defaults: - - override /trainer: default.yaml - - override /model: mnist_model.yaml - - override /datamodule: mnist_datamodule.yaml - - override /callbacks: default.yaml - - override /logger: null + - override /trainer: default.yaml + - override /model: mnist_model.yaml + - override /datamodule: mnist_datamodule.yaml + - override /callbacks: default.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 @@ -505,21 +517,21 @@ defaults: seed: 12345 trainer: - max_epochs: 10 - gradient_clip_val: 0.5 + max_epochs: 10 + gradient_clip_val: 0.5 model: - lin1_size: 128 - lin2_size: 256 - lin3_size: 64 - lr: 0.005 + 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 + train_val_test_split: [55_000, 5_000, 10_000] + batch_size: 64 ``` - +
Show advanced example @@ -529,11 +541,11 @@ datamodule: # python run.py experiment=example_full defaults: - - override /trainer: null - - override /model: null - - override /datamodule: null - - override /callbacks: null - - override /logger: null + - 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, @@ -542,36 +554,36 @@ defaults: seed: 12345 trainer: - _target_: pytorch_lightning.Trainer - gpus: 0 - min_epochs: 1 - max_epochs: 10 - gradient_clip_val: 0.5 + _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 + _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 + _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." + wandb: + _target_: pytorch_lightning.loggers.wandb.WandbLogger + project: "lightning-hydra-template" + tags: ["best_model", "uwu"] + notes: "Description of this model." ```
@@ -579,15 +591,18 @@ logger:
### Workflow + 1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example) 2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example) 3. Write your experiment config, containing paths to your model and datamodule 4. Run training with chosen experiment config: `python run.py experiment=experiment_name` -
+
### Logs + Hydra creates new working directory for every executed run.
By default, logs have the following structure: + ``` β”‚ β”œβ”€β”€ logs @@ -621,84 +636,84 @@ By default, logs have the following structure: You can change this structure by modifying paths in [hydra configuration](configs/mode).

- ### Experiment Tracking + PyTorch Lightning supports the most popular logging frameworks:
**[Weights&Biases](https://www.wandb.com/) Β· [Neptune](https://neptune.ai/) Β· [Comet](https://www.comet.ml/) Β· [MLFlow](https://mlflow.org) Β· [Tensorboard](https://www.tensorflow.org/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](configs/logger) and run: - ```yaml - python run.py logger=logger_name - ``` + +```yaml +python run.py logger=logger_name +``` + You can use many of them at once (see [configs/logger/many_loggers.yaml](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](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging) or take a look at [MNIST example](src/models/mnist_model.py).

- - ### Hyperparameter Search + Defining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search](configs/hparams_search). +
Show example ```yaml defaults: - - override /hydra/sweeper: optuna - + - override /hydra/sweeper: optuna # choose metric which will be optimized by Optuna optimized_metric: "val/acc" - hydra: - # here we define Optuna hyperparameter search - # it optimizes for value returned from function with @hydra.main decorator - # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper - sweeper: - _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper - storage: null - study_name: null - n_jobs: 1 + # here we define Optuna hyperparameter search + # it optimizes for value returned from function with @hydra.main decorator + # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper + sweeper: + _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper + storage: null + study_name: null + n_jobs: 1 - # 'minimize' or 'maximize' the objective - direction: maximize + # 'minimize' or 'maximize' the objective + direction: maximize - # number of experiments that will be executed - n_trials: 20 + # number of experiments that will be executed + n_trials: 20 - # choose Optuna hyperparameter sampler - # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html - sampler: - _target_: optuna.samplers.TPESampler - seed: 12345 - consider_prior: true - prior_weight: 1.0 - consider_magic_clip: true - consider_endpoints: false - n_startup_trials: 10 - n_ei_candidates: 24 - multivariate: false - warn_independent_sampling: true + # choose Optuna hyperparameter sampler + # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html + sampler: + _target_: optuna.samplers.TPESampler + seed: 12345 + consider_prior: true + prior_weight: 1.0 + consider_magic_clip: true + consider_endpoints: false + n_startup_trials: 10 + n_ei_candidates: 24 + multivariate: false + warn_independent_sampling: true - # define range of hyperparameters - search_space: - datamodule.batch_size: - type: categorical - choices: [32, 64, 128] - model.lr: - type: float - low: 0.0001 - high: 0.2 - model.lin1_size: - type: categorical - choices: [32, 64, 128, 256, 512] - model.lin2_size: - type: categorical - choices: [32, 64, 128, 256, 512] - model.lin3_size: - type: categorical - choices: [32, 64, 128, 256, 512] + # define range of hyperparameters + search_space: + datamodule.batch_size: + type: categorical + choices: [32, 64, 128] + model.lr: + type: float + low: 0.0001 + high: 0.2 + model.lin1_size: + type: categorical + choices: [32, 64, 128, 256, 512] + model.lin2_size: + type: categorical + choices: [32, 64, 128, 256, 512] + model.lin3_size: + type: categorical + choices: [32, 64, 128, 256, 512] ```
@@ -707,10 +722,10 @@ Next, you can execute it with: `python run.py -m hparams_search=mnist_optuna`

- - ### Inference + The following is example of loading model from checkpoint and running predictions.
+
Show inference example @@ -770,11 +785,11 @@ if __name__ == "__main__":

- - ### Tests + Template comes with example tests implemented with pytest library.
To execute them simply run: + ```yaml # run all tests pytest @@ -785,26 +800,29 @@ pytest tests/shell/test_basic_commands.py # run all tests except the ones marked as slow pytest -k "not slow" ``` + I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of 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 find them implemented in [tests/shell](tests/shell) folder. You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).

- - ### Callbacks + 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](src/callbacks/wandb_callbacks.py)).
To support reproducibility: + - **WatchModel** - **UploadCodeAsArtifact** - **UploadCheckpointsAsArtifact** To provide examples of logging custom visualisations with callbacks only: + - **LogConfusionMatrix** - **LogF1PrecRecHeatmap** - **LogImagePredictions** To try all of the callbacks at once, use: + ```yaml python run.py logger=wandb callbacks=wandb ``` @@ -812,30 +830,149 @@ python run.py logger=wandb callbacks=wandb To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).

- - ### Multi-GPU 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 [lightning docs](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html). You can run DDP on mnist example with 4 GPUs like this: + ```yaml python run.py trainer.gpus=4 +trainer.accelerator="ddp" ``` + ⚠️ When using DDP you have to be careful how you write your models - learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).

- ### Reproducibility + To reproduce previous experiment, simply load its config from logs: + ```yaml python run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml ``` -The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. -

+The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. +


+ +## Useful Tricks + +
+Accessing datamodule attributes in model + +1. The simplest way is to pass datamodule attribute directly to model on initialization: + + ```python + # ./src/train.py + datamodule = hydra.utils.instantiate(config.datamodule) + model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param) + ``` + + This is not a very robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash). + +2. If you only want to access datamodule config, you can simply pass it as an init parameter: + + ```python + # ./src/train.py + model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule) + ``` + + Now you can access any datamodule config part like this: + + ```python + # ./src/models/my_model.py + class MyLitModel(LightningModule): + def __init__(self, dm_conf, param1, param2): + super().__init__() + + batch_size = dm_conf.batch_size + ``` + +3. If you need to access the datamodule object attributes, a little hacky solution is to add Omegaconf resolver to your datamodule: + + ```python + # ./src/datamodules/my_datamodule.py + from omegaconf import OmegaConf + + class MyDataModule(LightningDataModule): + def __init__(self, param1, param2): + super().__init__() + + self.param1 = param1 + + 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: + + ```yaml + # this will return attribute 'param1' from datamodule object + param1: ${datamodule: param1} + ``` + + 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 or it will crash. **You also need to set `resolve=False` in `print_config()` in [run.py](run.py) or it will throw errors:** + + ```python + # ./src/run.py + utils.print_config(config, resolve=False) + ``` + +
+ +
+Automatic activation of virtual environment and tab completion when entering folder + +1. 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. Add some commands to your `.autoenv` file, like in the example below: + + ```bash + # activate conda environment + conda activate myenv + + # activate hydra tab completion for bash + eval "$(python run.py -sc install=bash)" + + # enable aliases for debugging + alias debug='python run.py mode=debug' + alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0' + alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1' + alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests' + ``` + + (these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file) + +2. To setup this automation for bash, execute the following line (it will append your `.bashrc` file): + + ```bash + echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc + ``` + +3. Lastly add execution previliges to your `.autoenv` file: + + ``` + chmod +x .autoenv + ``` + + (for safety, only `.autoenv` with previligies will be executed) + +**Explanation** + +The mentioned line appends your `.bashrc` file with 2 commands: + +1. `autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir and has execution previligies +2. `cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal or open new terminal + +
+ +
## Best Practices + +
- - - -## Tricks -
-Automatic activation of virtual environment and tab completion when entering folder - - -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. - -To setup this automation for bash, execute the following line: -```bash -echo "autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc -``` - -Now you can add any commands to your `.autoenv` file, e.g. activation of virtual environment and hydra tab completion: -```bash -# activate conda environment -conda activate myenv - -# activate hydra tab completion for bash -eval "$(python run.py -sc install=bash)" - -# enable aliases for debugging -alias debug='python run.py mode=debug' -alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0' -alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1' -alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests' -``` -(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file) - -Lastly add execution previliges to your `.autoenv` file: -``` -chmod +x .autoenv -``` - -**Explanation**
-The mentioned line appends your `.bashrc` file with 2 commands: -1. `autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir and has execution previligies -2. `cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal or open new terminal - -
- - - - - -
-Accessing datamodule attributes in model - -The simplest way is to pass datamodule attribute directly to model on initialization: -```python -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: -```python -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: -```yaml -# 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](run.py) method or it will throw errors!** -```python -utils.print_config(config, resolve=False) -``` - -
- - -
- - ## Other Repositories
@@ -1178,16 +1257,15 @@ This template was inspired by:
- -
- ## License + This project is licensed under the MIT License. + ``` MIT License @@ -1212,14 +1290,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -



- - **DELETE EVERYTHING ABOVE FOR YOUR PROJECT** --- @@ -1238,10 +1313,13 @@ SOFTWARE. ## Description + What it does ## How to run + Install dependencies + ```yaml # clone project git clone https://github.com/YourGithubName/your-repo-name @@ -1255,6 +1333,7 @@ pip install -r requirements.txt ``` Train model with default configuration + ```yaml # default python run.py @@ -1267,11 +1346,13 @@ python run.py trainer.gpus=1 ``` Train model with chosen experiment configuration from [configs/experiment/](configs/experiment/) + ```yaml python run.py experiment=experiment_name ``` You can override any parameter from command line like this + ```yaml python run.py trainer.max_epochs=20 datamodule.batch_size=64 ```