{"id":23924504,"url":"https://github.com/dbpprt/sm-face-recognition","last_synced_at":"2026-05-16T15:34:01.437Z","repository":{"id":79098709,"uuid":"425069468","full_name":"dbpprt/sm-face-recognition","owner":"dbpprt","description":"Face recognition @ scale","archived":false,"fork":false,"pushed_at":"2021-11-05T20:42:34.000Z","size":32,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-11-16T15:22:21.639Z","etag":null,"topics":[],"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/dbpprt.png","metadata":{"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":"2021-11-05T19:58:28.000Z","updated_at":"2021-11-05T20:42:36.000Z","dependencies_parsed_at":null,"dependency_job_id":"5dd279df-7170-48f5-8d00-600205be89d4","html_url":"https://github.com/dbpprt/sm-face-recognition","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dbpprt/sm-face-recognition","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbpprt%2Fsm-face-recognition","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbpprt%2Fsm-face-recognition/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbpprt%2Fsm-face-recognition/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbpprt%2Fsm-face-recognition/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dbpprt","download_url":"https://codeload.github.com/dbpprt/sm-face-recognition/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dbpprt%2Fsm-face-recognition/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33108182,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-16T04:41:52.686Z","status":"ssl_error","status_checked_at":"2026-05-16T04:41:52.009Z","response_time":115,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":[],"created_at":"2025-01-05T19:15:00.612Z","updated_at":"2026-05-16T15:34:01.429Z","avatar_url":"https://github.com/dbpprt.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# Lightning-Hydra-Template\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.10+-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\n\u003c!-- \u003ca href=\"https://hub.docker.com/r/ashlev/lightning-hydra\"\u003e\u003cimg alt=\"Docker\" src=\"https://img.shields.io/badge/docker-257bd6?style=for-the-badge\u0026logo=docker\u0026logoColor=white\"\u003e\u003c/a\u003e --\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\u003cbr\u003e\u003cbr\u003e\n\n\u003c!--\nIf you use this template please add \u003cbr\u003e\n[![](https://shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat\u0026logo=github\u0026labelColor=303030)](https://github.com/ashleve/lightning-hydra-template) \u003cbr\u003e\nto your `README.md`.\n\u003cbr\u003e\u003cbr\u003e\n--\u003e\n\n## 📌\u0026nbsp;\u0026nbsp;Introduction\n\nThis 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).\n\n\u003e 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\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 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.\n\n**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. 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\u003cbr\u003e\n\u003cbr\u003e\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 (see [#Project Structure](#project-structure))\n- **Rapid Experimentation**: thanks to automating pipeline with config files and hydra command line superpowers (see [#Your Superpowers](#your-superpowers))\n- **Little Boilerplate**: so pipeline can be easily modified (see [src/train.py](src/train.py))\n- **Main Configuration**: main config file specifies default training configuration (see [#Main Project Configuration](#main-project-configuration))\n- **Experiment Configurations**: stored in a separate folder, they can be composed out of smaller configs, override chosen parameters or define everything from scratch (see [#Experiment Configuration](#experiment-configuration))\n- **Workflow**: comes down to 4 simple steps (see [#Workflow](#workflow))\n- **Experiment Tracking**: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))\n- **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))\n- **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))\n- **Tests**: unit tests and command based tests (see [#Tests](#tests))\n- **Extra Features**: optional utilities to make your life easier\n\u003c!-- - **Reproducibility**: ? --\u003e\n- **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices))\n  \u003cbr\u003e\n\n## Project Structure\n\nThe directory structure of new project looks like this:\n\n```\n├── bash                    \u003c- Bash scripts\n│   └── schedule.sh             \u003c- Schedule execution of many runs\n│\n├── configs                 \u003c- Hydra configuration files\n│   ├── callbacks               \u003c- Callbacks configs\n│   ├── datamodule              \u003c- Datamodule configs\n│   ├── experiment              \u003c- Experiment configs\n│   ├── hparams_search          \u003c- Hyperparameter search configs\n│   ├── logger                  \u003c- Logger configs\n│   ├── mode                    \u003c- Running mode configs\n│   ├── model                   \u003c- Model configs\n│   ├── trainer                 \u003c- Trainer configs\n│   │\n│   └── config.yaml             \u003c- Main project configuration file\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, e.g.\n│                              `1.0-jqp-initial-data-exploration.ipynb`.\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├── src\n│   ├── callbacks               \u003c- Lightning callbacks\n│   ├── datamodules             \u003c- Lightning datamodules\n│   ├── models                  \u003c- Lightning models\n│   ├── utils                   \u003c- Utility scripts\n│   │\n│   └── train.py                \u003c- Training pipeline\n│\n├── run.py                  \u003c- Run pipeline with chosen experiment configuration\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 automatic code formatting\n├── setup.cfg               \u003c- Configurations of linters and pytest\n├── requirements.txt        \u003c- File for installing python dependencies\n└── README.md\n```\n\n\u003cbr\u003e\n\n## 🚀\u0026nbsp;\u0026nbsp;Quickstart\n\n```yaml\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 run.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(click to expand)\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```yaml\npython run.py trainer.max_epochs=20 model.lr=1e-4\n```\n\n\u003e You can also add new parameters with `+` sign.\n\n```yaml\npython run.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```yaml\n# train on CPU\npython run.py trainer.gpus=0\n\n# train on 1 GPU\npython run.py trainer.gpus=1\n\n# train on TPU\npython run.py +trainer.tpu_cores=8\n\n# train with DDP (Distributed Data Parallel) (4 GPUs)\npython run.py trainer.gpus=4 +trainer.accelerator=ddp\n\n# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)\npython run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator=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```yaml\n# train with pytorch native automatic mixed precision (AMP)\npython run.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```yaml\npython run.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```yaml\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```yaml\n# train model with Weights\u0026Biases (link to wandb dashboard should appear in the terminal)\npython run.py logger=wandb\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eUse different running modes\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# debug mode changes logging folder to `logs/debug/`\n# also enables default trainer debugging options from `configs/trainer/debug.yaml`\n# also sets level of all command line loggers to 'DEBUG'\npython run.py mode=debug\n\n# experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/`\n# name is also used by loggers\npython run.py mode=exp name='my_new_experiment_253'\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```yaml\npython run.py experiment=example_simple\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```yaml\npython run.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 run.py +trainer.gradient_clip_val=0.5\n\n# stochastic weight averaging can make your models generalize better\npython run.py +trainer.stochastic_weight_avg=true\n\n# run validation loop 4 times during a training epoch\npython run.py +trainer.val_check_interval=0.25\n\n# accumulate gradients\npython run.py +trainer.accumulate_grad_batches=10\n\n# terminate training after 12 hours\npython run.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```yaml\n# run in debug mode\n# changes logging folder to `logs/debug/...`\n# enables trainer debugging options specified in `configs/trainer/debug.yaml`\n# sets level of all command line loggers to 'DEBUG'\npython run.py mode=debug\n\n# enable trainer debugging options specified in `configs/trainer/debug.yaml`\npython run.py trainer=debug\n\n# run 1 train, val and test loop, using only 1 batch\npython run.py +trainer.fast_dev_run=true\n\n# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf\npython run.py +trainer.detect_anomaly=true\n\n# print full weight summary of all PyTorch modules\npython run.py trainer.weights_summary=\"full\"\n\n# print execution time profiling after training ends\npython run.py +trainer.profiler=\"simple\"\n\n# try overfitting to 1 batch\npython run.py +trainer.overfit_batches=1 trainer.max_epochs=20\n\n# use only 20% of the data\npython run.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 run.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. Path should be absolute!\n\n```yaml\npython run.py +trainer.resume_from_checkpoint=\"/absolute/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\u003eCreate a sweep over hyperparameters\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# this will run 6 experiments one after the other,\n# each with different combination of batch_size and learning rate\npython run.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```yaml\n# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`\n# over chosen experiment config\npython run.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```yaml\npython run.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\u003cbr\u003e\n\n## 🐳\u0026nbsp;\u0026nbsp;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. \u003cbr\u003e\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\u003cbr\u003e\n\n## ❤️\u0026nbsp;\u0026nbsp;Contributions\n\nHave 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!\n\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\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  \u003cbr\u003e\n\n### How it works\n\nBy 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:\n\n```yaml\n_target_: src.models.mnist_model.MNISTLitModel\ninput_size: 784\nlin1_size: 256\nlin2_size: 256\nlin3_size: 256\noutput_size: 10\nlr: 0.001\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!\u003cbr\u003e\nEvery time you create a new one, just specify its module path and parameters in appriopriate config file. \u003cbr\u003e\nThe whole pipeline managing the instantiation logic is placed in [src/train.py](src/train.py).\n\n\u003cbr\u003e\n\n### Main Project Configuration\n\nLocation: [configs/config.yaml](configs/config.yaml)\u003cbr\u003e\nMain project config contains default training configuration.\u003cbr\u003e\nIt determines how config is composed when simply executing command `python run.py`.\u003cbr\u003e\nIt also specifies everything that shouldn't be managed by experiment configurations.\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow main project configuration\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# specify here default training configuration\ndefaults:\n  - trainer: default.yaml\n  - model: mnist_model.yaml\n  - datamodule: mnist_datamodule.yaml\n  - callbacks: default.yaml # set this to null if you don't want to use callbacks\n  - logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`)\n\n  - mode: default.yaml\n\n  - experiment: null\n  - hparams_search: null\n\n# path to original working directory\n# hydra hijacks working directory by changing it to the current log directory,\n# so it's useful to have this path as a special variable\n# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory\nwork_dir: ${hydra:runtime.cwd}\n\n# path to folder with data\ndata_dir: ${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\n\u003c/details\u003e\n\u003cbr\u003e\n\n### Experiment Configuration\n\nLocation: [configs/experiment](configs/experiment)\u003cbr\u003e\nYou should store all your experiment configurations in this folder.\u003cbr\u003e\nExperiment configurations allow you to overwrite parameters from main project configuration.\n\n**Simple example**\n\n```yaml\n# to execute this experiment run:\n# python run.py experiment=example_simple\n\ndefaults:\n  - override /mode: exp.yaml\n  - override /trainer: default.yaml\n  - override /model: mnist_model.yaml\n  - override /datamodule: mnist_datamodule.yaml\n  - override /callbacks: default.yaml\n  - override /logger: null\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 and is accessed by loggers\nname: \"example_simple\"\n\nseed: 12345\n\ntrainer:\n  max_epochs: 10\n  gradient_clip_val: 0.5\n\nmodel:\n  lin1_size: 128\n  lin2_size: 256\n  lin3_size: 64\n  lr: 0.005\n\ndatamodule:\n  train_val_test_split: [55_000, 5_000, 10_000]\n  batch_size: 64\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow advanced example\u003c/b\u003e\u003c/summary\u003e\n\n```yaml\n# to execute this experiment run:\n# python run.py experiment=example_full\n\ndefaults:\n  - override /mode: exp.yaml\n  - override /trainer: null\n  - override /model: null\n  - override /datamodule: null\n  - override /callbacks: null\n  - override /logger: null\n\n# we override default configurations with nulls to prevent them from loading at all\n# instead we define all modules and their paths directly in this config,\n# so everything is stored in one place\n\nname: \"example_full\"\n\nseed: 12345\n\ntrainer:\n  _target_: pytorch_lightning.Trainer\n  gpus: 0\n  min_epochs: 1\n  max_epochs: 10\n  gradient_clip_val: 0.5\n\nmodel:\n  _target_: src.models.mnist_model.MNISTLitModel\n  lr: 0.001\n  weight_decay: 0.00005\n  input_size: 784\n  lin1_size: 256\n  lin2_size: 256\n  lin3_size: 128\n  output_size: 10\n\ndatamodule:\n  _target_: src.datamodules.mnist_datamodule.MNISTDataModule\n  data_dir: ${data_dir}\n  train_val_test_split: [55_000, 5_000, 10_000]\n  batch_size: 64\n  num_workers: 0\n  pin_memory: False\n\nlogger:\n  wandb:\n    _target_: pytorch_lightning.loggers.wandb.WandbLogger\n    project: \"lightning-hydra-template\"\n    name: ${name}\n    tags: [\"best_model\", \"mnist\"]\n    notes: \"Description of this model.\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e\n\n### Workflow\n\n1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example)\n2. Write your PyTorch Lightning datamodule (see [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 run.py experiment=experiment_name`\n\n\u003cbr\u003e\n\n### Logs\n\n**Hydra creates new working directory for every executed run.** \u003cbr\u003e\nBy default, logs have the following structure:\n\n```\n│\n├── logs\n│   ├── experiments             # Folder for logs generated by experiments\n│   │   ├── experiment_name         # Name of the experiment\n│   │   │   ├── 2021-02-15_16-50-49     # Date of execution\n│   │   │   │   ├── .hydra                  # Hydra logs\n│   │   │   │   ├── wandb                   # Weights\u0026Biases logs\n│   │   │   │   ├── checkpoints             # Training checkpoints\n│   │   │   │   └── ...                     # Any other thing saved during training\n│   │   │   └── ...\n│   │   ├── ...\n│   │   └── ...\n│   │\n│   ├── debugs                  # Folder for logs generated during debugging\n│   │   ├── 2021-02-15\n│   │   │   ├── 16-50-49\n│   │   │   └── ...\n│   │   ├── ...\n│   │   └── ...\n│   │\n│   ├── runs                    # Folder for logs generated by normal runs\n│   │   ├── 2021-02-15\n│   │   │   ├── 16-50-49\n│   │   │   │   └── ...\n│   │   │   ├── ...\n│   │   │   └── ...\n│   │   ├── ...\n│   │   └── ...\n│   │\n│   └── multiruns               # Folder for logs generated by multiruns (sweeps)\n│       ├── 2021-02-15_16-50-49\n│       │   ├── 0\n│       │   │   └── ...\n│       │   ├── 1\n│       │   ├── 2\n│       │   └── ...\n│       ├── ...\n│       └── ...\n│\n```\n\nYou can change this structure by modifying paths in [hydra configuration](configs/mode).\n\u003cbr\u003e\u003cbr\u003e\n\n### Experiment Tracking\n\nPyTorch Lightning supports the most 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```yaml\npython run.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_model.py).\n\u003cbr\u003e\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.lin1_size:\n        type: categorical\n        choices: [32, 64, 128, 256, 512]\n      model.lin2_size:\n        type: categorical\n        choices: [32, 64, 128, 256, 512]\n      model.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 run.py -m hparams_search=mnist_optuna`\u003cbr\u003e\nUsing this approach doesn't require you to add any boilerplate into your pipeline, everything is defined in a single config file. You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad. The `optimization_results.yaml` will be available under `logs/multirun` folder.\n\u003cbr\u003e\u003cbr\u003e\n\n### Inference\n\nThe following is example of loading model from checkpoint and running predictions.\u003cbr\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003e\u003cb\u003eShow inference example\u003c/b\u003e\u003c/summary\u003e\n\n```python\nfrom PIL import Image\nfrom torchvision import transforms\n\nfrom src.models.mnist_model import MNISTLitModel\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 = MNISTLitModel.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\u003cbr\u003e\n\n### Tests\n\nTemplate comes with example tests implemented with pytest library. \u003cbr\u003e\nTo execute them simply run:\n\n```yaml\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\nI 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.\n\nYou 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).\n\u003cbr\u003e\u003cbr\u003e\n\n### Callbacks\n\nTemplate contains example callbacks enabling better Weights\u0026Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](src/callbacks/wandb_callbacks.py)).\u003cbr\u003e\nTo support reproducibility:\n\n- **WatchModel**\n- **UploadCodeAsArtifact**\n- **UploadCheckpointsAsArtifact**\n\nTo provide examples of logging custom visualisations with callbacks only:\n\n- **LogConfusionMatrix**\n- **LogF1PrecRecHeatmap**\n- **LogImagePredictions**\n\nTo try all of the callbacks at once, use:\n\n```yaml\npython run.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\u003cbr\u003e\u003cbr\u003e\n\n### Multi-GPU Training\n\nLightning supports multiple ways of doing distributed training.\u003cbr\u003e\nThe 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).\n\nYou can run DDP on mnist example with 4 GPUs like this:\n\n```yaml\npython run.py trainer.gpus=4 +trainer.accelerator=\"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\u003cbr\u003e\u003cbr\u003e\n\n\u003c!--\n### Reproducibility\n\nTo reproduce previous experiment, simply load its config from logs:\n\n```yaml\npython run.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml\n```\n\nThe `config.yaml` from `.hydra` folder contains all overriden parameters and sections.\n\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n--\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- Pytorch Lightning might not the best choice for scalable reinforcement learning, it's probably better to use something like [Ray](https://github.com/ray-project/ray).\n- Currently hyperparameter search with Hydra Optuna Plugin doesn't support prunning.\n\n\u003cbr\u003e\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/train.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/train.py\n   model = hydra.utils.instantiate(config.model, dm_conf=config.datamodule)\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 [run.py](run.py) or it will throw errors:**\n\n   ```python\n   # ./src/run.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 run.py -sc install=bash)\"\n\n   # enable aliases for debugging\n   alias debug='python run.py mode=debug'\n   alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0'\n   alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1'\n   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'\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\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\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.\u003cbr\u003e\nExample installation:\n\n```yaml\nwget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\nbash Miniconda3-latest-Linux-x86_64.sh\n```\n\nCreate environment using bash script provided in the template:\n\n```yaml\nbash bash/setup_conda.sh\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```yaml\npip install pre-commit\n```\n\nNext, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml):\n\n```yaml\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), **flake8** (python code analysis) and **prettier** (yaml formating). \u003cbr\u003e\n\nTo reformat all files in the project use command:\n\n```yaml\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```yaml\nMY_VAR=/home/user/my_system_path\n```\n\nAll variables from `.env` are loaded in `run.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```yaml\ndvc init\n```\n\nTo start tracking a file or directory, use `dvc add`:\n\n```yaml\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```yaml\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```yaml\npip install -e .\n```\n\nOr directly from git repository:\n\n```yaml\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_model import MNISTLitModel\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\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```yaml\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```yaml\n# train on CPU\npython run.py trainer.gpus=0\n\n# train on GPU\npython run.py trainer.gpus=1\n```\n\nTrain model with chosen experiment configuration from [configs/experiment/](configs/experiment/)\n\n```yaml\npython run.py experiment=experiment_name.yaml\n```\n\nYou can override any parameter from command line like this\n\n```yaml\npython run.py trainer.max_epochs=20 datamodule.batch_size=64\n```\n\n\u003cbr\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbpprt%2Fsm-face-recognition","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdbpprt%2Fsm-face-recognition","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdbpprt%2Fsm-face-recognition/lists"}