Dev (#93)
* rework lightning model for mnist * sort imports * add comment to pre-commit-config * remove returns from test_step because it's bugged * update experiment configs * Update README.md
This commit is contained in:
1 parent
67d531ab67
commit
b1e0bf9717
23 files changed
+469
-309
No files matched your search
+10
-12
@@ -2,37 +2,35 @@ default_language_version:
|
|||||||
python: python3.8
|
python: python3.8
|
||||||
|
|
||||||
repos:
|
repos:
|
||||||
|
|
||||||
|
# Pre-commit-hooks
|
||||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||||
rev: v3.2.0
|
rev: v3.2.0
|
||||||
hooks:
|
hooks:
|
||||||
# list of supported hooks: https://pre-commit.com/hooks.html
|
# list of supported hooks: https://pre-commit.com/hooks.html
|
||||||
- id: end-of-file-fixer
|
|
||||||
- id: trailing-whitespace
|
- id: trailing-whitespace
|
||||||
- id: debug-statements
|
- id: debug-statements
|
||||||
- id: detect-private-key
|
- id: detect-private-key
|
||||||
- id: check-yaml
|
- id: check-yaml
|
||||||
- id: check-added-large-files
|
- id: check-added-large-files
|
||||||
|
|
||||||
|
|
||||||
# Black (code formatting)
|
# Black (code formatting)
|
||||||
- repo: https://github.com/psf/black
|
- repo: https://github.com/psf/black
|
||||||
rev: 20.8b1
|
rev: 20.8b1
|
||||||
hooks:
|
hooks:
|
||||||
- id: black
|
- id: black
|
||||||
args: [--force-exclude, train.py]
|
# args: [--force-exclude, train.py]
|
||||||
|
|
||||||
|
|
||||||
# Isort (import sorting)
|
# Isort (import sorting)
|
||||||
# - repo: https://github.com/PyCQA/isort
|
- repo: https://github.com/PyCQA/isort
|
||||||
# rev: 5.7.0
|
rev: 5.7.0
|
||||||
# hooks:
|
hooks:
|
||||||
# - id: isort
|
- id: isort
|
||||||
# # profiles: https://pycqa.github.io/isort/docs/configuration/profiles/
|
# profiles: https://pycqa.github.io/isort/docs/configuration/profiles/
|
||||||
# # other flags: https://pycqa.github.io/isort/docs/configuration/options/
|
# other flags: https://pycqa.github.io/isort/docs/configuration/options/
|
||||||
# args: [--profile, black]
|
args: [--profile, black, --skip, train.py, --filter-files]
|
||||||
# files: "src/.*"
|
# files: "src/.*"
|
||||||
|
|
||||||
|
|
||||||
# MyPy (static type checking)
|
# MyPy (static type checking)
|
||||||
# - repo: https://github.com/pre-commit/mirrors-mypy
|
# - repo: https://github.com/pre-commit/mirrors-mypy
|
||||||
# rev: v0.790
|
# rev: v0.790
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
# PyTorch Lightning + Hydra Template
|
# Lightning-Hydra-Template
|
||||||
|
|
||||||
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-orange?style=for-the-badge&logo=pytorch"></a>
|
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-orange?style=for-the-badge&logo=pytorch"></a>
|
||||||
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-blueviolet?style=for-the-badge"></a>
|
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-blueviolet?style=for-the-badge"></a>
|
||||||
@@ -10,15 +10,11 @@
|
|||||||
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
|
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
|
||||||
Click on [<kbd>Use this template</kbd>](https://github.com/hobogalaxy/lightning-hydra-template/generate) to initialize new repository.
|
Click on [<kbd>Use this template</kbd>](https://github.com/hobogalaxy/lightning-hydra-template/generate) to initialize new repository.
|
||||||
|
|
||||||
This template tries to be as general as possible.
|
*This template is work in progress. Suggestions are always welcome!*
|
||||||
You should be able to easily modify behavior in [train.py](train.py) in case you need some unconventional configuration wiring.
|
|
||||||
|
|
||||||
*This template is work in progress.* <br>
|
|
||||||
*Suggestions are always welcome!*
|
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
<br>
|
<br><br>
|
||||||
<br>
|
|
||||||
|
|
||||||
|
|
||||||
If you use this template please add <br>
|
If you use this template please add <br>
|
||||||
@@ -28,37 +24,47 @@ to your `README.md`.
|
|||||||
|
|
||||||
|
|
||||||
**Contents**
|
**Contents**
|
||||||
- [PyTorch Lightning + Hydra Template](#pytorch-lightning--hydra-template)
|
- [Introduction](#introduction)
|
||||||
- [Why Lightning + Hydra?](#why-lightning--hydra)
|
- [Main Ideas Of This Template](#main-ideas-of-this-template)
|
||||||
- [Main Ideas](#main-ideas)
|
|
||||||
- [Some Notes](#some-notes)
|
|
||||||
- [Project Structure](#project-structure)
|
- [Project Structure](#project-structure)
|
||||||
- [Quickstart](#quickstart)
|
- [Quickstart](#quickstart)
|
||||||
- [Your Superpowers](#your-superpowers)
|
- [Guide](#guide)
|
||||||
- [Features](#features)
|
- [How To Start?](#how-to-start)
|
||||||
- [Main Project Configuration](#main-project-configuration)
|
- [Main Project Configuration](#main-project-configuration)
|
||||||
- [Experiment Configuration](#experiment-configuration)
|
- [Experiment Configuration](#experiment-configuration)
|
||||||
- [Simple Example](#simple-example)
|
|
||||||
- [Advanced Example](#advanced-example)
|
|
||||||
- [Workflow](#workflow)
|
- [Workflow](#workflow)
|
||||||
- [Logs](#logs)
|
- [Logs](#logs)
|
||||||
- [Experiment Tracking](#experiment-tracking)
|
- [Experiment Tracking](#experiment-tracking)
|
||||||
- [Tests](#tests)
|
- [Callbacks](#callbacks)
|
||||||
- [Distributed Training](#distributed-training)
|
- [Best Practices](#best-practices)
|
||||||
- [Linting](#linting)
|
|
||||||
- [Tricks](#tricks)
|
- [Tricks](#tricks)
|
||||||
- [Examples Of Repositories Using This Template](#examples-of-repositories-using-this-template)
|
- [Other Repositories](#other-repositories)
|
||||||
- [Installing project as a package](#installing-project-as-a-package)
|
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## Why Lightning + Hydra?
|
## Introduction
|
||||||
- <b>[PyTorch Lightning](https://github.com/PyTorchLightning/pytorch-lightning)</b> provides great abstractions for well structured ML code and advanced features like checkpointing, gradient accumulation, distributed training, etc.
|
This template tries to be as general as possible.
|
||||||
- <b>[Hydra](https://github.com/facebookresearch/hydra)</b> provides convenient way to manage experiment configurations and advanced features like overriding any config parameter from command line, scheduling execution of many runs, etc.
|
By using it, you avoid writing any boilerplate code. At the same time it's flexible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [train.py](train.py).
|
||||||
|
|
||||||
|
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
|
||||||
|
|
||||||
|
The main advantage of using it, is that it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it might be the most convenient and all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility.
|
||||||
|
|
||||||
|
The main arguments for not using this template, are that Lightning and Hydra are not yet mature, which means you will probably run into some bugs. Also Lightning is not well suited for everything, e.g. for Reinforcement Learning it's probably better to replace it with Ray/RLlib.
|
||||||
|
|
||||||
|
### Why PyTorch Lightning?
|
||||||
|
PyTorch Lightning is a lightweight PyTorch wrapper for high-performance AI research.
|
||||||
|
Makes your code neatly organized and provides lots of useful features, like ability to run model on CPU, GPU, multi-GPU cluster and TPU.
|
||||||
|
|
||||||
|
|
||||||
|
### Why Hydra?
|
||||||
|
Hydra 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 provides convenient ways to manage experiments and advanced features like overriding any config parameter from command line or sweeping over hyperparameters.
|
||||||
|
<br>
|
||||||
|
<br>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## Main Ideas
|
## Main Ideas Of This Template
|
||||||
- Predefined Structure: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure))
|
- Predefined Structure: clean and scalable so that work can easily be extended and replicated (see [#Project Structure](#project-structure))
|
||||||
- Rapid Experimentation: thanks to automating pipeline with config files and hydra command line superpowers
|
- Rapid Experimentation: thanks to automating pipeline with config files and hydra command line superpowers
|
||||||
- Little Boilerplate: so pipeline can be easily modified (see [train.py](train.py))
|
- Little Boilerplate: so pipeline can be easily modified (see [train.py](train.py))
|
||||||
@@ -66,26 +72,9 @@ to your `README.md`.
|
|||||||
- 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))
|
- 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))
|
||||||
- Experiment Tracking: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))
|
- Experiment Tracking: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking))
|
||||||
- Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))
|
- Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs))
|
||||||
- Smoke Tests: simple bash scripts running 1-2 epoch experiments to check if your model doesn't crash under different conditions (see [tests](tests/))
|
|
||||||
- Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper)
|
- Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper)
|
||||||
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
|
- Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
|
||||||
<br>
|
- Best Practices: a couple of recommended tools, practices and standards (see [#Best Practices](#best-practices))
|
||||||
|
|
||||||
|
|
||||||
## Some Notes
|
|
||||||
- ***Warning: this template currently uses development version of hydra which might be unstable (we wait until Hydra 1.1 is released).*** <br>
|
|
||||||
- *Inspired by:
|
|
||||||
[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),
|
|
||||||
[drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),
|
|
||||||
[tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),
|
|
||||||
[Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest),
|
|
||||||
[ryul99/pytorch-project-template](https://github.com/ryul99/pytorch-project-template).*
|
|
||||||
- *Check out [lucmos/nn-template](https://github.com/lucmos/nn-template) for easier-to-start but less scalable version of this template.*
|
|
||||||
- *To learn how to configure PyTorch with Hydra take a look at [this detailed MNIST tutorial](https://github.com/pytorch/hydra-torch/blob/master/examples/mnist_00.md).*
|
|
||||||
- *Repositories useful for configuring PyTorch and PyTorch Lightning classes with Hydra:
|
|
||||||
[romesco/hydra-lightning](https://github.com/romesco/hydra-lightning),
|
|
||||||
[pytorch/hydra-torch](https://github.com/pytorch/hydra-torch).*
|
|
||||||
- *Suggestions are always welcome!*
|
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
@@ -94,10 +83,11 @@ The directory structure of new project looks like this:
|
|||||||
```
|
```
|
||||||
├── configs <- Hydra configuration files
|
├── configs <- Hydra configuration files
|
||||||
│ ├── trainer <- Configurations of Lightning trainers
|
│ ├── trainer <- Configurations of Lightning trainers
|
||||||
│ ├── model <- Configurations of Lightning models
|
|
||||||
│ ├── datamodule <- Configurations of Lightning datamodules
|
│ ├── datamodule <- Configurations of Lightning datamodules
|
||||||
|
│ ├── model <- Configurations of Lightning models
|
||||||
│ ├── callbacks <- Configurations of Lightning callbacks
|
│ ├── callbacks <- Configurations of Lightning callbacks
|
||||||
│ ├── logger <- Configurations of Lightning loggers
|
│ ├── logger <- Configurations of Lightning loggers
|
||||||
|
│ ├── optimizer <- Configurations of optimizers
|
||||||
│ ├── experiment <- Configurations of experiments
|
│ ├── experiment <- Configurations of experiments
|
||||||
│ │
|
│ │
|
||||||
│ ├── config.yaml <- Main project configuration file
|
│ ├── config.yaml <- Main project configuration file
|
||||||
@@ -161,23 +151,38 @@ When running `python train.py` you should see something like this:
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
### Your Superpowers
|
### Your Superpowers
|
||||||
(click to expand)
|
*(click to expand)*
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Override any config parameter from command line</summary>
|
<summary>Override any config parameter from command line</summary>
|
||||||
|
|
||||||
|
> *Hydra allows you to overwrite any parameter defined in your config, without writing any code!*
|
||||||
```yaml
|
```yaml
|
||||||
python train.py trainer.max_epochs=20 model.lr=0.0005
|
python train.py trainer.max_epochs=20 optimizer.lr=1e-4
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Train on GPU</summary>
|
<summary>Train on CPU, GPU, TPU or even with DDP and mixed precision</summary>
|
||||||
|
|
||||||
|
> *PyTorch Lightning makes it really easy to train your models on different hardware!*
|
||||||
```yaml
|
```yaml
|
||||||
|
# train on CPU
|
||||||
|
python train.py trainer.gpus=0
|
||||||
|
|
||||||
|
# train on 1 GPU
|
||||||
python train.py trainer.gpus=1
|
python train.py trainer.gpus=1
|
||||||
|
|
||||||
|
# train on TPU
|
||||||
|
python train.py trainer.tpu_cores=8
|
||||||
|
|
||||||
|
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
|
||||||
|
python train.py trainer.gpus=4 trainer.num_nodes=2 trainer.accelerator='ddp'
|
||||||
|
|
||||||
|
# train with mixed precision
|
||||||
|
python train.py trainer.amp_backend="apex" trainer.amp_level="O1" trainer.precision=16
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
@@ -186,8 +191,9 @@ python train.py trainer.gpus=1
|
|||||||
<details>
|
<details>
|
||||||
<summary>Train model with any logger available in PyTorch Lightning, like <a href="https://wandb.ai/">Weights&Biases</a></summary>
|
<summary>Train model with any logger available in PyTorch Lightning, like <a href="https://wandb.ai/">Weights&Biases</a></summary>
|
||||||
|
|
||||||
|
> *PyTorch Lightning provides convenient integrations with most popular logging frameworks. 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.*
|
||||||
```yaml
|
```yaml
|
||||||
# set project and entity names in `configs/logger/wandb.yaml`
|
# set project and entity names in `configs/logger/wandb`
|
||||||
wandb:
|
wandb:
|
||||||
project: "your_project_name"
|
project: "your_project_name"
|
||||||
entity: "your_wandb_team_name"
|
entity: "your_wandb_team_name"
|
||||||
@@ -195,8 +201,10 @@ wandb:
|
|||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# train model with Weights&Biases
|
# train model with Weights&Biases
|
||||||
|
# link to wandb dashboard should appear in the terminal
|
||||||
python train.py logger=wandb
|
python train.py logger=wandb
|
||||||
```
|
```
|
||||||
|
> *Click [here]() to see example wandb dashboard generated with this template.*
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
@@ -212,20 +220,10 @@ python train.py +experiment=exp_example_simple
|
|||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
<details>
|
|
||||||
<summary>Execute all experiments from folder</summary>
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
# execute all experiments from folder `configs/experiment/`
|
|
||||||
python train.py -m '+experiment=glob(*)'
|
|
||||||
```
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Attach some callbacks to run</summary>
|
<summary>Attach some callbacks to run</summary>
|
||||||
|
|
||||||
|
> *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).*
|
||||||
```yaml
|
```yaml
|
||||||
# callback set configurations are placed in `configs/callbacks/`
|
# callback set configurations are placed in `configs/callbacks/`
|
||||||
python train.py callbacks=default_callbacks
|
python train.py callbacks=default_callbacks
|
||||||
@@ -234,12 +232,47 @@ python train.py callbacks=default_callbacks
|
|||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Use different tricks available in Pytorch Lightning</summary>
|
||||||
|
|
||||||
|
> *PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).*
|
||||||
|
```yaml
|
||||||
|
# accumulate gradients from 10 training steps
|
||||||
|
python train.py trainer.accumulate_grad_batches=10
|
||||||
|
|
||||||
|
# gradient clipping may be enabled to avoid exploding gradients
|
||||||
|
python train.py trainer.gradient_clip_val=0.5
|
||||||
|
|
||||||
|
# stochastic weight averaging can make your models generalize better
|
||||||
|
python train.py trainer.stochastic_weight_avg=True
|
||||||
|
|
||||||
|
# run validation loop 4 times during a training epoch
|
||||||
|
python train.py trainer.val_check_interval=0.25
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Easily debug</summary>
|
<summary>Easily debug</summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# run 1 train, val and test loop, using only 1 batch
|
# run 1 train, val and test loop, using only 1 batch
|
||||||
python train.py debug=True
|
python train.py debug=true
|
||||||
|
|
||||||
|
# print full weight summary of all PyTorch modules
|
||||||
|
python train.py trainer.weights_summary="full"
|
||||||
|
|
||||||
|
# print execution time profiling after training ends
|
||||||
|
python train.py trainer.profiler="simple"
|
||||||
|
|
||||||
|
# try overfitting to 10 batches
|
||||||
|
python train.py trainer.overfit_batches=10
|
||||||
|
|
||||||
|
# use only 20% of the data
|
||||||
|
python train.py trainer.limit_train_batches=0.2 \
|
||||||
|
trainer.limit_val_batches=0.2 trainer.limit_test_batches=0.2
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
@@ -251,72 +284,77 @@ python train.py debug=True
|
|||||||
```yaml
|
```yaml
|
||||||
# checkpoint can be either path or URL
|
# checkpoint can be either path or URL
|
||||||
# path should be absolute!
|
# path should be absolute!
|
||||||
python train.py trainer.resume_from_checkpoint="/home/user/X/lightning-hydra-template/logs/runs/2021-02-28/16-50-49/checkpoints/last.ckpt"
|
python train.py trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt"
|
||||||
# currently loading ckpt in Lightning doesn't resume logger experiment, this should change when v1.3 is released...
|
|
||||||
```
|
```
|
||||||
|
> *Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.*
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Create a sweep over some hyperparameters </summary>
|
<summary>Create a sweep over hyperparameters </summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# this will run 6 experiments one after the other,
|
# this will run 6 experiments one after the other,
|
||||||
# each with different combination of batch_size and learning rate
|
# each with different combination of batch_size and learning rate
|
||||||
python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
|
python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
|
||||||
```
|
```
|
||||||
|
> *Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.*
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>Create a sweep over some hyperparameters with Optuna</summary>
|
<summary>Create a sweep over hyperparameters with Optuna</summary>
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
# this will run hyperparameter search defined in `configs/config_optuna.yaml`
|
# this will run hyperparameter search defined in `configs/config_optuna.yaml`
|
||||||
# over chosen experiment config
|
# over chosen experiment config
|
||||||
python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
|
python train.py -m --config-name config_optuna.yaml +experiment=exp_example_simple
|
||||||
```
|
```
|
||||||
|
> *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.*
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Execute all experiments from folder</summary>
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# execute all experiments from folder `configs/experiment/`
|
||||||
|
python train.py -m '+experiment=glob(*)'
|
||||||
|
```
|
||||||
|
> *Hydra provides special syntax for controlling behavior of multiruns. Read more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run).*
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Execute sweep on a remote AWS cluster</summary>
|
||||||
|
|
||||||
|
> *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.*
|
||||||
|
|
||||||
|
</details>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## Features
|
## Guide
|
||||||
- Method to pretty print configuration composed by Hydra at the start of the run, using [Rich](https://github.com/willmcgugan/rich/) library ([template_utils.py](src/utils/template_utils.py))
|
|
||||||
- Method to log chosen parts of Hydra config to all loggers ([template_utils.py](src/utils/template_utils.py))
|
### How To Start?
|
||||||
- Example of hyperparameter search with Optuna sweeps ([config_optuna.yaml](configs/config_optuna.yaml))
|
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)
|
||||||
- ~~Example of hyperparameter search with Weights&Biases sweeps~~ (TODO)
|
- Next, read this blog post: [Keeping Up with PyTorch Lightning and Hydra](https://towardsdatascience.com/keeping-up-with-pytorch-lightning-and-hydra-2nd-edition-34f88e9d5c90)
|
||||||
- Examples of simple bash scripts to check if your model doesn't crash under different training conditions ([tests/](tests/))
|
- Lastly, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) and [docs about instantiating objects with Hydra](https://hydra.cc/docs/patterns/instantiate_objects/overview)
|
||||||
- Example of inference with trained model ([inference_example.py](src/utils/inference_example.py))
|
|
||||||
- Built in requirements ([requirements.txt](requirements.txt))
|
|
||||||
- Built in conda environment initialization ([conda_env_gpu.yaml](conda_env_gpu.yaml), [conda_env_cpu.yaml](conda_env_cpu.yaml))
|
|
||||||
- Built in python package setup ([setup.py](setup.py))
|
|
||||||
- Built in pre-commit hooks for automatic code formatting ([pre-commit-config.yaml](pre-commit-config.yaml))
|
|
||||||
- Example with MNIST classification ([mnist_model.py](src/models/mnist_model.py), [mnist_datamodule.py](src/datamodules/mnist_datamodule.py))
|
|
||||||
- Optional callbacks for Weigths&Biases ([wandb_callbacks.py](src/callbacks/wandb_callbacks.py))
|
|
||||||
- To support reproducibility:
|
|
||||||
- UploadCodeToWandbAsArtifact
|
|
||||||
- UploadCheckpointsToWandbAsArtifact
|
|
||||||
- WatchModelWithWandb
|
|
||||||
- To provide examples of logging custom visualisations and metrics with callbacks:
|
|
||||||
- LogBestMetricScoresToWandb
|
|
||||||
- LogF1PrecisionRecallHeatmapToWandb
|
|
||||||
- LogConfusionMatrixToWandb
|
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
### Main Project Configuration
|
||||||
## Main Project Configuration
|
|
||||||
Location: [configs/config.yaml](configs/config.yaml)<br>
|
Location: [configs/config.yaml](configs/config.yaml)<br>
|
||||||
Main project config contains default training configuration.<br>
|
Main project config contains default training configuration.<br>
|
||||||
It determines how config is composed when simply executing command: `python train.py`
|
It determines how config is composed when simply executing command `python train.py`.<br>
|
||||||
|
It also specifies everything that shouldn't be managed by experiment configurations.
|
||||||
```yaml
|
```yaml
|
||||||
# specify here default training configuration
|
# specify here default training configuration
|
||||||
defaults:
|
defaults:
|
||||||
- trainer: default_trainer.yaml
|
- trainer: default_trainer.yaml
|
||||||
- model: mnist_model.yaml
|
- model: mnist_model.yaml
|
||||||
|
- optimizer: adam.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
@@ -367,11 +405,12 @@ hydra:
|
|||||||
```
|
```
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
### Experiment Configuration
|
||||||
## Experiment Configuration
|
|
||||||
Location: [configs/experiment](configs/experiment)<br>
|
Location: [configs/experiment](configs/experiment)<br>
|
||||||
You should store all your experiment configurations in this folder.<br>
|
You should store all your experiment configurations in this folder.<br>
|
||||||
### Simple Example
|
Experiment configurations allow you to overwrite parameters from main project configuration.
|
||||||
|
|
||||||
|
#### Simple Example
|
||||||
```yaml
|
```yaml
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=exp_example_simple
|
# python train.py +experiment=exp_example_simple
|
||||||
@@ -379,6 +418,7 @@ You should store all your experiment configurations in this folder.<br>
|
|||||||
defaults:
|
defaults:
|
||||||
- override /trainer: default_trainer.yaml
|
- override /trainer: default_trainer.yaml
|
||||||
- override /model: mnist_model.yaml
|
- override /model: mnist_model.yaml
|
||||||
|
- override /optimizer: adam.yaml
|
||||||
- override /datamodule: mnist_datamodule.yaml
|
- override /datamodule: mnist_datamodule.yaml
|
||||||
- override /callbacks: default_callbacks.yaml
|
- override /callbacks: default_callbacks.yaml
|
||||||
- override /logger: null
|
- override /logger: null
|
||||||
@@ -393,18 +433,20 @@ trainer:
|
|||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
|
|
||||||
model:
|
model:
|
||||||
lr: 0.001
|
|
||||||
lin1_size: 128
|
lin1_size: 128
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 64
|
lin3_size: 64
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
lr: 0.005
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
```
|
```
|
||||||
<br>
|
|
||||||
|
|
||||||
### Advanced Example
|
|
||||||
|
#### Advanced Example
|
||||||
```yaml
|
```yaml
|
||||||
# to execute this experiment run:
|
# to execute this experiment run:
|
||||||
# python train.py +experiment=exp_example_full
|
# python train.py +experiment=exp_example_full
|
||||||
@@ -412,6 +454,7 @@ datamodule:
|
|||||||
defaults:
|
defaults:
|
||||||
- override /trainer: null
|
- override /trainer: null
|
||||||
- override /model: null
|
- override /model: null
|
||||||
|
- override /optimizer: null
|
||||||
- override /datamodule: null
|
- override /datamodule: null
|
||||||
- override /callbacks: null
|
- override /callbacks: null
|
||||||
- override /logger: null
|
- override /logger: null
|
||||||
@@ -431,10 +474,6 @@ trainer:
|
|||||||
|
|
||||||
model:
|
model:
|
||||||
_target_: src.models.mnist_model.LitModelMNIST
|
_target_: src.models.mnist_model.LitModelMNIST
|
||||||
optimizer: adam
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00005
|
|
||||||
architecture: SimpleDenseNet
|
|
||||||
input_size: 784
|
input_size: 784
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
dropout1: 0.30
|
dropout1: 0.30
|
||||||
@@ -444,6 +483,12 @@ model:
|
|||||||
dropout3: 0.20
|
dropout3: 0.20
|
||||||
output_size: 10
|
output_size: 10
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
_target_: torch.optim.Adam
|
||||||
|
lr: 0.001
|
||||||
|
eps: 1e-08
|
||||||
|
weight_decay: 0
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
data_dir: ${data_dir}
|
data_dir: ${data_dir}
|
||||||
@@ -454,24 +499,24 @@ datamodule:
|
|||||||
|
|
||||||
logger:
|
logger:
|
||||||
wandb:
|
wandb:
|
||||||
|
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||||
|
project: "lightning-hydra-template"
|
||||||
tags: ["best_model", "uwu"]
|
tags: ["best_model", "uwu"]
|
||||||
notes: "Description of this model."
|
notes: "Description of this model."
|
||||||
```
|
```
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
### Workflow
|
||||||
## Workflow
|
|
||||||
1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example)
|
1. Write your PyTorch Lightning model (see [mnist_model.py](src/models/mnist_model.py) for example)
|
||||||
2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
|
2. Write your PyTorch Lightning datamodule (see [mnist_datamodule.py](src/datamodules/mnist_datamodule.py) for example)
|
||||||
3. Write your experiment config, containing paths to your model and datamodule (see [configs/experiment](configs/experiment) for examples)
|
3. Write your experiment config, containing paths to your model and datamodule (see [configs/experiment](configs/experiment) for examples)
|
||||||
4. Run training with chosen experiment config:<br>
|
4. Run training with chosen experiment config:<br>
|
||||||
```bash
|
```bash
|
||||||
python train.py +experiment=experiment_name.yaml
|
python train.py +experiment=experiment_name
|
||||||
```
|
```
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
### Logs
|
||||||
## Logs
|
|
||||||
Hydra creates new working directory for every executed run. <br>
|
Hydra creates new working directory for every executed run. <br>
|
||||||
By default, logs have the following structure:
|
By default, logs have the following structure:
|
||||||
```
|
```
|
||||||
@@ -503,34 +548,86 @@ By default, logs have the following structure:
|
|||||||
│ └── ...
|
│ └── ...
|
||||||
│
|
│
|
||||||
```
|
```
|
||||||
You can change this structure by modifying paths in [config.yaml](configs/config.yaml).
|
You can change this structure by modifying paths in [main project configuration](configs/config.yaml).
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
|
|
||||||
## Experiment Tracking
|
### Experiment Tracking
|
||||||
PyTorch Lightning provides built in loggers for Weights&Biases, Neptune, Comet, MLFlow, Tensorboard and CSV. To use one of them, simply add its config to [configs/logger](configs/logger) and run:
|
PyTorch Lightning supports the most popular logging frameworks:
|
||||||
|
- Weights&Biases
|
||||||
|
- Neptune
|
||||||
|
- Comet
|
||||||
|
- MLFlow
|
||||||
|
- TestTube
|
||||||
|
- Tensorboard
|
||||||
|
- CSV
|
||||||
|
|
||||||
|
These tools help you keep track of hyperparameters and output metrics and allow you to compare and visualize results. To use one of them simply complete its configuration in [configs/logger](configs/logger) and run:
|
||||||
|
```yaml
|
||||||
|
python train.py logger=logger_name
|
||||||
```
|
```
|
||||||
python train.py logger=logger_config.yaml
|
You can use many of them at once (see [configs/logger/many_loggers.yaml](configs/logger/many_loggers.yaml) for example).<br>
|
||||||
```
|
You can also write your own logger.<br>
|
||||||
You can use many of them at once (see [configs/logger/many_loggers.yaml](configs/logger/many_loggers.yaml) for example).
|
|
||||||
|
Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs [here](https://pytorch-lightning.readthedocs.io/en/latest/extensions/logging.html#automatic-logging) or take a look at [MNIST example](src/models/mnist_model.py).
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
|
|
||||||
## Tests
|
### Callbacks
|
||||||
(TODO) <br>
|
Template contains example callbacks for better Weights&Biases integration (see [wandb_callbacks.py](src/callbacks/wandb_callbacks.py)).<br>
|
||||||
|
|
||||||
|
To support reproducibility:
|
||||||
|
- UploadCodeToWandbAsArtifact
|
||||||
|
- UploadCheckpointsToWandbAsArtifact
|
||||||
|
- WatchModelWithWandb
|
||||||
|
|
||||||
|
To provide examples of logging custom visualisations with callbacks only:
|
||||||
|
- LogConfusionMatrixToWandb
|
||||||
|
- LogF1PrecisionRecallHeatmapToWandb
|
||||||
|
<br>
|
||||||
|
|
||||||
|
|
||||||
|
## Best Practices
|
||||||
|
|
||||||
|
### Miniconda
|
||||||
|
Use miniconda for your python environments. Makes it easier to install cudatoolkit for GPU and PyTorch.<br>
|
||||||
|
(I find it unnecessary to install full Anaconda environment, miniconda should be enough)<br>
|
||||||
|
Example installation:
|
||||||
|
```
|
||||||
|
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
||||||
|
bash Miniconda3-latest-Linux-x86_64.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
### Code Formating
|
||||||
|
Use pre-commit hooks to standardize code formatting of your project and save mental energy.<br>
|
||||||
|
Simply install pre-commit package with:
|
||||||
|
```yaml
|
||||||
|
pip install pre-commit
|
||||||
|
```
|
||||||
|
Next, install hooks from `.pre-commit-config.yaml`:
|
||||||
|
```
|
||||||
|
pre-commit install
|
||||||
|
```
|
||||||
|
After that your code will be automatically reformatted on every new commit.<br>
|
||||||
|
Currently `.pre-commit-config.yaml` contains configurations of **Black** (python code formatting) and **Isort** (python import sorting).
|
||||||
|
To format all files in the project use command:
|
||||||
|
```yaml
|
||||||
|
pre-commit run --all-files
|
||||||
|
```
|
||||||
|
You can exclude chosen files from automatic formatting, by modifying config (see [.pre-commit-config.yaml](pre-commit-config.yaml))
|
||||||
|
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
I find myself often 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 simple bash scripts that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. You can easily modify the commands in the script 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).<br>
|
||||||
|
Keep in mind those aren't real tests - it's simply executing commands one after the other, after which you need to take a look in terminal if some of them crashed.
|
||||||
To execute:
|
To execute:
|
||||||
```bash
|
```yaml
|
||||||
bash tests/smoke_tests.sh
|
bash tests/smoke_tests.sh
|
||||||
```
|
```
|
||||||
<br><br>
|
|
||||||
|
|
||||||
|
|
||||||
## Distributed Training
|
### Environment Variables
|
||||||
(TODO)
|
|
||||||
<br><br>
|
|
||||||
|
|
||||||
|
|
||||||
## Linting
|
|
||||||
(TODO)
|
(TODO)
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
@@ -540,18 +637,38 @@ bash tests/smoke_tests.sh
|
|||||||
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup,
|
<!-- installing miniconda, PrettyErrors and Rich exception handling, VSCode setup,
|
||||||
k-fold cross validation, linter, faster tab completion import trick,
|
k-fold cross validation, linter, faster tab completion import trick,
|
||||||
choosing metric names with '/' for wandb -->
|
choosing metric names with '/' for wandb -->
|
||||||
<br><br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## Examples Of Repositories Using This Template
|
## Other Repositories
|
||||||
|
|
||||||
|
### Inspirations
|
||||||
|
This template was inspired by:
|
||||||
|
[PyTorchLightning/deep-learninig-project-template](https://github.com/PyTorchLightning/deep-learning-project-template),
|
||||||
|
[drivendata/cookiecutter-data-science](https://github.com/drivendata/cookiecutter-data-science),
|
||||||
|
[tchaton/lightning-hydra-seed](https://github.com/tchaton/lightning-hydra-seed),
|
||||||
|
[Erlemar/pytorch_tempest](https://github.com/Erlemar/pytorch_tempest),
|
||||||
|
[ryul99/pytorch-project-template](https://github.com/ryul99/pytorch-project-template),
|
||||||
|
[lucmos/nn-template](https://github.com/lucmos/nn-template).
|
||||||
|
|
||||||
|
|
||||||
|
### Useful Repositories
|
||||||
|
- [pytorch/hydra-torch](https://github.com/pytorch/hydra-torch) - resources for configuring PyTorch classes with Hydra,
|
||||||
|
- [romesco/hydra-lightning](https://github.com/romesco/hydra-lightning) - resources for configuring PyTorch Lightning classes with Hydra
|
||||||
|
- [lucmos/nn-template](https://github.com/lucmos/nn-template) - similar template that's easier to start with but less scalable
|
||||||
|
|
||||||
|
### Examples Of Repositories Using This Template
|
||||||
(TODO)
|
(TODO)
|
||||||
<br><br>
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
<br>
|
<br>
|
||||||
|
<br>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### DELETE EVERYTHING ABOVE FOR YOUR PROJECT
|
### DELETE EVERYTHING ABOVE FOR YOUR PROJECT
|
||||||
|
|
||||||
@@ -572,7 +689,7 @@ choosing metric names with '/' for wandb -->
|
|||||||
What it does
|
What it does
|
||||||
|
|
||||||
## How to run
|
## How to run
|
||||||
First, install dependencies:
|
Install dependencies:
|
||||||
```yaml
|
```yaml
|
||||||
# clone project
|
# clone project
|
||||||
git clone https://github.com/YourGithubName/your-repo-name
|
git clone https://github.com/YourGithubName/your-repo-name
|
||||||
@@ -586,12 +703,12 @@ conda activate your_env_name
|
|||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
Next, you can train model with default configuration without logging:
|
Train model with default configuration:
|
||||||
```yaml
|
```yaml
|
||||||
python train.py
|
python train.py
|
||||||
```
|
```
|
||||||
|
|
||||||
Or you can train model with chosen logger like Weights&Biases:
|
Train model with chosen logger like Weights&Biases:
|
||||||
```yaml
|
```yaml
|
||||||
# set project and entity names in `configs/logger/wandb.yaml`
|
# set project and entity names in `configs/logger/wandb.yaml`
|
||||||
wandb:
|
wandb:
|
||||||
@@ -612,7 +729,7 @@ python train.py +experiment=exp_example_simple
|
|||||||
|
|
||||||
You can override any parameter from command line like this:
|
You can override any parameter from command line like this:
|
||||||
```yaml
|
```yaml
|
||||||
python train.py trainer.max_epochs=20 model.lr=0.0005
|
python train.py trainer.max_epochs=20 optimizer.lr=0.0005
|
||||||
```
|
```
|
||||||
|
|
||||||
To train on GPU:
|
To train on GPU:
|
||||||
|
|||||||
+4
-2
@@ -4,6 +4,7 @@
|
|||||||
defaults:
|
defaults:
|
||||||
- trainer: default_trainer.yaml
|
- trainer: default_trainer.yaml
|
||||||
- model: mnist_model.yaml
|
- model: mnist_model.yaml
|
||||||
|
- optimizer: adam.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
@@ -26,7 +27,8 @@ data_dir: ${work_dir}/data/
|
|||||||
|
|
||||||
# use `python train.py debug=true` for easy debugging!
|
# use `python train.py debug=true` for easy debugging!
|
||||||
# this will run 1 train, val and test loop with only 1 batch
|
# this will run 1 train, val and test loop with only 1 batch
|
||||||
# (equivalent to running `python train.py trainer.fast_dev_run=True`)
|
# equivalent to running `python train.py trainer.fast_dev_run=true`
|
||||||
|
# (this is placed here just for easier access from command line)
|
||||||
debug: False
|
debug: False
|
||||||
|
|
||||||
|
|
||||||
@@ -52,7 +54,7 @@ hydra:
|
|||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
|
|
||||||
job:
|
job:
|
||||||
# set your environment variables here
|
# you can set environment variables here
|
||||||
env_set:
|
env_set:
|
||||||
# currently there are some issues with running sweeps alongside wandb
|
# currently there are some issues with running sweeps alongside wandb
|
||||||
# https://github.com/wandb/client/issues/1314
|
# https://github.com/wandb/client/issues/1314
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ hydra:
|
|||||||
direction: maximize
|
direction: maximize
|
||||||
|
|
||||||
# number of experiments that will be executed
|
# number of experiments that will be executed
|
||||||
n_trials: 30
|
n_trials: 20
|
||||||
|
|
||||||
# choose optuna hyperparameter sampler ('tpe', 'random', 'cmaes' or 'nsgaii', 'motpe')
|
# choose optuna hyperparameter sampler ('tpe', 'random', 'cmaes' or 'nsgaii', 'motpe')
|
||||||
# learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html
|
# learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
|
|
||||||
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
data_dir: ${data_dir} # data_dir is specified in config.yaml
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
defaults:
|
defaults:
|
||||||
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
|
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
|
||||||
- override /model: null
|
- override /model: null
|
||||||
|
- override /optimizer: null
|
||||||
- override /datamodule: null
|
- override /datamodule: null
|
||||||
- override /callbacks: null
|
- override /callbacks: null
|
||||||
- override /logger: null
|
- override /logger: null
|
||||||
@@ -41,6 +42,11 @@ model:
|
|||||||
dropout3: 0.20
|
dropout3: 0.20
|
||||||
output_size: 10
|
output_size: 10
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
_target_: torch.optim.Adam
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
_target_: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
data_dir: ${data_dir}
|
data_dir: ${data_dir}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
defaults:
|
defaults:
|
||||||
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
|
- override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' folder or set to null
|
||||||
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder or set to null
|
- override /model: mnist_model.yaml # choose model from 'configs/model/' folder or set to null
|
||||||
|
- override /optimizer: adam.yaml # choose model from 'configs/model/' folder or set to null
|
||||||
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder or set to null
|
- override /datamodule: mnist_datamodule.yaml # choose datamodule from 'configs/datamodule/' folder or set to null
|
||||||
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder or set to null
|
- override /callbacks: default_callbacks.yaml # choose callback set from 'configs/callbacks/' folder or set to null
|
||||||
- override /logger: null # choose logger from 'configs/logger/' folder or set to null
|
- override /logger: null # choose logger from 'configs/logger/' folder or set to null
|
||||||
@@ -21,11 +22,13 @@ trainer:
|
|||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
|
|
||||||
model:
|
model:
|
||||||
lr: 0.001
|
|
||||||
lin1_size: 128
|
lin1_size: 128
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 64
|
lin3_size: 64
|
||||||
|
|
||||||
|
optimizer:
|
||||||
|
lr: 0.001
|
||||||
|
|
||||||
datamodule:
|
datamodule:
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
_target_: src.models.mnist_model.LitModelMNIST
|
_target_: src.models.mnist_model.LitModelMNIST
|
||||||
optimizer: adam
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.00005
|
|
||||||
architecture: SimpleDenseNet
|
|
||||||
input_size: 784
|
input_size: 784
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
dropout1: 0.30
|
dropout1: 0.30
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
_target_: torch.optim.Adam
|
||||||
|
# these are default parameters for Adam
|
||||||
|
lr: 0.001
|
||||||
|
eps: 1e-08
|
||||||
|
weight_decay: 0
|
||||||
|
|
||||||
|
|
||||||
|
# betas: [ 0.9, 0.999 ] # BUGGED :(
|
||||||
@@ -1,11 +1,43 @@
|
|||||||
_target_: pytorch_lightning.Trainer
|
_target_: pytorch_lightning.Trainer
|
||||||
gpus: 0 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
|
||||||
|
# set -1 to train on all GPUs available
|
||||||
|
# set 0 to train on CPU only
|
||||||
|
gpus: 0
|
||||||
|
|
||||||
min_epochs: 1
|
min_epochs: 1
|
||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
gradient_clip_val: 0.5
|
|
||||||
num_sanity_val_steps: 2
|
|
||||||
progress_bar_refresh_rate: 10
|
# all of the parameters below are set to Lightning defaults
|
||||||
weights_summary: null
|
|
||||||
default_root_dir: "lightning_logs/"
|
|
||||||
fast_dev_run: False
|
|
||||||
resume_from_checkpoint: null
|
resume_from_checkpoint: null
|
||||||
|
|
||||||
|
# tricks
|
||||||
|
gradient_clip_val: 0
|
||||||
|
accumulate_grad_batches: 1
|
||||||
|
val_check_interval: 1.0
|
||||||
|
check_val_every_n_epoch: 1
|
||||||
|
stochastic_weight_avg: False
|
||||||
|
|
||||||
|
# debug
|
||||||
|
num_sanity_val_steps: 2
|
||||||
|
fast_dev_run: False
|
||||||
|
overfit_batches: 0
|
||||||
|
limit_train_batches: 1.0
|
||||||
|
limit_val_batches: 1.0
|
||||||
|
limit_test_batches: 1.0
|
||||||
|
track_grad_norm: -1
|
||||||
|
|
||||||
|
# prints
|
||||||
|
progress_bar_refresh_rate: null
|
||||||
|
weights_summary: null
|
||||||
|
profiler: null
|
||||||
|
|
||||||
|
# others
|
||||||
|
amp_backend: "native"
|
||||||
|
amp_level: "02"
|
||||||
|
precision: 32
|
||||||
|
accelerator: null
|
||||||
|
num_nodes: 1
|
||||||
|
tpu_cores: null
|
||||||
|
deterministic: False
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
from setuptools import setup, find_packages
|
from setuptools import find_packages, setup
|
||||||
|
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="src",
|
name="src",
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ from torch import nn
|
|||||||
|
|
||||||
|
|
||||||
class SimpleDenseNet(nn.Module):
|
class SimpleDenseNet(nn.Module):
|
||||||
def __init__(self, hparams):
|
def __init__(self, hparams: dict):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.model = nn.Sequential(
|
self.model = nn.Sequential(
|
||||||
@@ -19,7 +19,6 @@ class SimpleDenseNet(nn.Module):
|
|||||||
nn.ReLU(),
|
nn.ReLU(),
|
||||||
nn.Dropout(p=hparams["dropout3"]),
|
nn.Dropout(p=hparams["dropout3"]),
|
||||||
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
|
nn.Linear(hparams["lin3_size"], hparams["output_size"]),
|
||||||
nn.LogSoftmax(dim=1),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
from pytorch_lightning import Callback
|
|
||||||
|
|
||||||
|
|
||||||
class ExampleCallback(Callback):
|
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def on_init_start(self, trainer):
|
|
||||||
print("Starting to initialize trainer!")
|
|
||||||
|
|
||||||
def on_init_end(self, trainer):
|
|
||||||
print("Trainer is initialized now.")
|
|
||||||
|
|
||||||
def on_train_end(self, trainer, pl_module):
|
|
||||||
print("Do something when training ends.")
|
|
||||||
|
|
||||||
|
|
||||||
class UnfreezeModelCallback(Callback):
|
|
||||||
"""
|
|
||||||
Unfreeze all model parameters after a few epochs.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, wait_epochs=5):
|
|
||||||
self.wait_epochs = wait_epochs
|
|
||||||
|
|
||||||
def on_epoch_end(self, trainer, pl_module):
|
|
||||||
if trainer.current_epoch == self.wait_epochs:
|
|
||||||
for param in pl_module.model.model.parameters():
|
|
||||||
param.requires_grad = True
|
|
||||||
@@ -1,17 +1,13 @@
|
|||||||
# wandb
|
|
||||||
from pytorch_lightning.loggers import WandbLogger
|
|
||||||
import wandb
|
|
||||||
|
|
||||||
# pytorch
|
|
||||||
from pytorch_lightning import Callback
|
|
||||||
import pytorch_lightning as pl
|
|
||||||
import torch
|
|
||||||
|
|
||||||
# others
|
|
||||||
from sklearn.metrics import precision_score, recall_score, f1_score
|
|
||||||
from typing import List
|
|
||||||
import glob
|
import glob
|
||||||
import os
|
import os
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
import pytorch_lightning as pl
|
||||||
|
import torch
|
||||||
|
import wandb
|
||||||
|
from pytorch_lightning import Callback
|
||||||
|
from pytorch_lightning.loggers import WandbLogger
|
||||||
|
from sklearn.metrics import f1_score, precision_score, recall_score
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
from torch.utils.data import DataLoader, ConcatDataset, random_split
|
|
||||||
from pytorch_lightning import LightningDataModule
|
from pytorch_lightning import LightningDataModule
|
||||||
from torchvision.transforms import transforms
|
from torch.utils.data import ConcatDataset, DataLoader, random_split
|
||||||
from torchvision.datasets import MNIST
|
from torchvision.datasets import MNIST
|
||||||
|
from torchvision.transforms import transforms
|
||||||
|
|
||||||
|
|
||||||
class MNISTDataModule(LightningDataModule):
|
class MNISTDataModule(LightningDataModule):
|
||||||
"""
|
"""
|
||||||
This is example of LightningDataModule for MNIST dataset.
|
Example of LightningDataModule for MNIST dataset.
|
||||||
|
|
||||||
|
A DataModule standardizes the training, val, test splits, data preparation and transforms.
|
||||||
|
The main advantage is consistent data splits, data preparation and transforms across models.
|
||||||
|
|
||||||
|
Read the docs:
|
||||||
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
https://pytorch-lightning.readthedocs.io/en/latest/datamodules.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -1,23 +1,21 @@
|
|||||||
from torch.utils.data import Dataset
|
|
||||||
from PIL import Image
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
from torch.utils.data import Dataset
|
||||||
|
|
||||||
|
|
||||||
class TestDataset(Dataset):
|
class TestDataset(Dataset):
|
||||||
"""
|
"""Example dataset class for loading images from folder."""
|
||||||
Example dataset class for loading images from folder and converting them to monochromatic.
|
|
||||||
Can be used to perform inference with trained MNIST model.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, img_dir, transform):
|
def __init__(self, dir: str, transform):
|
||||||
self.transform = transform
|
self.transform = transform
|
||||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
self.images = [os.path.join(dir, fname) for fname in os.listdir(dir)]
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||||
# image = Image.open(self.images[idx]).convert("RGB")
|
# image = Image.open(self.images[idx]).convert("RGB")
|
||||||
|
|
||||||
if self.transform is not None:
|
if self.transform:
|
||||||
image = self.transform(image)
|
image = self.transform(image)
|
||||||
|
|
||||||
return image
|
return image
|
||||||
|
|||||||
+92
-57
@@ -1,94 +1,129 @@
|
|||||||
from pytorch_lightning.metrics.classification import Accuracy
|
from typing import Any, Dict, List, Sequence, Tuple, Union
|
||||||
|
|
||||||
|
import hydra
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
|
import torch
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
import torch
|
from pytorch_lightning.metrics.classification import Accuracy
|
||||||
|
from torch.optim import Optimizer
|
||||||
|
|
||||||
# import custom architectures
|
|
||||||
from src.architectures.simple_dense_net import SimpleDenseNet
|
from src.architectures.simple_dense_net import SimpleDenseNet
|
||||||
|
|
||||||
|
|
||||||
class LitModelMNIST(pl.LightningModule):
|
class LitModelMNIST(pl.LightningModule):
|
||||||
"""
|
"""
|
||||||
This is example of LightningModule for MNIST classification.
|
Example of LightningModule for MNIST classification.
|
||||||
|
|
||||||
|
A LightningModule organizes your PyTorch code into 5 sections:
|
||||||
|
- Computations (init).
|
||||||
|
- Train loop (training_step)
|
||||||
|
- Validation loop (validation_step)
|
||||||
|
- Test loop (test_step)
|
||||||
|
- Optimizers (configure_optimizers)
|
||||||
|
|
||||||
|
Read the docs:
|
||||||
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
https://pytorch-lightning.readthedocs.io/en/latest/lightning_module.html
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
def __init__(self, *args, **kwargs):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
|
# this line ensures params passed to LightningModule will be saved to ckpt
|
||||||
|
# it also allows to access params with 'self.hparams' attribute
|
||||||
self.save_hyperparameters()
|
self.save_hyperparameters()
|
||||||
self.accuracy = Accuracy()
|
|
||||||
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
self.architecture = SimpleDenseNet(hparams=self.hparams)
|
||||||
|
|
||||||
self.train_acc_hist = []
|
# loss function
|
||||||
self.train_loss_hist = []
|
self.criterion = torch.nn.CrossEntropyLoss()
|
||||||
self.val_acc_hist = []
|
|
||||||
self.val_loss_hist = []
|
|
||||||
|
|
||||||
def forward(self, x):
|
# use separate metric instance for train, val and test step
|
||||||
|
# to ensure a proper reduction over the epoch
|
||||||
|
self.train_accuracy = Accuracy()
|
||||||
|
self.val_accuracy = Accuracy()
|
||||||
|
self.test_accuracy = Accuracy()
|
||||||
|
|
||||||
|
self.metric_hist = {
|
||||||
|
"train/acc": [],
|
||||||
|
"val/acc": [],
|
||||||
|
"train/loss": [],
|
||||||
|
"val/loss": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
def forward(self, x) -> torch.Tensor:
|
||||||
return self.architecture(x)
|
return self.architecture(x)
|
||||||
|
|
||||||
# logic for a single training step
|
def step(self, batch) -> Dict[str, torch.Tensor]:
|
||||||
def training_step(self, batch, batch_idx):
|
|
||||||
x, y = batch
|
x, y = batch
|
||||||
logits = self.forward(x)
|
logits = self.forward(x)
|
||||||
loss = F.nll_loss(logits, y)
|
loss = self.criterion(logits, y)
|
||||||
|
|
||||||
# training metrics
|
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = self.accuracy(preds, y)
|
return loss, preds, y
|
||||||
|
|
||||||
|
def training_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||||
|
loss, preds, targets = self.step(batch)
|
||||||
|
|
||||||
|
# log train metrics to your loggers!
|
||||||
|
acc = self.train_accuracy(preds, targets)
|
||||||
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
self.log("train/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||||
self.log("train/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log("train/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback or in training_epoch_end() below
|
# we can return here dict with any tensors
|
||||||
return {"loss": loss, "preds": preds, "targets": y}
|
# and then read it in some callback or in training_epoch_end() below
|
||||||
|
# remember to always return loss from training_step, or else backpropagation will fail!
|
||||||
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
# logic for a single validation step
|
def validation_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||||
def validation_step(self, batch, batch_idx):
|
loss, preds, targets = self.step(batch)
|
||||||
x, y = batch
|
|
||||||
logits = self.forward(x)
|
|
||||||
loss = F.nll_loss(logits, y)
|
|
||||||
|
|
||||||
# validation metrics
|
# log val metrics to your loggers!
|
||||||
preds = torch.argmax(logits, dim=1)
|
acc = self.val_accuracy(preds, targets)
|
||||||
acc = self.accuracy(preds, y)
|
|
||||||
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
self.log("val/loss", loss, on_step=False, on_epoch=True, prog_bar=False)
|
||||||
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log("val/acc", acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback or in validation_epoch_end() below
|
# we can return here dict with any tensors
|
||||||
return {"loss": loss, "preds": preds, "targets": y}
|
# and then read it in some callback or in validation_epoch_end() below
|
||||||
|
return {"loss": loss, "preds": preds, "targets": targets}
|
||||||
|
|
||||||
# logic for a single testing step
|
def test_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
|
||||||
def test_step(self, batch, batch_idx):
|
loss, preds, targets = self.step(batch)
|
||||||
x, y = batch
|
|
||||||
logits = self.forward(x)
|
|
||||||
loss = F.nll_loss(logits, y)
|
|
||||||
|
|
||||||
# test metrics
|
# log test metrics to your loggers!
|
||||||
preds = torch.argmax(logits, dim=1)
|
acc = self.test_accuracy(preds, targets)
|
||||||
acc = self.accuracy(preds, y)
|
|
||||||
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
self.log("test/loss", loss, on_step=False, on_epoch=True)
|
||||||
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
self.log("test/acc", acc, on_step=False, on_epoch=True)
|
||||||
|
|
||||||
return loss
|
return {"loss": loss}
|
||||||
|
|
||||||
def training_epoch_end(self, outputs):
|
# [OPTIONAL METHOD]
|
||||||
self.train_acc_hist.append(self.trainer.callback_metrics["train/acc"])
|
def training_epoch_end(self, outputs: List[Any]) -> None:
|
||||||
self.train_loss_hist.append(self.trainer.callback_metrics["train/loss"])
|
# log best so far train acc and train loss
|
||||||
self.log("train/acc_best", max(self.train_acc_hist), prog_bar=False)
|
self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
|
||||||
self.log("train/loss_best", min(self.train_loss_hist), prog_bar=False)
|
self.metric_hist["train/loss"].append(
|
||||||
|
self.trainer.callback_metrics["train/loss"]
|
||||||
def validation_epoch_end(self, outputs):
|
|
||||||
self.val_acc_hist.append(self.trainer.callback_metrics["val/acc"])
|
|
||||||
self.val_loss_hist.append(self.trainer.callback_metrics["val/loss"])
|
|
||||||
self.log("val/acc_best", max(self.val_acc_hist), prog_bar=False)
|
|
||||||
self.log("val/loss_best", min(self.val_loss_hist), prog_bar=False)
|
|
||||||
|
|
||||||
def configure_optimizers(self):
|
|
||||||
if self.hparams.optimizer == "adam":
|
|
||||||
return torch.optim.Adam(
|
|
||||||
self.parameters(),
|
|
||||||
lr=self.hparams.lr,
|
|
||||||
weight_decay=self.hparams.weight_decay,
|
|
||||||
)
|
)
|
||||||
else:
|
self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
|
||||||
raise Exception("Invalid optimizer name")
|
self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
|
||||||
|
|
||||||
|
# [OPTIONAL METHOD]
|
||||||
|
def validation_epoch_end(self, outputs: List[Any]) -> None:
|
||||||
|
# log best so far val acc and val loss
|
||||||
|
self.metric_hist["val/acc"].append(self.trainer.callback_metrics["val/acc"])
|
||||||
|
self.metric_hist["val/loss"].append(self.trainer.callback_metrics["val/loss"])
|
||||||
|
self.log("val/acc_best", max(self.metric_hist["val/acc"]), prog_bar=False)
|
||||||
|
self.log("val/loss_best", min(self.metric_hist["val/loss"]), prog_bar=False)
|
||||||
|
|
||||||
|
def configure_optimizers(
|
||||||
|
self,
|
||||||
|
) -> Union[Optimizer, Tuple[Sequence[Optimizer], Sequence[Any]]]:
|
||||||
|
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
|
||||||
|
Normally you'd need one. But in the case of GANs or similar you might have multiple.
|
||||||
|
|
||||||
|
See examples here:
|
||||||
|
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
|
||||||
|
|
||||||
|
"""
|
||||||
|
optim = hydra.utils.instantiate(
|
||||||
|
self.hparams.optimizer, params=self.parameters()
|
||||||
|
)
|
||||||
|
return optim
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
from torchvision import transforms
|
from torchvision import transforms
|
||||||
|
|
||||||
|
|
||||||
mnist_train_transforms = transforms.Compose(
|
mnist_train_transforms = transforms.Compose(
|
||||||
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
[transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))]
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
|
from PIL import Image
|
||||||
|
|
||||||
from src.models.mnist_model import LitModelMNIST
|
from src.models.mnist_model import LitModelMNIST
|
||||||
from src.transforms import mnist_transforms
|
from src.transforms import mnist_transforms
|
||||||
from PIL import Image
|
|
||||||
|
|
||||||
|
|
||||||
def predict():
|
def predict():
|
||||||
"""
|
"""Example of inference with trained model.
|
||||||
This is example of inference with a trained model.
|
It loads trained image classification model from checkpoint.
|
||||||
It Loads trained image classification model from checkpoint.
|
|
||||||
Then it loads example image and predicts its label.
|
Then it loads example image and predicts its label.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
|||||||
@@ -1,37 +1,23 @@
|
|||||||
# lightning imports
|
import logging
|
||||||
|
import warnings
|
||||||
|
from typing import List
|
||||||
|
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
|
|
||||||
# hydra imports
|
|
||||||
from omegaconf import DictConfig, OmegaConf
|
|
||||||
from hydra.utils import get_original_cwd, to_absolute_path
|
|
||||||
from hydra.utils import log
|
|
||||||
|
|
||||||
# logger imports
|
|
||||||
import wandb
|
import wandb
|
||||||
|
from hydra.utils import get_original_cwd, log, to_absolute_path
|
||||||
|
from omegaconf import DictConfig, OmegaConf
|
||||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||||
|
from rich import print
|
||||||
# from pytorch_lightning.loggers.neptune import NeptuneLogger
|
|
||||||
# from pytorch_lightning.loggers.comet import CometLogger
|
|
||||||
# from pytorch_lightning.loggers.mlflow import MLFlowLogger
|
|
||||||
# from pytorch_lightning.loggers.tensorboard import TensorBoardLogger
|
|
||||||
|
|
||||||
# rich imports
|
|
||||||
from rich.syntax import Syntax
|
from rich.syntax import Syntax
|
||||||
from rich.tree import Tree
|
from rich.tree import Tree
|
||||||
from rich import print
|
|
||||||
|
|
||||||
# normal imports
|
|
||||||
from typing import List
|
|
||||||
import warnings
|
|
||||||
import logging
|
|
||||||
|
|
||||||
|
|
||||||
def extras(config: DictConfig):
|
def extras(config: DictConfig):
|
||||||
"""A couple of optional utilities, controlled by main config file.
|
"""A couple of optional utilities, controlled by main config file.
|
||||||
- easier access to debug mode
|
|
||||||
- forcing debug friendly configuration
|
|
||||||
- disabling warnings
|
- disabling warnings
|
||||||
- disabling lightning logs
|
- disabling lightning logs
|
||||||
|
- easier access to debug mode
|
||||||
|
- forcing debug friendly configuration
|
||||||
Args:
|
Args:
|
||||||
config (DictConfig): [description]
|
config (DictConfig): [description]
|
||||||
"""
|
"""
|
||||||
|
|||||||
+8
-2
@@ -33,7 +33,13 @@ python train.py trainer.gpus=-1 trainer.max_epochs=2 \
|
|||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 4"
|
echo "TEST 4"
|
||||||
echo "Train with mixed-precision (apex, 2 epochs)"
|
echo "Train with mixed precision (apex, amp level 01, 2 epochs)"
|
||||||
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
|
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
|
||||||
+trainer.amp_backend='apex' +trainer.amp_level='O2' \
|
+trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16 \
|
||||||
|
print_config=false
|
||||||
|
|
||||||
|
echo "TEST 5"
|
||||||
|
echo "Train with mixed precision (apex, amp level 02, 2 epochs)"
|
||||||
|
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
|
||||||
|
+trainer.amp_backend="apex" +trainer.amp_level="O2" +trainer.precision=16 \
|
||||||
print_config=false
|
print_config=false
|
||||||
@@ -22,7 +22,7 @@ print_config=false
|
|||||||
|
|
||||||
echo "TEST 2"
|
echo "TEST 2"
|
||||||
echo "Overfit to 10 batches (10 epochs)"
|
echo "Overfit to 10 batches (10 epochs)"
|
||||||
python train.py +trainer.overfit_batches=10 \
|
python train.py trainer.overfit_batches=10 \
|
||||||
trainer.min_epochs=10 trainer.max_epochs=10 \
|
trainer.min_epochs=10 trainer.max_epochs=10 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
@@ -34,13 +34,13 @@ print_config=false
|
|||||||
echo "TEST 4"
|
echo "TEST 4"
|
||||||
echo "Train on 25% of data (1 epoch)"
|
echo "Train on 25% of data (1 epoch)"
|
||||||
python train.py trainer.max_epochs=1 \
|
python train.py trainer.max_epochs=1 \
|
||||||
+trainer.limit_train_batches=0.25 +trainer.limit_val_batches=0.25 +trainer.limit_test_batches=0.25 \
|
trainer.limit_train_batches=0.25 trainer.limit_val_batches=0.25 trainer.limit_test_batches=0.25 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 5"
|
echo "TEST 5"
|
||||||
echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)"
|
echo "Train on 15 train batches, 10 val batches, 5 test batches (1 epoch)"
|
||||||
python train.py trainer.max_epochs=1 \
|
python train.py trainer.max_epochs=1 \
|
||||||
+trainer.limit_train_batches=15 +trainer.limit_val_batches=10 +trainer.limit_test_batches=5 \
|
trainer.limit_train_batches=15 trainer.limit_val_batches=10 trainer.limit_test_batches=5 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 6"
|
echo "TEST 6"
|
||||||
@@ -50,18 +50,18 @@ print_config=false
|
|||||||
|
|
||||||
echo "TEST 7"
|
echo "TEST 7"
|
||||||
echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
|
echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
|
||||||
python train.py -m datamodule.batch_size=32,64 model.lr=0.001,0.003 \
|
python train.py -m datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \
|
||||||
debug=True \
|
debug=True \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 8"
|
echo "TEST 8"
|
||||||
echo "Run with gradient accumulation (1 epoch)"
|
echo "Run with gradient accumulation (1 epoch)"
|
||||||
python train.py trainer.max_epochs=1 +trainer.accumulate_grad_batches=10 \
|
python train.py trainer.max_epochs=1 trainer.accumulate_grad_batches=10 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 9"
|
echo "TEST 9"
|
||||||
echo "Run validation loop twice per epoch (2 epochs)"
|
echo "Run validation loop twice per epoch (2 epochs)"
|
||||||
python train.py trainer.max_epochs=2 +trainer.val_check_interval=0.5 \
|
python train.py trainer.max_epochs=2 trainer.val_check_interval=0.5 \
|
||||||
print_config=false
|
print_config=false
|
||||||
|
|
||||||
echo "TEST 10"
|
echo "TEST 10"
|
||||||
|
|||||||
@@ -18,10 +18,10 @@ from src.utils import template_utils as utils
|
|||||||
def train(config: DictConfig):
|
def train(config: DictConfig):
|
||||||
|
|
||||||
# A couple of optional utilities:
|
# A couple of optional utilities:
|
||||||
# - easier access to debug mode
|
|
||||||
# - forcing debug friendly configuration
|
|
||||||
# - disabling warnings
|
# - disabling warnings
|
||||||
# - disabling lightning logs
|
# - disabling lightning logs
|
||||||
|
# - easier access to debug mode
|
||||||
|
# - forcing debug friendly configuration
|
||||||
# You can safely get rid of this line if you don't want those
|
# You can safely get rid of this line if you don't want those
|
||||||
utils.extras(config)
|
utils.extras(config)
|
||||||
|
|
||||||
@@ -34,14 +34,16 @@ def train(config: DictConfig):
|
|||||||
if "seed" in config:
|
if "seed" in config:
|
||||||
seed_everything(config.seed)
|
seed_everything(config.seed)
|
||||||
|
|
||||||
# Init Lightning model ⚡
|
|
||||||
log.info(f"Instantiating model <{config.model._target_}>")
|
|
||||||
model: LightningModule = hydra.utils.instantiate(config.model)
|
|
||||||
|
|
||||||
# Init Lightning datamodule ⚡
|
# Init Lightning datamodule ⚡
|
||||||
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||||
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
|
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
|
||||||
|
|
||||||
|
# Init Lightning model ⚡
|
||||||
|
log.info(f"Instantiating model <{config.model._target_}>")
|
||||||
|
model: LightningModule = hydra.utils.instantiate(
|
||||||
|
config.model, optimizer=config.optimizer, _recursive_=False
|
||||||
|
)
|
||||||
|
|
||||||
# Init Lightning callbacks ⚡
|
# Init Lightning callbacks ⚡
|
||||||
callbacks: List[Callback] = []
|
callbacks: List[Callback] = []
|
||||||
if "callbacks" in config:
|
if "callbacks" in config:
|
||||||
|
|||||||
Reference in new issue
Block a user