Merge pull request #40 from kinoai/dev

Dev
This commit is contained in:
hobogalaxy authored and GitHub committed 2020-12-05 03:04:31 +01:00
commit 9fca0eebd1
11 files changed
+136 -166

No files matched your search

+41 -38
View File
@@ -3,15 +3,16 @@ A convenient starting template for most deep learning projects. Built with <b>Py
Click on <b>"Use this template"</b> button above to initialize new repository.<br>
## Features
- All advantages of Pytorch Lightning
- All advantages of PyTorch Lightning
- Predefined folder structure
- Storing project configuration in a convenient way ([project_config.yaml](project/project_config.yaml))
- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml))
- Automates the whole training process and initialization, you only need to create `model` and `datamodule` classes and specify them in [run_configs.yaml](project/run_configs.yaml)
- Automates the whole training process and initialization, you only need to create `model` and `datamodule` and specify them in [run_configs.yaml](project/run_configs.yaml)
- Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/utils/execute_sweep.py))
- Built in requirements ([requirements.txt](requirements.txt))
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
- Built in package setup ([setup.py](setup.py))
- Example with MNIST digits classification
- Useful example callbacks ([callbacks.py](project/utils/callbacks.py))
<br>
@@ -55,7 +56,7 @@ The directory structure of new project looks like this:
├── .gitignore
├── LICENSE
├── README.md
├── SETUP.md
├── setup.py
├── conda_env.yaml
└── requirements.txt
```
@@ -63,6 +64,7 @@ The directory structure of new project looks like this:
## Project config parameters ([project_config.yaml](project/project_config.yaml))
Example project configuration:
```yaml
num_of_gpus: -1 <- '-1' to use all gpus available, '0' to train on cpu
@@ -81,7 +83,7 @@ callbacks:
mode: "max" <- can be "max" or "min"
early_stop:
monitor: "val_acc" <- name of the logged metric that determines when model is improving
patience: 100 <- how many epochs of not improving until training stops
patience: 5 <- how many epochs of not improving until training stops
mode: "max" <- can be "max" or "min"
printing:
@@ -128,27 +130,13 @@ MNIST_CLASSIFIER_V1:
## Workflow
1. Add your model to `project/models` folder.<br>
You need to create folder with `lightning_module.py` file containing `LitModel` class
2. Add your datamodule to `project/data_modules` folder.<br>
You need to create folder with `datamodule.py` file containing `DataModule` class
3. Add your run config to [run_configs.yaml](project/run_configs.yaml) (specify there folders containing your model and datamodule)
1. Add your model to `project/models` folder. You need to create folder with `lightning_module.py` file containing `LitModel` class
2. Add your datamodule to `project/data_modules` folder. You need to create folder with `datamodule.py` file containing `DataModule` class
3. Create new run config in [run_configs.yaml](project/run_configs.yaml) (specify there folders containing your model and datamodule)
3. Configure [project_config.yaml](project/project_config.yaml)
4. Run training:<br>
Either pass run config name as an argument
```
python train.py -r MNIST_CLASSIFIER_V1
python train.py --run_conf_name MNIST_CLASSIFIER_V1
```
Or modify default run config name in [train.py](project/train.py)
```python
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-r", "--run_conf_name", type=str, default="MNIST_CLASSIFIER_V1")
parser.add_argument("-u", "--use_wandb", type=bool, default=True)
args = parser.parse_args()
main(run_config_name=args.run_conf_name, use_wandb=args.use_wandb)
4. Run training<br>
```bash
python train.py --use_wandb=True --run_config MNIST_CLASSIFIER_V1
```
<br><br>
@@ -178,38 +166,53 @@ First, install dependencies
git clone https://github.com/YourGithubName/your-repo-name
cd your-repo-name
# create conda environment
# optionally create conda environment
conda update conda
conda env create -f conda_env.yaml -n your_env_name
conda activate your_env_name
# optionally install project with setup.py
pip install -e .
# install requirements
pip install -r requirements.txt
```
Next, you can train model without data logging
Next, you can train model without logging
```bash
# train model with chosen run configuration
# train model without Weights&Biases
# choose run config from project/run_configs.yaml
cd project
python train.py --use_wandb=False --run_conf_name MNIST_CLASSIFIER_V1
python train.py --use_wandb=False --run_config MNIST_CLASSIFIER_V1
```
Or you can train model with Weights&Biases data logging
Or you can train model with Weights&Biases logging
```yaml
# set project and enity names in project/project_config.yaml
loggers:
wandb:
project: "your_project_name"
entity: "your_wandb_user_or_team_name"
entity: "your_wandb_username_or_team"
```
```bash
# log to your wandb account
wandb login
```
```bash
# train model with chosen run configuration
# train model with Weights&Biases
# choose run config from project/run_configs.yaml
cd project
python train.py --use_wandb=True --run_conf_name MNIST_CLASSIFIER_V1
python train.py --use_wandb=True --run_config MNIST_CLASSIFIER_V1
```
All run configurations are located in [run_configs.yaml](project/run_configs.yaml).
For PyCharm setup read [SETUP.md](SETUP.md).
<br>
#### PyCharm setup
- open this repository as PyCharm project
- set project interpreter:<br>
`Ctrl + Shift + A -> type "Project Interpreter"`
- mark folder "project" as sources root:<br>
`right click on directory -> "Mark Directory as" -> "Sources Root"`
- set terminal emulation:<br>
`Ctrl + Shift + A -> type "Edit Configurations..." -> select "Emulate terminal in output console"`
- run training:<br>
`right click on train.py file -> "Run 'train'"`
#### VS Code setup
- TODO
-61
View File
@@ -1,61 +0,0 @@
## Setup
1. Install anaconda if you don't already have it
https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html
2. Clone repo
```
git clone https://github.com/kinoai/hackathon-template
cd hackathon-template
```
3. Create conda environment (change 'hack_env' to any name you want)
```
conda update conda
conda env create -f conda_env.yaml -n hack_env
conda activate hack_env
```
4. Make sure proper python PATH is loaded<br>
- Unix
```
which python
```
- Windows
```
for %i in (python.exe) do @echo. %~$PATH:i
```
Expected result: `PATH_TO_CONDA/envs/ENV_NAME/bin/python`
5. Install requirements
```
pip install -r requirements.txt
```
6. Log to your Weights&Biases account
```
wandb login
```
7. Run training
```
cd project
python train.py
```
<br>
#### Important notes!
- If you're using CUDA compatible GPU make sure your drivers are updated!
- If you are not using GPU (CUDA incompatible GPU) you may need to specify the number of GPUs manually instead of leaving the default `-1` in `project_config.yaml`:
```
num_of_gpus: 0
```
<br>
## PyCharm setup
- open this repository as PyCharm project
- set "hack_env" as project interpreter:<br>
`Ctrl + Shift + A -> type "Project Interpreter"`
- mark folder "project" as sources root:<br>
`right click on directory -> "Mark Directory as" -> "Sources Root"`
- set terminal emulation:<br>
`Ctrl + Shift + A -> type "Edit Configurations..." -> select "Emulate terminal in output console"`
- run training:<br>
`right click on train.py file -> "Run 'train'"`
+1 -2
View File
@@ -1,4 +1,4 @@
#name: hack_env
#name: conda_env_name
channels:
- pytorch
- conda-forge
@@ -10,4 +10,3 @@ dependencies:
- pytorch
- torchvision
- torchaudio
- jupyter
@@ -6,7 +6,7 @@ import os
class TestDataset(Dataset):
"""
Example dataset class for loading images from folder.
'Dataset' classes can be used by 'DataModule' classes.
'Dataset' classes can be used by 'DataModule' class.
"""
def __init__(self, img_dir, transform):
+4 -3
View File
@@ -1,10 +1,7 @@
MNIST_CLASSIFIER_V1:
trainer:
min_epochs: 1
max_epochs: 5
gradient_clip_val: 0.5
accumulate_grad_batches: 1
limit_train_batches: 1.0
model:
model_folder: "simple_mnist_classifier"
lr: 0.001
@@ -28,7 +25,11 @@ MNIST_CLASSIFIER_V2:
max_epochs: 10
gradient_clip_val: 0.5
accumulate_grad_batches: 2
fast_dev_run: False
limit_train_batches: 1.0
limit_val_batches: 1.0
limit_test_batches: 1.0
val_check_interval: 1.0
model:
model_folder: "simple_mnist_classifier"
lr: 0.002
+25 -21
View File
@@ -2,7 +2,9 @@ from pytorch_lightning.profiler import SimpleProfiler
from pytorch_lightning.loggers import WandbLogger
from argparse import ArgumentParser
import pytorch_lightning as pl
from typing import List
import yaml
import os
# utils
from utils.init_utils import init_lit_model, init_data_module, init_main_callbacks, init_wandb_logger
@@ -17,11 +19,16 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
# Init Weights&Biases logger
logger: pl.loggers.WandbLogger = init_wandb_logger(project_config, run_config, lit_model, datamodule) \
if use_wandb else None
logger: pl.loggers.WandbLogger = init_wandb_logger(
project_config=project_config,
run_config=run_config,
lit_model=lit_model,
datamodule=datamodule,
log_path=os.path.join(os.path.dirname(__file__), "logs/")
) if use_wandb else None
# Init ModelCheckpoint and EarlyStopping callbacks
callbacks: list = init_main_callbacks(project_config)
callbacks: List[pl.Callback] = init_main_callbacks(project_config=project_config)
# Add custom callbacks from utils/callbacks.py
callbacks.extend([
@@ -30,10 +37,14 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
])
if use_wandb:
callbacks.append(
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model, datamodule=datamodule),
SaveCodeToWandbCallback(
base_dir=os.path.dirname(__file__),
wandb_save_dir=logger.save_dir,
run_config=run_config
),
)
# Get path to checkpoint you want to resume with if it was set in run config
# Get path to checkpoint you want to resume with if it was set in the run config
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
# Init PyTorch Lightning trainer ⚡
@@ -59,22 +70,14 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
weights_summary=project_config["printing"]["weights_summary"],
# run related
max_epochs=run_config["trainer"]["max_epochs"],
min_epochs=run_config["trainer"].get("min_epochs", 1),
accumulate_grad_batches=run_config["trainer"].get("accumulate_grad_batches", 1),
gradient_clip_val=run_config["trainer"].get("gradient_clip_val", 0.5),
# these are mostly for debugging
fast_dev_run=run_config["trainer"].get("fast_dev_run", False),
limit_train_batches=run_config["trainer"].get("limit_train_batches", 1.0),
limit_val_batches=run_config["trainer"].get("limit_val_batches", 1.0),
limit_test_batches=run_config["trainer"].get("limit_test_batches", 1.0),
val_check_interval=run_config["trainer"].get("val_check_interval", 1.0),
num_sanity_val_steps=run_config["trainer"].get("fast_dev_run", 3),
# number of validation sanity checks
num_sanity_val_steps=3,
# default log dir if no logger is found
default_root_dir="logs/lightning_logs",
# insert all other trainer parameters specified in run config
**run_config["trainer"]
)
# Evaluate model on test set before training
@@ -87,7 +90,8 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
trainer.test()
def load_config(path):
def load_config(filename):
path = os.path.join(os.path.dirname(__file__), filename)
with open(path, "r") as ymlfile:
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
return config
@@ -104,8 +108,8 @@ def main(run_config_name: str, use_wandb: bool):
if __name__ == "__main__":
parser = ArgumentParser()
parser.add_argument("-r", "--run_conf_name", type=str, default="MNIST_CLASSIFIER_V1")
parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V1")
parser.add_argument("-u", "--use_wandb", type=bool, default=True)
args = parser.parse_args()
main(run_config_name=args.run_conf_name, use_wandb=args.use_wandb)
main(run_config_name=args.run_config, use_wandb=args.use_wandb)
+24 -19
View File
@@ -26,11 +26,11 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
Save model in .onnx format and upload to wandb.
Might crash since not all models are compatible with onnx.
"""
def __init__(self, datamodule, save_dir):
def __init__(self, datamodule, wandb_save_dir):
first_batch = next(iter(datamodule.train_dataloader()))
x, y = first_batch
self.dummy_input = x
self.save_dir = save_dir
self.wandb_save_dir = wandb_save_dir
def on_sanity_check_end(self, trainer, pl_module):
self.save_onnx_model(pl_module)
@@ -39,9 +39,9 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
self.save_onnx_model(pl_module)
def save_onnx_model(self, pl_module):
file_path = os.path.join(self.save_dir, "model.onnx")
file_path = os.path.join(self.wandb_save_dir, "model.onnx")
pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
wandb.save(file_path, base_path=self.save_dir)
wandb.save(file_path, base_path=self.wandb_save_dir)
class ImagePredictionLoggerCallback(pl.Callback):
@@ -131,52 +131,57 @@ class SaveCodeToWandbCallback(pl.Callback):
"""
Upload specified code files to wandb at the beginning of the run.
"""
def __init__(self, wandb_save_dir, lit_model, datamodule):
def __init__(self, base_dir, wandb_save_dir, run_config):
self.base_dir = base_dir
self.wandb_save_dir = wandb_save_dir
self.additional_files_to_be_saved = [
self.model_folder = run_config["model"]["model_folder"]
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
"utils/callbacks.py",
"utils/init_utils.py",
"train.py",
"project_config.yaml",
"run_configs.yaml",
]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
self.datamodule_path = os.path.dirname(inspect.getfile(datamodule.__class__))
def on_sanity_check_end(self, trainer, pl_module):
"""Upload files when all validation sanity checks end."""
# upload additional files
for file in self.additional_files_to_be_saved:
src_path = os.path.join(self.base_dir, file)
dst_path = os.path.join(self.wandb_save_dir, "code", file)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
copy(file, dst_path)
copy(src_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
for filename in os.listdir(self.model_path):
# upload model files
for filename in os.listdir(os.path.join(self.base_dir, "models", self.model_folder)):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path),
filename)
src_path = os.path.join(self.base_dir, "models", self.model_folder, filename)
dst_path = os.path.join(self.wandb_save_dir, "code", "models", self.model_folder, filename)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
file_path = os.path.join(self.model_path, filename)
copy(file_path, dst_path)
copy(src_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
for filename in os.listdir(self.datamodule_path):
# upload datamodule files
for filename in os.listdir(os.path.join(self.base_dir, "data_modules", self.datamodule_folder)):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", os.path.basename(
self.datamodule_path), filename)
src_path = os.path.join(self.base_dir, "data_modules", self.datamodule_folder, filename)
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", self.datamodule_folder, filename)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
file_path = os.path.join(self.datamodule_path, filename)
copy(file_path, dst_path)
copy(src_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
+3 -3
View File
@@ -8,8 +8,8 @@ import train
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1"
# Load configs
project_config = train.load_config("../project_config.yaml")
run_config = train.load_config("../run_configs.yaml")[RUN_CONFIG_NAME]
project_config = train.load_config("project_config.yaml")
run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
# Initialize wandb
wandb.init()
@@ -27,4 +27,4 @@ for key, value in sweep_hparams.items():
run_config["dataset"][key] = value
# Execute run
train.train(project_config=project_config, run_config=run_config)
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
+20 -16
View File
@@ -1,6 +1,7 @@
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning.loggers import WandbLogger
import pytorch_lightning as pl
from typing import List
import importlib
import os
@@ -21,36 +22,39 @@ def init_data_module(hparams: dict) -> pl.LightningDataModule:
return datamodule
def init_main_callbacks(project_config: dict) -> list:
"""Initialize EarlyStopping callback and ModelCheckpoint callback."""
def init_main_callbacks(project_config: dict) -> List[pl.Callback]:
"""Initialize ModelCheckpoint and EarlyStopping callbacks."""
callbacks = [
EarlyStopping(
monitor=project_config["callbacks"]["early_stop"]["monitor"],
patience=project_config["callbacks"]["early_stop"]["patience"],
mode=project_config["callbacks"]["early_stop"]["mode"],
),
ModelCheckpoint(
monitor=project_config["callbacks"]["checkpoint"]["monitor"],
save_top_k=project_config["callbacks"]["checkpoint"]["save_top_k"],
mode=project_config["callbacks"]["checkpoint"]["mode"],
save_last=project_config["callbacks"]["checkpoint"]["save_last"],
),
EarlyStopping(
monitor=project_config["callbacks"]["early_stop"]["monitor"],
patience=project_config["callbacks"]["early_stop"]["patience"],
mode=project_config["callbacks"]["early_stop"]["mode"],
)
]
return callbacks
def init_wandb_logger(
config: dict, run_config: dict,
lit_model: pl.LightningModule, datamodule: pl.LightningDataModule
project_config: dict,
run_config: dict,
lit_model: pl.LightningModule,
datamodule: pl.LightningDataModule,
log_path: str = "logs/"
) -> pl.loggers.WandbLogger:
"""Initialize Weights&Biases logger."""
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
wandb_logger = WandbLogger(
project=config["loggers"]["wandb"]["project"],
entity=config["loggers"]["wandb"]["entity"],
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
project=project_config["loggers"]["wandb"]["project"],
entity=project_config["loggers"]["wandb"]["entity"],
log_model=project_config["loggers"]["wandb"]["log_model"],
offline=project_config["loggers"]["wandb"]["offline"],
group=run_config.get("wandb", {}).get("group", None),
job_type=run_config.get("wandb", {}).get("job_type", "train"),
@@ -63,11 +67,11 @@ def init_wandb_logger(
and resume_from_checkpoint is not False and wandb_run_id is not False
else None,
save_dir="logs/",
save_dir=log_path,
save_code=False
)
if not os.path.exists("logs/"):
os.mkdir("logs/")
if not os.path.exists(log_path):
os.makedirs(log_path)
if hasattr(lit_model, 'model'):
wandb_logger.watch(lit_model.model, log=None)
else:
+3 -2
View File
@@ -1,6 +1,7 @@
torch>=1.7.0
torchvision>=0.8.1
torchaudio>=0.7.0
pytorch-lightning>=1.0.8
pytorch-lightning-bolts>=0.2.5
wandb>=0.10.11
wandb>=0.10.12
PyYAML>=5.3.1
scikit-learn>=0.23.2
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='project',
version='0.0.0',
description='Describe Your Cool Project',
author='',
author_email='',
url='https://github.com/kinoai/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
install_requires=['pytorch-lightning', 'PyYAML'],
packages=find_packages(),
)