Dev (#118)
* update readme * remove optimizer * make parameters more explicit * add .autoenv * update dockerfile * fix paths * update configs * update train.py * fix test
This commit is contained in:
1 parent
42f8acddd0
commit
2dcbdcdaf9
26 files changed
+246
-158
No files matched your search
@@ -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)"
|
||||
@@ -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"
|
||||
@@ -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
|
||||
+2
-1
@@ -102,7 +102,6 @@ celerybeat.pid
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
@@ -144,3 +143,5 @@ dmypy.json
|
||||
data/
|
||||
logs/
|
||||
wandb/
|
||||
.env
|
||||
.autoenv
|
||||
+4
-7
@@ -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
|
||||
@@ -71,12 +71,9 @@ RUN source activate ${CONDA_ENV_NAME} \
|
||||
&& 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
|
||||
@@ -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 .
|
||||
```
|
||||
<br>
|
||||
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).
|
||||
<br><br><br>
|
||||
|
||||
|
||||
## :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)
|
||||
<br>
|
||||
|
||||
|
||||
### 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!<br>
|
||||
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
|
||||
```
|
||||
<br>
|
||||
|
||||
|
||||
### Main Project Configuration
|
||||
Location: [configs/config.yaml](configs/config.yaml)<br>
|
||||
Main project config contains default training configuration.<br>
|
||||
@@ -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}
|
||||
@@ -648,7 +664,7 @@ You can easily remove all of those by modifying [run.py](run.py) and [src/train.
|
||||
<details>
|
||||
<summary><b>Use Docker</b></summary>
|
||||
|
||||
(TODO)
|
||||
Docker makes it easy to initialize the whole training environment, e.g. when you want to execute experiments in cloud or on some private computing cluster. You can extend Dockerfile provided in the template with your own instructions for building the container image.<br>
|
||||
|
||||
</details>
|
||||
|
||||
@@ -662,7 +678,7 @@ Example installation:
|
||||
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
||||
bash Miniconda3-latest-Linux-x86_64.sh
|
||||
```
|
||||
Docker image provided in the template already has miniconda installed.
|
||||
Docker image provided in the template already comes with initialized miniconda environment.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -689,11 +705,11 @@ pre-commit run -a
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Set environment variables in .env file</b></summary>
|
||||
<summary><b>Set private environment variables in .env file</b></summary>
|
||||
|
||||
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users.<br>
|
||||
System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.<br>
|
||||
|
||||
Template contains `.env.tmp` file. Change its name to `.env` (this name is excluded from version control in .gitignore).
|
||||
Template contains `.env.template` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore).
|
||||
You should use it for storing environment variables like this:
|
||||
```bash
|
||||
export MY_VAR=/home/user/my_system_path
|
||||
@@ -718,6 +734,50 @@ This way loggers will treat your metrics as belonging to different sections, whi
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Follow PyTorch Lightning style guide</b></summary>
|
||||
|
||||
The style guide is available [here](https://pytorch-lightning.readthedocs.io/en/latest/starter/style_guide.html).<br>
|
||||
|
||||
1. Be explicit in your init. Try to define all the relevant defaults so that the user doesn’t have to guess. Provide type hints. This way your module is reusable across projects!
|
||||
```python
|
||||
class LitModel(LightningModule):
|
||||
def __init__(self, layer_size: int = 256, lr: float = 0.001):
|
||||
```
|
||||
|
||||
2. Preserve the recommended method order.
|
||||
```python
|
||||
class LitModel(LightningModule):
|
||||
|
||||
def __init__(...):
|
||||
|
||||
def forward(...):
|
||||
|
||||
def training_step(...)
|
||||
|
||||
def training_step_end(...)
|
||||
|
||||
def training_epoch_end(...)
|
||||
|
||||
def validation_step(...)
|
||||
|
||||
def validation_step_end(...)
|
||||
|
||||
def validation_epoch_end(...)
|
||||
|
||||
def test_step(...)
|
||||
|
||||
def test_step_end(...)
|
||||
|
||||
def test_epoch_end(...)
|
||||
|
||||
def configure_optimizers(...)
|
||||
|
||||
def any_extra_hook(...)
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Version control your data and models with DVC</b></summary>
|
||||
|
||||
@@ -774,6 +834,13 @@ from project_name.pl_datamodules.mnist_datamodule import MNISTDataModule
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><b>Write tests</b></summary>
|
||||
|
||||
(TODO)
|
||||
|
||||
</details>
|
||||
|
||||
<!--
|
||||
<details>
|
||||
<summary><b>Use Miniconda</b></summary>
|
||||
@@ -788,6 +855,39 @@ bash tests/smoke_tests.sh
|
||||
|
||||
</details>
|
||||
-->
|
||||
<br>
|
||||
|
||||
|
||||
## Tricks
|
||||
<details>
|
||||
<summary><b>Automatic activation of virtual environment and tab completion</b></summary>
|
||||
|
||||
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**<br>
|
||||
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
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
<details>
|
||||
<summary><b>Accessing datamodule attributes in model</b></summary>
|
||||
@@ -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
|
||||
|
||||
+2
-1
@@ -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
|
||||
@@ -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
|
||||
@@ -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`)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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"
|
||||
@@ -24,4 +24,5 @@ scikit-learn
|
||||
pandas
|
||||
matplotlib
|
||||
seaborn
|
||||
pudb
|
||||
# dvc
|
||||
File renamed without changes.
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
)
|
||||
File renamed without changes.
+1
-3
@@ -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] = []
|
||||
|
||||
@@ -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():
|
||||
|
||||
+11
-11
@@ -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
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user