{"id":20200934,"url":"https://github.com/openclimatefix/climatehackai","last_synced_at":"2025-03-03T08:44:03.308Z","repository":{"id":42011189,"uuid":"480864626","full_name":"openclimatefix/climatehackai","owner":"openclimatefix","description":"Unified Repo for the models from the 2022 Climate Hack AI competition","archived":false,"fork":false,"pushed_at":"2025-02-17T17:39:42.000Z","size":63,"stargazers_count":10,"open_issues_count":1,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-02-17T18:40:00.821Z","etag":null,"topics":["deep-learning","pytorch"],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openclimatefix.png","metadata":{"funding":{"github":["openclimatefix"],"patreon":null,"open_collective":"openclimatefix","ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null},"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-04-12T15:18:52.000Z","updated_at":"2025-02-05T15:47:31.000Z","dependencies_parsed_at":"2023-12-11T18:44:38.211Z","dependency_job_id":"ca292d7c-31d0-4481-8bdb-504c588ccea7","html_url":"https://github.com/openclimatefix/climatehackai","commit_stats":{"total_commits":12,"total_committers":2,"mean_commits":6.0,"dds":"0.16666666666666663","last_synced_commit":"2ae7a62fd6afcbf096612a33f69ce87905a2205d"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":"ashleve/lightning-hydra-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openclimatefix%2Fclimatehackai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openclimatefix%2Fclimatehackai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openclimatefix%2Fclimatehackai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openclimatefix%2Fclimatehackai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openclimatefix","download_url":"https://codeload.github.com/openclimatefix/climatehackai/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241637191,"owners_count":19994927,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["deep-learning","pytorch"],"created_at":"2024-11-14T04:46:13.045Z","updated_at":"2025-03-03T08:44:03.287Z","avatar_url":"https://github.com/openclimatefix.png","language":"Python","funding_links":["https://github.com/sponsors/openclimatefix","https://opencollective.com/openclimatefix"],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# Climate Hack AI 2022 Models\n\n\u003ca href=\"https://www.python.org/\"\u003e\u003cimg alt=\"Python\" src=\"https://img.shields.io/badge/-Python 3.7+-blue?style=for-the-badge\u0026logo=python\u0026logoColor=white\"\u003e\u003c/a\u003e\n\u003ca href=\"https://pytorch.org/get-started/locally/\"\u003e\u003cimg alt=\"PyTorch\" src=\"https://img.shields.io/badge/-PyTorch 1.8+-ee4c2c?style=for-the-badge\u0026logo=pytorch\u0026logoColor=white\"\u003e\u003c/a\u003e\n\u003ca href=\"https://pytorchlightning.ai/\"\u003e\u003cimg alt=\"Lightning\" src=\"https://img.shields.io/badge/-Lightning 1.5+-792ee5?style=for-the-badge\u0026logo=pytorchlightning\u0026logoColor=white\"\u003e\u003c/a\u003e\n\u003ca href=\"https://hydra.cc/\"\u003e\u003cimg alt=\"Config: hydra\" src=\"https://img.shields.io/badge/config-hydra 1.1-89b8cd?style=for-the-badge\u0026labelColor=gray\"\u003e\u003c/a\u003e\n\u003ca href=\"https://black.readthedocs.io/en/stable/\"\u003e\u003cimg alt=\"Code style: black\" src=\"https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge\u0026labelColor=gray\"\u003e\u003c/a\u003e\n\nA clean and scalable template to kickstart your deep learning project 🚀⚡🔥\u003cbr\u003e\nClick on [\u003ckbd\u003eUse this template\u003c/kbd\u003e](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.\n\n_Suggestions are always welcome!_\n\n\u003c/div\u003e\n\n\u003cbr\u003e\u003cbr\u003e\n\n## 📌\u0026nbsp;\u0026nbsp;Introduction\n\nThis template tries to be as general as possible.\n\n\u003e Effective usage 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\u0026Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.\n\n**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 prototyping. Quick starting point for reproducing papers, hackathons, kaggle competitions or small-team research projects. It's also a collection of best practices for efficient workflow and reproducibility.\n\n**Why you shouldn't use it:** this template is not fitted to be a production/deployment environment, should be used more as a fast experimentation tool. Apart from that, Lightning and Hydra are still evolving and integrate many libraries, which means sometimes things break - for the list of currently known bugs, visit [this page](https://github.com/ashleve/lightning-hydra-template/labels/bug). Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task. See [#Limitations](#limitations) for more.\n\n### Why PyTorch Lightning?\n\n[PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning) is a lightweight PyTorch wrapper for high-performance AI research.\nIt makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.\n\n### Why Hydra?\n\n[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.\n\n\u003cbr\u003e\n\n## Main Ideas Of This Template\n\n- **Predefined Structure**: clean and scalable so that work can easily be extended and replicated | [#Project Structure](#project-structure)\n- **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers | [#Your Superpowers](#your-superpowers)\n- **Reproducibility**: obtaining similar results is supported in multiple ways | [#Reproducibility](#reproducibility)\n- **Little Boilerplate**: so pipeline can be easily modified | [#How It Works](#how-it-works)\n- **Main Configuration**: main config file specifies default training configuration | [#Main Project Configuration](#main-project-configuration)\n- **Experiment Configurations**: can be composed out of smaller configs and override chosen hyperparameters | [#Experiment Configuration](#experiment-configuration)\n- **Workflow**: comes down to 4 simple steps | [#Workflow](#workflow)\n- **Experiment Tracking**: many logging frameworks can be easily integrated, like Tensorboard, MLFlow or W\u0026B | [#Experiment Tracking](#experiment-tracking)\n- **Logs**: all logs (checkpoints, data from loggers, hparams, etc.) are stored in a convenient folder structure imposed by Hydra | [#Logs](#logs)\n- **Hyperparameter Search**: made easier with Hydra built-in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) | [#Hyperparameter Search](#hyperparameter-search)\n- **Tests**: unit tests and shell/command based tests for speeding up the development | [#Tests](#tests)\n- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility | [#Best Practices](#best-practices)\n\n\u003cbr\u003e\n\n## Project Structure\n\nThe directory structure of new project looks like this:\n\n```\n├── configs                   \u003c- Hydra configuration files\n│   ├── callbacks                \u003c- Callbacks configs\n│   ├── datamodule               \u003c- Datamodule configs\n│   ├── debug                    \u003c- Debugging configs\n│   ├── experiment               \u003c- Experiment configs\n│   ├── hparams_search           \u003c- Hyperparameter search configs\n│   ├── local                    \u003c- Local configs\n│   ├── log_dir                  \u003c- Logging directory configs\n│   ├── logger                   \u003c- Logger configs\n│   ├── model                    \u003c- Model configs\n│   ├── trainer                  \u003c- Trainer configs\n│   │\n│   ├── test.yaml             \u003c- Main config for testing\n│   └── train.yaml            \u003c- Main config for training\n│\n├── data                   \u003c- Project data\n│\n├── logs                   \u003c- Logs generated by Hydra and PyTorch Lightning loggers\n│\n├── notebooks              \u003c- Jupyter notebooks. Naming convention is a number (for ordering),\n│                             the creator's initials, and a short `-` delimited description,\n│                             e.g. `1.0-jqp-initial-data-exploration.ipynb`.\n│\n├── scripts                \u003c- Shell scripts\n│\n├── src                    \u003c- Source code\n│   ├── datamodules              \u003c- Lightning datamodules\n│   ├── models                   \u003c- Lightning models\n│   ├── utils                    \u003c- Utility scripts\n│   ├── vendor                   \u003c- Third party code that cannot be installed using PIP/Conda\n│   │\n│   ├── testing_pipeline.py\n│   └── training_pipeline.py\n│\n├── tests                  \u003c- Tests of any kind\n│   ├── helpers                  \u003c- A couple of testing utilities\n│   ├── shell                    \u003c- Shell/command based tests\n│   └── unit                     \u003c- Unit tests\n│\n├── test.py               \u003c- Run testing\n├── train.py              \u003c- Run training\n│\n├── .env.example              \u003c- Template of the file for storing private environment variables\n├── .gitignore                \u003c- List of files/folders ignored by git\n├── .pre-commit-config.yaml   \u003c- Configuration of pre-commit hooks for code formatting\n├── requirements.txt          \u003c- File for installing python dependencies\n├── setup.cfg                 \u003c- Configuration of linters and pytest\n└── README.md\n```\n\n\u003cbr\u003e\n\n## 🚀\u0026nbsp;\u0026nbsp;Quickstart\n\n```bash\n# clone project\ngit clone https://github.com/ashleve/lightning-hydra-template\ncd lightning-hydra-template\n\n# [OPTIONAL] create conda environment\nconda create -n myenv python=3.8\nconda activate myenv\n\n# install pytorch according to instructions\n# https://pytorch.org/get-started/\n\n# install requirements\npip install -r requirements.txt\n```\n\nTemplate contains example with MNIST classification.\u003cbr\u003e\nWhen running `python train.py` you should see something like this:\n\n\u003cdiv align=\"center\"\u003e\n\n![](https://github.com/ashleve/lightning-hydra-template/blob/resources/terminal.png)\n\n\u003c/div\u003e\n\n### ⚡\u0026nbsp;\u0026nbsp;Your Superpowers\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eOverride any config parameter from command line\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Hydra allows you to easily overwrite any parameter defined in your config.\n\n```bash\npython train.py trainer.max_epochs=20 model.lr=1e-4\n```\n\n\u003e You can also add new parameters with `+` sign.\n\n```bash\npython train.py +model.new_param=\"uwu\"\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTrain on CPU, GPU, multi-GPU and TPU\u003c/b\u003e\u003c/summary\u003e\n\n\u003e PyTorch Lightning makes it easy to train your models on different hardware.\n\n```bash\n# train on CPU\npython train.py trainer.gpus=0\n\n# train on 1 GPU\npython train.py trainer.gpus=1\n\n# train on TPU\npython train.py +trainer.tpu_cores=8\n\n# train with DDP (Distributed Data Parallel) (4 GPUs)\npython train.py trainer.gpus=4 +trainer.strategy=ddp\n\n# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)\npython train.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.strategy=ddp\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTrain with mixed precision\u003c/b\u003e\u003c/summary\u003e\n\n```bash\n# train with pytorch native automatic mixed precision (AMP)\npython train.py trainer.gpus=1 +trainer.precision=16\n```\n\n\u003c/details\u003e\n\n\u003c!-- deepspeed support still in beta\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eOptimize large scale models on multiple GPUs with Deepspeed\u003c/b\u003e\u003c/summary\u003e\n\n```bash\npython train.py +trainer.\n```\n\n\u003c/details\u003e\n --\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTrain model with any logger available in PyTorch Lightning, like Weights\u0026Biases or Tensorboard\u003c/b\u003e\u003c/summary\u003e\n\n\u003e 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.\u003cbr\u003e \u003e **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.**\n\n```bash\n# set project and entity names in `configs/logger/wandb`\nwandb:\n  project: \"your_project_name\"\n  entity: \"your_wandb_team_name\"\n```\n\n```bash\n# train model with Weights\u0026Biases (link to wandb dashboard should appear in the terminal)\npython train.py logger=wandb\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eTrain model with chosen experiment config\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Experiment configurations are placed in [configs/experiment/](configs/experiment/).\n\n```bash\npython train.py experiment=example\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eAttach some callbacks to run\u003c/b\u003e\u003c/summary\u003e\n\n\u003e 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).\u003cbr\u003e\n\u003e Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).\n\n```bash\npython train.py callbacks=default\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse different tricks available in Pytorch Lightning\u003c/b\u003e\u003c/summary\u003e\n\n\u003e PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).\n\n```yaml\n# gradient clipping may be enabled to avoid exploding gradients\npython train.py +trainer.gradient_clip_val=0.5\n\n# stochastic weight averaging can make your models generalize better\npython train.py +trainer.stochastic_weight_avg=true\n\n# run validation loop 4 times during a training epoch\npython train.py +trainer.val_check_interval=0.25\n\n# accumulate gradients\npython train.py +trainer.accumulate_grad_batches=10\n\n# terminate training after 12 hours\npython train.py +trainer.max_time=\"00:12:00:00\"\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eEasily debug\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Visit [configs/debug/](configs/debug/) for different debugging configs.\n\n```bash\n# runs 1 epoch in default debugging mode\n# changes logging directory to `logs/debugs/...`\n# sets level of all command line loggers to 'DEBUG'\n# enables extra trainer flags like tracking gradient norm\n# enforces debug-friendly configuration\npython train.py debug=default\n\n# runs test epoch without training\npython train.py debug=test_only\n\n# run 1 train, val and test loop, using only 1 batch\npython train.py +trainer.fast_dev_run=true\n\n# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf\npython train.py +trainer.detect_anomaly=true\n\n# print execution time profiling after training ends\npython train.py +trainer.profiler=\"simple\"\n\n# try overfitting to 1 batch\npython train.py +trainer.overfit_batches=1 trainer.max_epochs=20\n\n# use only 20% of the data\npython train.py +trainer.limit_train_batches=0.2 \\\n+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2\n\n# log second gradient norm of the model\npython train.py +trainer.track_grad_norm=2\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eResume training from checkpoint\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Checkpoint can be either path or URL.\n\n```yaml\npython train.py trainer.resume_from_checkpoint=\"/path/to/ckpt/name.ckpt\"\n```\n\n\u003e ⚠️ Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eExecute evaluation for a given checkpoint\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Checkpoint can be either path or URL.\n\n```yaml\npython test.py ckpt_path=\"/path/to/ckpt/name.ckpt\"\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eCreate a sweep over hyperparameters\u003c/b\u003e\u003c/summary\u003e\n\n```bash\n# this will run 6 experiments one after the other,\n# each with different combination of batch_size and learning rate\npython train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005\n```\n\n\u003e ⚠️ This sweep is not failure resistant (if one job crashes than the whole sweep crashes).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eCreate a sweep over hyperparameters with Optuna\u003c/b\u003e\u003c/summary\u003e\n\n\u003e 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)!\n\n```bash\n# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`\n# over chosen experiment config\npython train.py -m hparams_search=mnist_optuna experiment=example_simple\n```\n\n\u003e ⚠️ Currently this sweep is not failure resistant (if one job crashes than the whole sweep crashes). Might be supported in future Hydra release.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eExecute all experiments from folder\u003c/b\u003e\u003c/summary\u003e\n\n\u003e 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/).\n\n```bash\npython train.py -m 'experiment=glob(*)'\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eExecute sweep on a remote AWS cluster\u003c/b\u003e\u003c/summary\u003e\n\n\u003e This should be achievable with simple config using [Ray AWS launcher for Hydra](https://hydra.cc/docs/next/plugins/ray_launcher). Example is not yet implemented in this template.\n\n\u003c/details\u003e\n\n\u003c!-- \u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eExecute sweep on a SLURM cluster\u003c/b\u003e\u003c/summary\u003e\n\n\u003e This should be achievable with either [the right lightning trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/clouds/cluster.html?highlight=SLURM#slurm-managed-cluster) or simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.\n\n\u003c/details\u003e --\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse Hydra tab completion\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Learn more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eApply pre-commit hooks\u003c/b\u003e\u003c/summary\u003e\n\n\u003e Apply pre-commit hooks to automatically format your code and configs, perform code analysis and remove output from jupyter notebooks. See [# Best Practices](#best-practices) for more.\n\n```bash\npre-commit run -a\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n## ❤️\u0026nbsp;\u0026nbsp;Contributions\n\nHave a question? Found a bug? Missing a specific feature? Have an idea for improving documentation? Feel free to file a new issue, discussion 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 are always welcome!\n\n\u003cbr\u003e\n\n## ℹ️\u0026nbsp;\u0026nbsp;Guide\n\n### How To Get Started\n\n- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)\n- 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/)\n\n\u003cbr\u003e\n\n### How It Works\n\nAll PyTorch Lightning modules are dynamically instantiated from module paths specified in config. Example model config:\n\n```yaml\n_target_: src.models.mnist_model.MNISTLitModule\nlr: 0.001\n\nnet:\n  _target_: src.models.components.simple_dense_net.SimpleDenseNet\n  input_size: 784\n  lin1_size: 256\n  lin2_size: 256\n  lin3_size: 256\n  output_size: 10\n```\n\nUsing this config we can instantiate the object with the following line:\n\n```python\nmodel = hydra.utils.instantiate(config.model)\n```\n\nThis 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. \u003cbr\u003e\n\nSwitch between models and datamodules with command line arguments:\n\n```bash\npython train.py model=mnist\n```\n\nThe whole pipeline managing the instantiation logic is placed in [src/training_pipeline.py](src/training_pipeline.py).\n\n\u003cbr\u003e\n\n### Main Project Configuration\n\nLocation: [configs/train.yaml](configs/train.yaml) \u003cbr\u003e\nMain project config contains default training configuration.\u003cbr\u003e\nIt determines how config is composed when simply executing command `python train.py`.\u003cbr\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow main project config\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# specify here default training configuration\ndefaults:\n  - _self_\n  - datamodule: mnist.yaml\n  - model: mnist.yaml\n  - callbacks: default.yaml\n  - logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)\n  - trainer: default.yaml\n  - log_dir: default.yaml\n\n  # experiment configs allow for version control of specific configurations\n  # e.g. best hyperparameters for each combination of model and datamodule\n  - experiment: null\n\n  # debugging config (enable through command line, e.g. `python train.py debug=default)\n  - debug: null\n\n  # config for hyperparameter optimization\n  - hparams_search: null\n\n  # optional local config for machine/user specific settings\n  # it's optional since it doesn't need to exist and is excluded from version control\n  - optional local: default.yaml\n\n  # enable color logging\n  - override hydra/hydra_logging: colorlog\n  - override hydra/job_logging: colorlog\n\n# path to original working directory\n# hydra hijacks working directory by changing it to the new log directory\n# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory\noriginal_work_dir: ${hydra:runtime.cwd}\n\n# path to folder with data\ndata_dir: ${original_work_dir}/data/\n\n# pretty print config at the start of the run using Rich library\nprint_config: True\n\n# disable python warnings if they annoy you\nignore_warnings: True\n\n# set False to skip model training\ntrain: True\n\n# evaluate on test set, using best model weights achieved during training\n# lightning chooses best weights based on the metric specified in checkpoint callback\ntest: True\n\n# seed for random number generators in pytorch, numpy and python.random\nseed: null\n\n# default name for the experiment, determines logging folder path\n# (you can overwrite this name in experiment configs)\nname: \"default\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n### Experiment Configuration\n\nLocation: [configs/experiment](configs/experiment)\u003cbr\u003e\nExperiment configs allow you to overwrite parameters from main project configuration.\u003cbr\u003e\nFor example, you can use them to version control best hyperparameters for each combination of model and dataset.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow example experiment config\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# to execute this experiment run:\n# python train.py experiment=example\n\ndefaults:\n  - override /datamodule: mnist.yaml\n  - override /model: mnist.yaml\n  - override /callbacks: default.yaml\n  - override /logger: null\n  - override /trainer: default.yaml\n\n# all parameters below will be merged with parameters from default configurations set above\n# this allows you to overwrite only specified parameters\n\n# name of the run determines folder name in logs\nname: \"simple_dense_net\"\n\nseed: 12345\n\ntrainer:\n  min_epochs: 10\n  max_epochs: 10\n  gradient_clip_val: 0.5\n\nmodel:\n  lr: 0.002\n  net:\n    lin1_size: 128\n    lin2_size: 256\n    lin3_size: 64\n\ndatamodule:\n  batch_size: 64\n\nlogger:\n  wandb:\n    tags: [\"mnist\", \"${name}\"]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n### Local Configuration\n\nLocation: [configs/local](configs/local) \u003cbr\u003e\nSome 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.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow example local Slurm cluster config\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# @package _global_\n\ndefaults:\n  - override /hydra/launcher@_here_: submitit_slurm\n\ndata_dir: /mnt/scratch/data/\n\nhydra:\n  launcher:\n    timeout_min: 1440\n    gpus_per_task: 1\n    gres: gpu:1\n  job:\n    env_set:\n      MY_VAR: /home/user/my/system/path\n      MY_KEY: asdgjhawi8y23ihsghsueity23ihwd\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n### Workflow\n\n1. Write your PyTorch Lightning module (see [models/mnist_module.py](src/models/mnist_module.py) for example)\n2. Write your PyTorch Lightning datamodule (see [datamodules/mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)\n3. Write your experiment config, containing paths to your model and datamodule\n4. Run training with chosen experiment config: `python train.py experiment=experiment_name`\n\n\u003cbr\u003e\n\n### Logs\n\n**Hydra creates new working directory for every executed run.** By default, logs have the following structure:\n\n```\n├── logs\n│   ├── experiments                     # Folder for the logs generated by experiments\n│   │   ├── runs                          # Folder for single runs\n│   │   │   ├── experiment_name             # Experiment name\n│   │   │   │   ├── YYYY-MM-DD_HH-MM-SS       # Datetime of the run\n│   │   │   │   │   ├── .hydra                  # Hydra logs\n│   │   │   │   │   ├── csv                     # Csv logs\n│   │   │   │   │   ├── wandb                   # Weights\u0026Biases logs\n│   │   │   │   │   ├── checkpoints             # Training checkpoints\n│   │   │   │   │   └── ...                     # Any other thing saved during training\n│   │   │   │   └── ...\n│   │   │   └── ...\n│   │   │\n│   │   └── multiruns                     # Folder for multiruns\n│   │       ├── experiment_name             # Experiment name\n│   │       │   ├── YYYY-MM-DD_HH-MM-SS       # Datetime of the multirun\n│   │       │   │   ├──1                        # Multirun job number\n│   │       │   │   ├──2\n│   │       │   │   └── ...\n│   │       │   └── ...\n│   │       └── ...\n│   │\n│   ├── evaluations                       # Folder for the logs generated during testing\n│   │   └── ...\n│   │\n│   └── debugs                            # Folder for the logs generated during debugging\n│       └── ...\n```\n\nYou can change this structure by modifying paths in [hydra configuration](configs/log_dir).\n\n\u003cbr\u003e\n\n### Experiment Tracking\n\nPyTorch Lightning supports many popular logging frameworks:\u003cbr\u003e\n**[Weights\u0026Biases](https://www.wandb.com/) · [Neptune](https://neptune.ai/) · [Comet](https://www.comet.ml/) · [MLFlow](https://mlflow.org) · [Tensorboard](https://www.tensorflow.org/tensorboard/)**\n\nThese 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:\n\n```bash\npython train.py logger=logger_name\n```\n\nYou can use many of them at once (see [configs/logger/many_loggers.yaml](configs/logger/many_loggers.yaml) for example).\n\nYou can also write your own logger.\n\nLightning 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_module.py).\n\n\u003cbr\u003e\n\n### Hyperparameter Search\n\nDefining hyperparameter optimization is as easy as adding new config file to [configs/hparams_search](configs/hparams_search).\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow example\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\ndefaults:\n  - override /hydra/sweeper: optuna\n\n# choose metric which will be optimized by Optuna\noptimized_metric: \"val/acc_best\"\n\nhydra:\n  # here we define Optuna hyperparameter search\n  # it optimizes for value returned from function with @hydra.main decorator\n  # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper\n  sweeper:\n    _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper\n    storage: null\n    study_name: null\n    n_jobs: 1\n\n    # 'minimize' or 'maximize' the objective\n    direction: maximize\n\n    # number of experiments that will be executed\n    n_trials: 20\n\n    # choose Optuna hyperparameter sampler\n    # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html\n    sampler:\n      _target_: optuna.samplers.TPESampler\n      seed: 12345\n      consider_prior: true\n      prior_weight: 1.0\n      consider_magic_clip: true\n      consider_endpoints: false\n      n_startup_trials: 10\n      n_ei_candidates: 24\n      multivariate: false\n      warn_independent_sampling: true\n\n    # define range of hyperparameters\n    search_space:\n      datamodule.batch_size:\n        type: categorical\n        choices: [32, 64, 128]\n      model.lr:\n        type: float\n        low: 0.0001\n        high: 0.2\n      model.net.lin1_size:\n        type: categorical\n        choices: [32, 64, 128, 256, 512]\n      model.net.lin2_size:\n        type: categorical\n        choices: [32, 64, 128, 256, 512]\n      model.net.lin3_size:\n        type: categorical\n        choices: [32, 64, 128, 256, 512]\n```\n\n\u003c/details\u003e\n\nNext, you can execute it with: `python train.py -m hparams_search=mnist_optuna`\n\nUsing this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file.\n\nYou can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.\n\nThe `optimization_results.yaml` will be available under `logs/multirun` folder.\n\nThis approach doesn't support advanced technics like prunning - for more sophisticated search, you probably shouldn't use hydra multirun feature and instead write your own optimization pipeline.\n\n\u003cbr\u003e\n\n### Inference\n\nThe following code is an example of loading model from checkpoint and running predictions.\u003cbr\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow example\u003c/b\u003e\u003c/summary\u003e\n\n```python\nfrom PIL import Image\nfrom torchvision import transforms\n\nfrom src.models.mnist_module import MNISTLitModule\n\n\ndef predict():\n    \"\"\"Example of inference with trained model.\n    It loads trained image classification model from checkpoint.\n    Then it loads example image and predicts its label.\n    \"\"\"\n\n    # ckpt can be also a URL!\n    CKPT_PATH = \"last.ckpt\"\n\n    # load model from checkpoint\n    # model __init__ parameters will be loaded from ckpt automatically\n    # you can also pass some parameter explicitly to override it\n    trained_model = MNISTLitModule.load_from_checkpoint(checkpoint_path=CKPT_PATH)\n\n    # print model hyperparameters\n    print(trained_model.hparams)\n\n    # switch to evaluation mode\n    trained_model.eval()\n    trained_model.freeze()\n\n    # load data\n    img = Image.open(\"data/example_img.png\").convert(\"L\")  # convert to black and white\n    # img = Image.open(\"data/example_img.png\").convert(\"RGB\")  # convert to RGB\n\n    # preprocess\n    mnist_transforms = transforms.Compose(\n        [\n            transforms.ToTensor(),\n            transforms.Resize((28, 28)),\n            transforms.Normalize((0.1307,), (0.3081,)),\n        ]\n    )\n    img = mnist_transforms(img)\n    img = img.reshape((1, *img.size()))  # reshape to form batch of size 1\n\n    # inference\n    output = trained_model(img)\n    print(output)\n\n\nif __name__ == \"__main__\":\n    predict()\n\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n### Tests\n\nTemplate comes with example tests implemented with pytest library. To execute them simply run:\n\n```bash\n# run all tests\npytest\n\n# run tests from specific file\npytest tests/shell/test_basic_commands.py\n\n# run all tests except the ones marked as slow\npytest -k \"not slow\"\n```\n\nTo speed up the development, you can once in a while execute tests that run a couple of quick experiments, like training 1 epoch on 25% of data, executing single train/val/test step, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some bash commands doesn't end up in throwing exceptions. You can find them implemented in [tests/shell](tests/shell) folder.\n\nYou can easily modify the commands in the scripts for your use case. If 1 epoch is too much for your model, then make it run for a couple of batches instead (by using the right trainer flags).\n\n\u003cbr\u003e\n\n### Callbacks\n\nThe branch [`wandb-callbacks`](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks) contains example callbacks enabling better Weights\u0026Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks/src/callbacks/wandb_callbacks.py)).\n\nCallbacks which support reproducibility:\n\n- **WatchModel**\n- **UploadCodeAsArtifact**\n- **UploadCheckpointsAsArtifact**\n\nCallbacks which provide examples of logging custom visualisations:\n\n- **LogConfusionMatrix**\n- **LogF1PrecRecHeatmap**\n- **LogImagePredictions**\n\nTo try all of the callbacks at once, switch to the right branch:\n\n```bash\ngit checkout wandb-callbacks\n```\n\nAnd then run the following command:\n\n```bash\npython train.py logger=wandb callbacks=wandb\n```\n\nTo see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).\n\n\u003cbr\u003e\n\n### Multi-GPU Training\n\nLightning 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 the [lightning docs](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).\n\nYou can run DDP on mnist example with 4 GPUs like this:\n\n```bash\npython train.py trainer.gpus=4 +trainer.strategy=ddp\n```\n\n⚠️ 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).\n\n\u003cbr\u003e\n\n### Docker\n\nFirst you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.\n\nThe template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder.\n\nTo build the container use:\n\n```bash\ndocker build -t \u003cproject_name\u003e .\n```\n\nTo mount the project to the container use:\n\n```bash\ndocker run -v $(pwd):/workspace/project --gpus all -it --rm \u003cproject_name\u003e\n```\n\n\u003cbr\u003e\n\n### Reproducibility\n\nWhat provides reproducibility:\n\n- Hydra manages your configs.\n- Hydra manages your logging paths and makes every executed run store its hyperparameters and config overrides in a separate file in logs.\n- LightningDataModule allows you to encapsulate data split, transformations and default parameters in a single, clean abstraction.\n- LightningModule separates your research code from engineering code in a clean way.\n- Experiment tracking frameworks take care of logging metrics and hparams, some can also store results and artifacts in cloud.\n- Pytorch Lightning takes care of creating training checkpoints.\n- [Example callbacks for wandb](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks) show how you can save and upload a snapshot of codebase every time the run is executed, as well as upload ckpts and track model gradients.\n\n\u003c!--\nYou can load the config of previous run using:\n\n```bash\npython train.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml\n```\n\nThe `config.yaml` from `.hydra` folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the `hydra/` part of the config, meaning logging paths will revert to default!\n --\u003e\n\u003cbr\u003e\n\n### Limitations\n\n- Currently, template doesn't support k-fold cross validation, but it's possible to achieve it with Lightning Loop interface. See the [official example](https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/loop_examples/kfold.py). Implementing it requires rewriting the training pipeline.\n- Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.\n- Hydra changes working directory to new logging folder for every executed run, which might not be compatible with the way some libraries work.\n- Restoring logger state is currently not supported. This might change in future lightning realease.\n\n\u003cbr\u003e\n\n## Useful Tricks\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eAccessing datamodule attributes in model\u003c/b\u003e\u003c/summary\u003e\n\n1. The simplest way is to pass datamodule attribute directly to model on initialization:\n\n   ```python\n   # ./src/training_pipeline.py\n   datamodule = hydra.utils.instantiate(config.datamodule)\n   model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)\n   ```\n\n   This is not a very robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).\n\n2. If you only want to access datamodule config, you can simply pass it as an init parameter:\n\n   ```python\n   # ./src/training_pipeline.py\n   model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule, _recursive_=False)\n   ```\n\n   Now you can access any datamodule config part like this:\n\n   ```python\n   # ./src/models/my_model.py\n   class MyLitModel(LightningModule):\n   \tdef __init__(self, dm_conf, param1, param2):\n   \t\tsuper().__init__()\n\n   \t\tbatch_size = dm_conf.batch_size\n   ```\n\n3. If you need to access the datamodule object attributes, a little hacky solution is to add Omegaconf resolver to your datamodule:\n\n   ```python\n   # ./src/datamodules/my_datamodule.py\n   from omegaconf import OmegaConf\n\n   class MyDataModule(LightningDataModule):\n   \tdef __init__(self, param1, param2):\n   \t\tsuper().__init__()\n\n   \t\tself.param1 = param1\n\n   \t\tresolver_name = \"datamodule\"\n   \t\tOmegaConf.register_new_resolver(\n   \t\t\tresolver_name,\n   \t\t\tlambda name: getattr(self, name),\n   \t\t\tuse_cache=False\n   \t\t)\n   ```\n\n   This way you can reference any datamodule attribute from your config like this:\n\n   ```yaml\n   # this will return attribute 'param1' from datamodule object\n   param1: ${datamodule: param1}\n   ```\n\n   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 [train.py](train.py) or it will throw errors:**\n\n   ```python\n   # ./src/train.py\n   utils.print_config(config, resolve=False)\n   ```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eAutomatic activation of virtual environment and tab completion when entering folder\u003c/b\u003e\u003c/summary\u003e\n\n1. Create a new file called `.autoenv` (this name is excluded from version control in `.gitignore`). \u003cbr\u003e\n   You can use it to automatically execute shell commands when entering folder. Add some commands to your `.autoenv` file, like in the example below:\n\n   ```bash\n   # activate conda environment\n   conda activate myenv\n\n   # activate hydra tab completion for bash\n   eval \"$(python train.py -sc install=bash)\"\n   ```\n\n   (these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)\n\n2. To setup this automation for bash, execute the following line (it will append your `.bashrc` file):\n\n   ```bash\n   echo \"autoenv() { if [ -x .autoenv ]; then source .autoenv ; echo '.autoenv executed' ; fi } ; cd() { builtin cd \\\"\\$@\\\" ; autoenv ; } ; autoenv\" \u003e\u003e ~/.bashrc\n   ```\n\n3. Lastly add execution previliges to your `.autoenv` file:\n\n   ```\n   chmod +x .autoenv\n   ```\n\n   (for safety, only `.autoenv` with previligies will be executed)\n\n**Explanation**\n\nThe mentioned line appends your `.bashrc` file with 2 commands:\n\n1. `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\n2. `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\n\n\u003c/details\u003e\n\n\u003c!--\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eMaking sweeps failure resistant\u003c/b\u003e\u003c/summary\u003e\n\nTODO\n\n\u003c/details\u003e\n --\u003e\n\n\u003cbr\u003e\n\n## Best Practices\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse Miniconda for GPU environments\u003c/b\u003e\u003c/summary\u003e\n\nUse miniconda for your python environments (it's usually unnecessary to install full anaconda environment, miniconda should be enough).\nIt makes it easier to install some dependencies, like cudatoolkit for GPU support. It also allows you to acccess your environments globally.\n\nExample installation:\n\n```bash\nwget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\nbash Miniconda3-latest-Linux-x86_64.sh\n```\n\nCreate new conda environment:\n\n```bash\nconda create -n myenv python=3.8\nconda activate myenv\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse automatic code formatting\u003c/b\u003e\u003c/summary\u003e\n\nUse pre-commit hooks to standardize code formatting of your project and save mental energy.\u003cbr\u003e\nSimply install pre-commit package with:\n\n```bash\npip install pre-commit\n```\n\nNext, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):\n\n```bash\npre-commit install\n```\n\nAfter that your code will be automatically reformatted on every new commit.\u003cbr\u003e\nCurrently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **docformatter** (python docstring formatting), **flake8** (python code analysis), **prettier** (yaml formating) and **nbstripout** (clearing output from jupyter notebooks). \u003cbr\u003e\n\nTo reformat all files in the project use command:\n\n```bash\npre-commit run -a\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eSet private environment variables in .env file\u003c/b\u003e\u003c/summary\u003e\n\nSystem 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.\u003cbr\u003e\n\nTemplate contains `.env.example` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore).\nYou should use it for storing environment variables like this:\n\n```\nMY_VAR=/home/user/my_system_path\n```\n\nAll variables from `.env` are loaded in `train.py` automatically.\n\nHydra allows you to reference any env variable in `.yaml` configs like this:\n\n```yaml\npath_to_data: ${oc.env:MY_VAR}\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eName metrics using '/' character\u003c/b\u003e\u003c/summary\u003e\n\nDepending on which logger you're using, it's often useful to define metric name with `/` character:\n\n```python\nself.log(\"train/loss\", loss)\n```\n\nThis way loggers will treat your metrics as belonging to different sections, which helps to get them organised in UI.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse torchmetrics\u003c/b\u003e\u003c/summary\u003e\n\nUse official [torchmetrics](https://github.com/PytorchLightning/metrics) library to ensure proper calculation of metrics. This is especially important for multi-GPU training!\n\nFor example, instead of calculating accuracy by yourself, you should use the provided `Accuracy` class like this:\n\n```python\nfrom torchmetrics.classification.accuracy import Accuracy\n\n\nclass LitModel(LightningModule):\n    def __init__(self)\n        self.train_acc = Accuracy()\n        self.val_acc = Accuracy()\n\n    def training_step(self, batch, batch_idx):\n        ...\n        acc = self.train_acc(predictions, targets)\n        self.log(\"train/acc\", acc)\n        ...\n\n    def validation_step(self, batch, batch_idx):\n        ...\n        acc = self.val_acc(predictions, targets)\n        self.log(\"val/acc\", acc)\n        ...\n```\n\nMake sure to use different metric instance for each step to ensure proper value reduction over all GPU processes.\n\nTorchmetrics provides metrics for most use cases, like F1 score or confusion matrix. Read [documentation](https://torchmetrics.readthedocs.io/en/latest/#more-reading) for more.\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eFollow PyTorch Lightning style guide\u003c/b\u003e\u003c/summary\u003e\n\nThe style guide is available [here](https://pytorch-lightning.readthedocs.io/en/latest/starter/style_guide.html).\u003cbr\u003e\n\n1. 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!\n\n   ```python\n   class LitModel(LightningModule):\n       def __init__(self, layer_size: int = 256, lr: float = 0.001):\n   ```\n\n2. Preserve the recommended method order.\n\n   ```python\n   class LitModel(LightningModule):\n\n       def __init__():\n           ...\n\n       def forward():\n           ...\n\n       def training_step():\n           ...\n\n       def training_step_end():\n           ...\n\n       def training_epoch_end():\n           ...\n\n       def validation_step():\n           ...\n\n       def validation_step_end():\n           ...\n\n       def validation_epoch_end():\n           ...\n\n       def test_step():\n           ...\n\n       def test_step_end():\n           ...\n\n       def test_epoch_end():\n           ...\n\n       def configure_optimizers():\n           ...\n\n       def any_extra_hook():\n           ...\n   ```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eVersion control your data and models with DVC\u003c/b\u003e\u003c/summary\u003e\n\nUse [DVC](https://dvc.org) to version control big files, like your data or trained ML models.\u003cbr\u003e\nTo initialize the dvc repository:\n\n```bash\ndvc init\n```\n\nTo start tracking a file or directory, use `dvc add`:\n\n```bash\ndvc add data/MNIST\n```\n\nDVC 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:\n\n```bash\ngit add data/MNIST.dvc data/.gitignore\ngit commit -m \"Add raw data\"\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eSupport installing project as a package\u003c/b\u003e\u003c/summary\u003e\n\nIt allows other people to easily use your modules in their own projects.\nChange name of the `src` folder to your project name and add `setup.py` file:\n\n```python\nfrom setuptools import find_packages, setup\n\n\nsetup(\n    name=\"src\",  # change \"src\" folder name to your project name\n    version=\"0.0.0\",\n    description=\"Describe Your Cool Project\",\n    author=\"...\",\n    author_email=\"...\",\n    url=\"https://github.com/ashleve/lightning-hydra-template\",  # replace with your own github project link\n    install_requires=[\n        \"pytorch\u003e=1.10.0\",\n        \"pytorch-lightning\u003e=1.4.0\",\n        \"hydra-core\u003e=1.1.0\",\n    ],\n    packages=find_packages(),\n)\n```\n\nNow your project can be installed from local files:\n\n```bash\npip install -e .\n```\n\nOr directly from git repository:\n\n```bash\npip install git+git://github.com/YourGithubName/your-repo-name.git --upgrade\n```\n\nSo any file can be easily imported into any other file like so:\n\n```python\nfrom project_name.models.mnist_module import MNISTLitModule\nfrom project_name.datamodules.mnist_datamodule import MNISTDataModule\n```\n\n\u003c/details\u003e\n\n\u003c!-- \u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eMake notebooks independent from other files\u003c/b\u003e\u003c/summary\u003e\n\nIt's a good practice for jupyter notebooks to be portable. Try to make them independent from src files. If you need to access external code, try to embed it inside the notebook.\n\n\u003c/details\u003e --\u003e\n\n\u003c!--\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse Docker\u003c/b\u003e\u003c/summary\u003e\n\nDocker 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](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles) provided in the template with your own instructions for building the image.\u003cbr\u003e\n\n\u003c/details\u003e --\u003e\n\n\u003cbr\u003e\n\n## Other Repositories\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eInspirations\u003c/b\u003e\u003c/summary\u003e\n\nThis template was inspired by:\n[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),\n[drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),\n[tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),\n[Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest),\n[lucmos/nn-template](https://github.com/lucmos/nn-template).\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUseful repositories\u003c/b\u003e\u003c/summary\u003e\n\n- [pytorch/hydra-torch](https://github.com/pytorch/hydra-torch) - resources for configuring PyTorch classes with Hydra,\n- [romesco/hydra-lightning](https://github.com/romesco/hydra-lightning) - resources for configuring PyTorch Lightning classes with Hydra\n- [lucmos/nn-template](https://github.com/lucmos/nn-template) - similar template\n- [PyTorchLightning/lightning-transformers](https://github.com/PyTorchLightning/lightning-transformers) - official Lightning Transformers repo built with Hydra\n\n\u003c/details\u003e\n\n\u003c!-- ## :star:\u0026nbsp; Stargazers Over Time\n[![Stargazers over time](https://starchart.cc/ashleve/lightning-hydra-template.svg)](https://starchart.cc/ashleve/lightning-hydra-template) --\u003e\n\n\u003cbr\u003e\n\n## License\n\nThis project is licensed under the MIT License.\n\n```\nMIT License\n\nCopyright (c) 2021 ashleve\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n```\n\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\u003cbr\u003e\n\n**DELETE EVERYTHING ABOVE FOR YOUR PROJECT**\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n# Your Project Name\n\n\u003ca href=\"https://pytorch.org/get-started/locally/\"\u003e\u003cimg alt=\"PyTorch\" src=\"https://img.shields.io/badge/PyTorch-ee4c2c?logo=pytorch\u0026logoColor=white\"\u003e\u003c/a\u003e\n\u003ca href=\"https://pytorchlightning.ai/\"\u003e\u003cimg alt=\"Lightning\" src=\"https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning\u0026logoColor=white\"\u003e\u003c/a\u003e\n\u003ca href=\"https://hydra.cc/\"\u003e\u003cimg alt=\"Config: Hydra\" src=\"https://img.shields.io/badge/Config-Hydra-89b8cd\"\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/ashleve/lightning-hydra-template\"\u003e\u003cimg alt=\"Template\" src=\"https://img.shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat\u0026logo=github\u0026labelColor=gray\"\u003e\u003c/a\u003e\u003cbr\u003e\n[![Paper](http://img.shields.io/badge/paper-arxiv.1001.2234-B31B1B.svg)](https://www.nature.com/articles/nature14539)\n[![Conference](http://img.shields.io/badge/AnyConference-year-4b44ce.svg)](https://papers.nips.cc/paper/2020)\n\n\u003c/div\u003e\n\n## Description\n\nWhat it does\n\n## How to run\n\nInstall dependencies\n\n```bash\n# clone project\ngit clone https://github.com/YourGithubName/your-repo-name\ncd your-repo-name\n\n# [OPTIONAL] create conda environment\nconda create -n myenv python=3.8\nconda activate myenv\n\n# install pytorch according to instructions\n# https://pytorch.org/get-started/\n\n# install requirements\npip install -r requirements.txt\n```\n\nTrain model with default configuration\n\n```bash\n# train on CPU\npython train.py trainer.gpus=0\n\n# train on GPU\npython train.py trainer.gpus=1\n```\n\nTrain model with chosen experiment configuration from [configs/experiment/](configs/experiment/)\n\n```bash\npython train.py experiment=experiment_name.yaml\n```\n\nYou can override any parameter from command line like this\n\n```bash\npython train.py trainer.max_epochs=20 datamodule.batch_size=64\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenclimatefix%2Fclimatehackai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenclimatefix%2Fclimatehackai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenclimatefix%2Fclimatehackai/lists"}