diff --git a/.autoenv.template b/.autoenv.template
new file mode 100644
index 0000000..7c87112
--- /dev/null
+++ b/.autoenv.template
@@ -0,0 +1,15 @@
+# this a template of the file that can be used to automatically execute schell commands when entering folder
+# it useful for automatic activation of conda environment and hydra tab completion
+# create a file named .autoenv
+# by default .autoenv will be excluded from version control
+# next, execute the line below to enable the automation for bash:
+# echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
+# alternatively, you can load it manually each time with:
+# source .autoenv
+
+
+# activate conda environment
+conda activate myenv
+
+# initialize hydra tab completion for bash
+eval "$(python run.py -sc install=bash)"
diff --git a/.env.template b/.env.template
new file mode 100644
index 0000000..42c9c3e
--- /dev/null
+++ b/.env.template
@@ -0,0 +1,8 @@
+# this a template of the file that can be used for storing private and user specific environment variables, like keys or system paths
+# create a file named .env
+# by default .env will be excluded from version control
+# the variables declared in .env are loaded automatically in run.py
+
+
+export MY_VAR="/home/user/my_system_path"
+export MY_KEY="asdgjhawi8y23ihsghsueity23ihwd"
diff --git a/.env.tmp b/.env.tmp
deleted file mode 100644
index 6a749a8..0000000
--- a/.env.tmp
+++ /dev/null
@@ -1,7 +0,0 @@
-# change name of this file from `.env.tmp` to `.env`
-# `.env` will be excluded from version control
-# you can store here all your system specific environment variables like this:
-
-export MY_VAR="/home/user/my_system_path"
-
-# these variables are loaded automatically in run.py
diff --git a/.gitignore b/.gitignore
index c0b5f56..9bd1899 100644
--- a/.gitignore
+++ b/.gitignore
@@ -102,7 +102,6 @@ celerybeat.pid
*.sage.py
# Environments
-.env
.venv
env/
venv/
@@ -144,3 +143,5 @@ dmypy.json
data/
logs/
wandb/
+.env
+.autoenv
diff --git a/Dockerfile b/Dockerfile
index d6a051d..2a5d5c7 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -3,7 +3,7 @@
# Build container:
# docker build -t lightning-hydra .
-# Run container:
+# Run container:
# sudo docker run --gpus all -it --rm lightning-hydra
ARG CUDA_VERSION=11.1
@@ -11,7 +11,7 @@ ARG CUDA_VERSION=11.1
# build from official cuda image, devel version is needed for apex
FROM nvidia/cuda:${CUDA_VERSION}-devel
-ENV CONDA_ENV_NAME=env
+ENV CONDA_ENV_NAME=myenv
ENV PYTHON_VERSION=3.8
ENV PYTORCH_VERSION=1.8.1
ENV CUDA_TOOLKIT_VERSION=11.1
@@ -67,16 +67,13 @@ RUN source activate ${CONDA_ENV_NAME} \
RUN source activate ${CONDA_ENV_NAME} \
&& git clone https://github.com/ashleve/lightning-hydra-template \
&& cd lightning-hydra-template \
- && pip install -r requirements.txt \
+ && pip install -r requirements.txt \
&& pre-commit install
-# Install tab completion for template
-# RUN source activate ${CONDA_ENV_NAME} \
-# && cd lightning-hydra-template \
-# && RUN_PATH=$(realpath run.py) \
-# && echo "eval \"\$(python ${RUN_PATH} -sc install=bash)\" " >> ~/.bashrc
+# Install .autoenv for automatic conda env activation and tab completion
+RUN echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
-# Set conda env to default
+# Set ${CONDA_ENV_NAME} to default virutal environment
RUN echo "source activate ${CONDA_ENV_NAME}" > ~/.bashrc
diff --git a/README.md b/README.md
index b7eed43..e42211f 100644
--- a/README.md
+++ b/README.md
@@ -30,7 +30,7 @@ This template tries to be as general as possible - you can easily delete any unw
> Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended.
-**Why you should use it:** it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most, if not the most convenient all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility.
+**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. It's also a collection of best practices for efficient workflow and reproducibility.
**Why you shouldn't use it:** Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. Also, even though Lightning is very flexible, it's not well suited for every possible deep learning task.
@@ -65,13 +65,12 @@ It makes your code neatly organized and provides lots of useful features, like a
The directory structure of new project looks like this:
```
├── configs <- Hydra configuration files
-│ ├── model <- Configurations of Lightning models
-│ ├── datamodule <- Configurations of Lightning datamodules
-│ ├── callbacks <- Configurations of Lightning callbacks
-│ ├── logger <- Configurations of Lightning loggers
-│ ├── trainer <- Configurations of Lightning trainers
-│ ├── optimizer <- Configurations of optimizers
-│ ├── experiment <- Configurations of experiments
+│ ├── callbacks <- Callbacks configs
+│ ├── datamodule <- Datamodule configs
+│ ├── experiment <- Experiment configs
+│ ├── logger <- Logger configs
+│ ├── model <- Model configs
+│ ├── trainer <- Trainer configs
│ │
│ ├── config.yaml <- Main project configuration file
│ └── config_optuna.yaml <- Configuration of Optuna hyperparameter search
@@ -80,30 +79,31 @@ The directory structure of new project looks like this:
│
├── logs <- Logs generated by Hydra and PyTorch Lightning loggers
│
-├── notebooks <- Jupyter notebooks
+├── notebooks <- Jupyter notebooks. Naming convention is a number (for ordering),
+│ the creator's initials, and a short `-` delimited description, e.g.
+│ `1.0-jqp-initial-data-exploration.ipynb`.
│
├── tests <- Tests of any kind
│
├── src
-│ ├── architectures <- PyTorch model architectures
-│ ├── datasets <- PyTorch datasets
-│ ├── pl_callbacks <- PyTorch Lightning callbacks
-│ ├── pl_datamodules <- PyTorch Lightning datamodules
-│ ├── pl_models <- PyTorch Lightning models
+│ ├── callbacks <- Lightning callbacks
+│ ├── datamodules <- Lightning datamodules
+│ ├── models <- Lightning models
│ ├── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
-│ │ └── template_utils.py <- Some extra template utilities
+│ │ └── template_utils.py <- Extra features for the template
│ │
-│ └── train.py <- Contains training pipeline
+│ └── train.py <- Training pipeline
│
-├── run.py <- Run training with chosen experiment configuration
+├── run.py <- Run training pipeline with chosen experiment configuration
│
-├── .env <- File for storing environment variables
+├── .env.template <- Template of file for storing private environment variables
+├── .autoenv.template <- Template of file for automatic virtual environment setup
├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
-├── Dockerfie <- File for building docker image
├── conda_env_gpu.yaml <- File for installing conda environment
├── requirements.txt <- File for installing python dependencies
+├── Dockerfie <- File for building docker image
├── LICENSE
└── README.md
```
@@ -117,8 +117,8 @@ git clone https://github.com/hobogalaxy/lightning-hydra-template
cd lightning-hydra-template
# [OPTIONAL] create conda environment
-conda env create -f conda_env_gpu.yaml -n testenv
-conda activate testenv
+conda env create -f conda_env_gpu.yaml -n myenv
+conda activate myenv
# install requirements
pip install -r requirements.txt
@@ -352,16 +352,41 @@ docker run --gpus all -it --rm lightning-hydra
# you can also build image by yourself using Dockerfile
docker build -t lightning-hydra .
```
-
+If you want to use some popular official image instead, I recommed the [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags), or [pytorch/pytorch](https://hub.docker.com/r/pytorch/pytorch) (this one doesn't have installed Apex for mixed precision training).
+
## :information_source: Guide
-### How To Learn?
+### How To Learn
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai)
- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [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)
+
+### How it works
+By design, every pipeline should be initialized by [run.py](run.py) file. [train.py](src/train.py) contains training pipeline.
+You can create different pipelines for different needs (e.g. for k-fold cross validation or for testing only).
+
+All PyTorch Lightning modules are dynamically instantiated from module paths specified in config, e.g. the model can be instantiated with the following line:
+```python
+model = hydra.utils.instantiate(config.model)
+```
+This allows to easily iterate over new models!
+Every time you create a new one, you only need to specify its module path and parameters in appriopriate config file:
+```yaml
+_target_: src.models.mnist_model.MNISTLitModel
+
+input_size: 784
+lin1_size: 256
+lin2_size: 256
+lin3_size: 256
+output_size: 10
+lr: 0.001
+```
+
+
+
### Main Project Configuration
Location: [configs/config.yaml](configs/config.yaml)
Main project config contains default training configuration.
@@ -375,7 +400,6 @@ It also specifies everything that shouldn't be managed by experiment configurati
defaults:
- trainer: default_trainer.yaml
- model: mnist_model.yaml
- - optimizer: adam.yaml
- datamodule: mnist_datamodule.yaml
- 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 run.py logger=wandb`)
@@ -431,7 +455,6 @@ Experiment configurations allow you to overwrite parameters from main project co
defaults:
- override /trainer: default_trainer.yaml
- override /model: mnist_model.yaml
- - override /optimizer: adam.yaml
- override /datamodule: mnist_datamodule.yaml
- override /callbacks: default_callbacks.yaml
- override /logger: null
@@ -449,8 +472,6 @@ model:
lin1_size: 128
lin2_size: 256
lin3_size: 64
-
-optimizer:
lr: 0.005
datamodule:
@@ -470,7 +491,6 @@ datamodule:
defaults:
- override /trainer: null
- override /model: null
- - override /optimizer: null
- override /datamodule: null
- override /callbacks: null
- override /logger: null
@@ -490,18 +510,14 @@ trainer:
model:
_target_: src.pl_models.mnist_model.MNISTLitModel
+ lr: 0.001
+ weight_decay: 0.00005
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 128
output_size: 10
-optimizer:
- _target_: torch.optim.Adam
- lr: 0.001
- eps: 1e-08
- weight_decay: 0.0005
-
datamodule:
_target_: src.pl_datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir}
@@ -603,7 +619,7 @@ You can run DDP on mnist example with 4 GPUs like this:
python run.py trainer.gpus=4 +trainer.accelerator="ddp"
```
⚠️ When using DDP you have to be careful how you write your models - learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html).
-
+
+
+
+## Tricks
+
+Automatic activation of virtual environment and tab completion
+
+Template contains `.autoenv.template` file, which serves as an example. Create a new file called `.autoenv` (this name is excluded from version control in .gitignore).
+You can use it to automatically execute shell commands when entering folder:
+```bash
+# activate conda environment
+conda activate myenv
+
+# initialize hydra tab completion for bash
+eval "$(python run.py -sc install=bash)"
+```
+
+To setup this automation for bash, execute the following line:
+```bash
+echo "autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; } ; cd() { builtin cd \"\$@\" ; autoenv ; } ; autoenv" >> ~/.bashrc
+```
+**Explanation**
+This line appends your `.bashrc` file with 3 commands:
+1. `autoenv() { [[ -f \"\$PWD/.autoenv\" ]] && source .autoenv ; }` - this declares the `autoenv()` function, which executes `.autoenv` file if it exists in current work dir
+2. `cd() { builtin cd \"\$@\" ; autoenv ; }` - this extends behaviour of `cd` command, to make it execute `autoenv()` function each time you change folder in terminal
+3. `autoenv` this is just to ensure the function will also be called when directly openning terminal in any folder
+
+
+
+
+
+
+
Accessing datamodule attributes in model
@@ -798,8 +898,7 @@ datamodule = hydra.utils.instantiate(config.datamodule)
model = hydra.utils.instantiate(config.model, some_param=datamodule.some_param)
```
-This is not a robust solution, since when you have many datamodules in your project, it will make them incompatible if this same parameter is not defined in each of them.
-
+This is not a robust solution, since it assumes all your datamodules have `some_param` attribute available (otherwise the run will crash).
A better solution is to add Omegaconf resolver to your datamodule:
```python
from omegaconf import OmegaConf
@@ -824,7 +923,7 @@ template_utils.print_config(config, resolve=False)
-
diff --git a/conda_env_gpu.yaml b/conda_env_gpu.yaml
index 18a45a2..4021895 100644
--- a/conda_env_gpu.yaml
+++ b/conda_env_gpu.yaml
@@ -1,4 +1,4 @@
-#name: conda_env_name
+name: myenv
channels:
- pytorch
@@ -9,6 +9,7 @@ dependencies:
- python=3.8
- pip
- notebook
+ - ipython
- cudatoolkit
- pytorch=1.8.1
- torchvision=0.9.1
diff --git a/configs/callbacks/wandb_callbacks.yaml b/configs/callbacks/wandb_callbacks.yaml
index 5e5af1a..2e7ebee 100644
--- a/configs/callbacks/wandb_callbacks.yaml
+++ b/configs/callbacks/wandb_callbacks.yaml
@@ -3,25 +3,25 @@ defaults:
watch_model_with_wandb:
- _target_: src.pl_callbacks.wandb_callbacks.WatchModelWithWandb
+ _target_: src.callbacks.wandb_callbacks.WatchModelWithWandb
log: "all"
log_freq: 100
upload_code_to_wandb_as_artifact:
- _target_: src.pl_callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact
+ _target_: src.callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact
code_dir: ${work_dir}
upload_ckpts_to_wandb_as_artifact:
- _target_: src.pl_callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
+ _target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
ckpt_dir: "checkpoints/"
upload_best_only: True
save_f1_precision_recall_heatmap_to_wandb:
- _target_: src.pl_callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb
+ _target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb
save_confusion_matrix_to_wandb:
- _target_: src.pl_callbacks.wandb_callbacks.LogConfusionMatrixToWandb
+ _target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb
diff --git a/configs/config.yaml b/configs/config.yaml
index 4a13160..2713703 100644
--- a/configs/config.yaml
+++ b/configs/config.yaml
@@ -4,7 +4,6 @@
defaults:
- trainer: default_trainer.yaml
- model: mnist_model.yaml
- - optimizer: adam.yaml
- datamodule: mnist_datamodule.yaml
- 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 run.py logger=wandb`)
diff --git a/configs/config_optuna.yaml b/configs/config_optuna.yaml
index b406f8d..2d7552b 100644
--- a/configs/config_optuna.yaml
+++ b/configs/config_optuna.yaml
@@ -41,7 +41,7 @@ hydra:
datamodule.batch_size:
type: categorical
choices: [32, 64, 128]
- optimizer.lr:
+ model.lr:
type: float
low: 0.0001
high: 0.2
diff --git a/configs/datamodule/mnist_datamodule.yaml b/configs/datamodule/mnist_datamodule.yaml
index a03e8d7..1633939 100644
--- a/configs/datamodule/mnist_datamodule.yaml
+++ b/configs/datamodule/mnist_datamodule.yaml
@@ -1,4 +1,4 @@
-_target_: src.pl_datamodules.mnist_datamodule.MNISTDataModule
+_target_: src.datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir} # data_dir is specified in config.yaml
batch_size: 64
diff --git a/configs/experiment/exp_example_full.yaml b/configs/experiment/exp_example_full.yaml
index 5ca7d9e..494b7a0 100644
--- a/configs/experiment/exp_example_full.yaml
+++ b/configs/experiment/exp_example_full.yaml
@@ -6,7 +6,6 @@
defaults:
- override /trainer: null # override trainer to null so it's not loaded from main config defaults...
- override /model: null
- - override /optimizer: null
- override /datamodule: null
- override /callbacks: null
- override /logger: null
@@ -28,8 +27,7 @@ trainer:
# resume_from_checkpoint: ${work_dir}/last.ckpt
model:
- _target_: src.pl_models.mnist_model.MNISTLitModel
- optimizer: adam
+ _target_: src.models.mnist_model.MNISTLitModel
lr: 0.001
weight_decay: 0.00005
architecture: SimpleDenseNet
@@ -39,13 +37,8 @@ model:
lin3_size: 128
output_size: 10
-optimizer:
- _target_: torch.optim.Adam
- lr: 0.001
- weight_decay: 0
-
datamodule:
- _target_: src.pl_datamodules.mnist_datamodule.MNISTDataModule
+ _target_: src.datamodules.mnist_datamodule.MNISTDataModule
data_dir: ${data_dir}
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
diff --git a/configs/experiment/exp_example_simple.yaml b/configs/experiment/exp_example_simple.yaml
index 5c86452..fa6f221 100644
--- a/configs/experiment/exp_example_simple.yaml
+++ b/configs/experiment/exp_example_simple.yaml
@@ -4,9 +4,8 @@
# python run.py +experiment=exp_example_simple
defaults:
- - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/' or set to null...
+ - override /trainer: default_trainer.yaml # choose trainer from 'configs/trainer/'
- override /model: mnist_model.yaml
- - override /optimizer: adam.yaml
- override /datamodule: mnist_datamodule.yaml
- override /callbacks: default_callbacks.yaml
- override /logger: null
@@ -25,9 +24,7 @@ model:
lin1_size: 128
lin2_size: 256
lin3_size: 64
-
-optimizer:
- lr: 0.001
+ lr: 0.002
datamodule:
batch_size: 64
diff --git a/configs/model/mnist_model.yaml b/configs/model/mnist_model.yaml
index 8df8bb3..907ae6e 100644
--- a/configs/model/mnist_model.yaml
+++ b/configs/model/mnist_model.yaml
@@ -1,7 +1,9 @@
-_target_: src.pl_models.mnist_model.MNISTLitModel
+_target_: src.models.mnist_model.MNISTLitModel
input_size: 784
lin1_size: 256
lin2_size: 256
lin3_size: 256
output_size: 10
+lr: 0.001
+weight_decay: 0.0005
diff --git a/configs/optimizer/adam.yaml b/configs/optimizer/adam.yaml
deleted file mode 100644
index 6958926..0000000
--- a/configs/optimizer/adam.yaml
+++ /dev/null
@@ -1,12 +0,0 @@
-_target_: torch.optim.Adam
-
-# these are default parameters for Adam
-lr: 0.001
-eps: 1e-08
-weight_decay: 0
-betas: [0.9, 0.999]
-
-
-# _convert_ is hydra syntax needed to make betas parameter work, learn more here:
-# https://hydra.cc/docs/next/advanced/instantiate_objects/overview/#parameter-conversion-strategies
-_convert_: "partial"
diff --git a/requirements.txt b/requirements.txt
index 1acb83c..8575f41 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -24,4 +24,5 @@ scikit-learn
pandas
matplotlib
seaborn
+pudb
# dvc
diff --git a/src/pl_callbacks/wandb_callbacks.py b/src/callbacks/wandb_callbacks.py
similarity index 99%
rename from src/pl_callbacks/wandb_callbacks.py
rename to src/callbacks/wandb_callbacks.py
index 1f5d3fd..fdb87c4 100644
--- a/src/pl_callbacks/wandb_callbacks.py
+++ b/src/callbacks/wandb_callbacks.py
@@ -36,7 +36,7 @@ class WatchModelWithWandb(Callback):
def on_train_start(self, trainer, pl_module):
logger = get_wandb_logger(trainer=trainer)
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
-
+
class UploadCodeToWandbAsArtifact(Callback):
"""Upload all *.py files to wandb as an artifact, at the beginning of the run."""
diff --git a/src/datasets/img_test_dataset.py b/src/datamodules/datasets/img_dataset.py
similarity index 79%
rename from src/datasets/img_test_dataset.py
rename to src/datamodules/datasets/img_dataset.py
index a4ba58d..82523ac 100644
--- a/src/datasets/img_test_dataset.py
+++ b/src/datamodules/datasets/img_dataset.py
@@ -1,4 +1,5 @@
import os
+from typing import Callable, Optional
from PIL import Image
from torch.utils.data import Dataset
@@ -7,11 +8,11 @@ from torch.utils.data import Dataset
class TestDataset(Dataset):
"""Example dataset class for loading images from folder."""
- def __init__(self, dir: str, transform):
+ def __init__(self, dir: str, transform: Optional[Callable] = None):
self.transform = transform
self.images = [os.path.join(dir, fname) for fname in os.listdir(dir)]
- def __getitem__(self, idx):
+ def __getitem__(self, idx: int):
image = Image.open(self.images[idx]).convert("L") # convert to black and white
# image = Image.open(self.images[idx]).convert("RGB")
diff --git a/src/pl_datamodules/mnist_datamodule.py b/src/datamodules/mnist_datamodule.py
similarity index 90%
rename from src/pl_datamodules/mnist_datamodule.py
rename to src/datamodules/mnist_datamodule.py
index 750f676..e3a969d 100644
--- a/src/pl_datamodules/mnist_datamodule.py
+++ b/src/datamodules/mnist_datamodule.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from typing import Optional, Tuple
from pytorch_lightning import LightningDataModule
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
@@ -19,18 +19,18 @@ class MNISTDataModule(LightningDataModule):
def __init__(
self,
- data_dir="data/",
- batch_size=64,
- train_val_test_split=(55_000, 5_000, 10_000),
- num_workers=0,
- pin_memory=False,
+ data_dir: str = "data/",
+ train_val_test_split: Tuple[int, int, int] = (55_000, 5_000, 10_000),
+ batch_size: int = 64,
+ num_workers: int = 0,
+ pin_memory: bool = False,
**kwargs,
):
super().__init__()
self.data_dir = data_dir
- self.batch_size = batch_size
self.train_val_test_split = train_val_test_split
+ self.batch_size = batch_size
self.num_workers = num_workers
self.pin_memory = pin_memory
@@ -51,7 +51,7 @@ class MNISTDataModule(LightningDataModule):
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
- def setup(self, stage=None):
+ def setup(self, stage: Optional[str] = None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.data_dir, train=False, transform=self.transforms)
diff --git a/src/pl_models/mnist_model.py b/src/models/mnist_model.py
similarity index 77%
rename from src/pl_models/mnist_model.py
rename to src/models/mnist_model.py
index 7c4711c..fb8c94e 100644
--- a/src/pl_models/mnist_model.py
+++ b/src/models/mnist_model.py
@@ -1,12 +1,10 @@
-from typing import Any, Dict, List, Sequence, Tuple, Union
+from typing import Any, List
-import hydra
import torch
from pytorch_lightning import LightningModule
from pytorch_lightning.metrics.classification import Accuracy
-from torch.optim import Optimizer
-from src.architectures.simple_dense_net import SimpleDenseNet
+from src.models.modules.simple_dense_net import SimpleDenseNet
class MNISTLitModel(LightningModule):
@@ -26,12 +24,13 @@ class MNISTLitModel(LightningModule):
def __init__(
self,
- optimizer,
- input_size=784,
- lin1_size=256,
- lin2_size=256,
- lin3_size=256,
- output_size=10,
+ input_size: int = 784,
+ lin1_size: int = 256,
+ lin2_size: int = 256,
+ lin3_size: int = 256,
+ output_size: int = 10,
+ lr: float = 0.001,
+ weight_decay: float = 0.0005,
**kwargs
):
super().__init__()
@@ -58,17 +57,17 @@ class MNISTLitModel(LightningModule):
"val/loss": [],
}
- def forward(self, x) -> torch.Tensor:
+ def forward(self, x):
return self.model(x)
- def step(self, batch) -> Dict[str, torch.Tensor]:
+ def step(self, batch):
x, y = batch
logits = self.forward(x)
loss = self.criterion(logits, y)
preds = torch.argmax(logits, dim=1)
return loss, preds, y
- def training_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
+ def training_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log train metrics
@@ -81,7 +80,14 @@ class MNISTLitModel(LightningModule):
# remember to always return loss from training_step, or else backpropagation will fail!
return {"loss": loss, "preds": preds, "targets": targets}
- def validation_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
+ def training_epoch_end(self, outputs: List[Any]):
+ # log best so far train acc and train loss
+ self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
+ self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"])
+ self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
+ self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False)
+
+ def validation_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log val metrics
@@ -91,7 +97,14 @@ class MNISTLitModel(LightningModule):
return {"loss": loss, "preds": preds, "targets": targets}
- def test_step(self, batch: Any, batch_idx: int) -> Dict[str, torch.Tensor]:
+ def validation_epoch_end(self, outputs: List[Any]):
+ # 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 test_step(self, batch: Any, batch_idx: int):
loss, preds, targets = self.step(batch)
# log test metrics
@@ -99,31 +112,12 @@ class MNISTLitModel(LightningModule):
self.log("test/loss", loss, on_step=False, on_epoch=True)
self.log("test/acc", acc, on_step=False, on_epoch=True)
- return loss
+ return {"loss": loss, "preds": preds, "targets": targets}
- # [OPTIONAL METHOD]
- def training_epoch_end(self, outputs: List[Any]) -> None:
- # log best so far train acc and train loss
- self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"])
- self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"])
- self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False)
- 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)
-
- # [OPTIONAL METHOD]
- def test_epoch_end(self, outputs: List[Any]) -> None:
+ def test_epoch_end(self, outputs: List[Any]):
pass
- def configure_optimizers(
- self,
- ) -> Union[Optimizer, Tuple[Sequence[Optimizer], Sequence[Any]]]:
+ def configure_optimizers(self):
"""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.
@@ -131,5 +125,6 @@ class MNISTLitModel(LightningModule):
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
+ return torch.optim.Adam(
+ params=self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay
+ )
diff --git a/src/architectures/simple_dense_net.py b/src/models/modules/simple_dense_net.py
similarity index 100%
rename from src/architectures/simple_dense_net.py
rename to src/models/modules/simple_dense_net.py
diff --git a/src/train.py b/src/train.py
index d8c9c44..dbcbadc 100644
--- a/src/train.py
+++ b/src/train.py
@@ -34,9 +34,7 @@ def train(config: DictConfig) -> Optional[float]:
# Init Lightning model
log.info(f"Instantiating model <{config.model._target_}>")
- model: LightningModule = hydra.utils.instantiate(
- config.model, optimizer=config.optimizer, _recursive_=False
- )
+ model: LightningModule = hydra.utils.instantiate(config.model)
# Init Lightning callbacks
callbacks: List[Callback] = []
diff --git a/src/utils/inference_example.py b/src/utils/inference_example.py
index 389c414..2cc3f0e 100644
--- a/src/utils/inference_example.py
+++ b/src/utils/inference_example.py
@@ -1,7 +1,7 @@
from PIL import Image
from torchvision import transforms
-from src.pl_models.mnist_model import MNISTLitModel
+from src.models.mnist_model import MNISTLitModel
def predict():
diff --git a/src/utils/template_utils.py b/src/utils/template_utils.py
index de696cf..89ec225 100644
--- a/src/utils/template_utils.py
+++ b/src/utils/template_utils.py
@@ -44,7 +44,7 @@ def extras(config: DictConfig) -> None:
config.trainer.gpus = 0
if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0
-
+
# force multi-gpu friendly configuration if
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
log.info("Forcing ddp friendly configuration! ")
diff --git a/tests/gpu_tests.sh b/tests/gpu_tests.sh
index 762059f..9c3f120 100644
--- a/tests/gpu_tests.sh
+++ b/tests/gpu_tests.sh
@@ -27,19 +27,19 @@ datamodule.num_workers=4 datamodule.pin_memory=True \
print_config=false
echo "TEST 3"
-echo "Train with 16-bit precision (1 epoch)"
-python run.py trainer.gpus=-1 trainer.max_epochs=2 \
-+trainer.precision=16 \
-print_config=false
-
-echo "TEST 4"
-echo "Train with mixed precision (apex, amp level 01, 2 epochs)"
-python run.py trainer.gpus=-1 trainer.max_epochs=2 \
+echo "Train with mixed precision (apex, amp level 01, 1 epoch)"
+python run.py trainer.gpus=-1 trainer.max_epochs=1 \
+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 run.py trainer.gpus=-1 trainer.max_epochs=2 \
+echo "TEST 4"
+echo "Train with mixed precision (apex, amp level 02, 1 epoch)"
+python run.py trainer.gpus=-1 trainer.max_epochs=1 \
+trainer.amp_backend="apex" +trainer.amp_level="O2" +trainer.precision=16 \
print_config=false
+
+echo "TEST 5"
+echo "Train with mixed precision (apex, amp level 03, 1 epoch)"
+python run.py trainer.gpus=-1 trainer.max_epochs=1 \
++trainer.amp_backend="apex" +trainer.amp_level="O3" +trainer.precision=16 \
+print_config=false
diff --git a/tests/smoke_tests.sh b/tests/smoke_tests.sh
index b8be255..39a8a0a 100644
--- a/tests/smoke_tests.sh
+++ b/tests/smoke_tests.sh
@@ -50,7 +50,7 @@ print_config=false
echo "TEST 7"
echo "Run default hydra sweep (executes 4 different combinations in debug mode)"
-python run.py -m trainer=debug_trainer datamodule.batch_size=32,64 optimizer.lr=0.001,0.003 \
+python run.py -m trainer=debug_trainer datamodule.batch_size=32,64 model.lr=0.001,0.003 \
debug=True \
print_config=false
diff --git a/tests/sweep_tests.sh b/tests/sweep_tests.sh
index 18a7fe0..9ef3cd9 100644
--- a/tests/sweep_tests.sh
+++ b/tests/sweep_tests.sh
@@ -19,7 +19,7 @@ echo "TEST 1"
echo "Default hydra sweep with wandb logging"
python run.py -m \
+experiment=exp_example_simple \
-datamodule.batch_size=64,128 optimizer.lr=0.001,0.003 \
+datamodule.batch_size=64,128 model.lr=0.001,0.003 \
trainer.gpus=-1 trainer.max_epochs=2 \
datamodule.num_workers=12 datamodule.pin_memory=True \
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"