Merge pull request #31 from kinoai/new-project-structure

New project structure
This commit is contained in:
hobogalaxy authored and GitHub committed 2020-11-24 19:15:06 +01:00
commit f775c15586
23 files changed
+621 -361

No files matched your search

+84 -129
View File
@@ -1,6 +1,12 @@
# Hackathon template # Hackathon template
A convenient starting template for most deep learning projects. Built with PyTorch Lightning and Weights&Biases (wandb). A convenient starting template for most deep learning projects. Built with PyTorch Lightning and Weights&Biases.
<br>
<br>
## Setup
Read [SETUP.md](SETUP.md)
<br>
<br>
## Project structure ## Project structure
The directory structure of new project looks like this: The directory structure of new project looks like this:
@@ -8,167 +14,116 @@ The directory structure of new project looks like this:
├── project ├── project
│ ├── data <- Data from third party sources │ ├── data <- Data from third party sources
│ │ │ │
│ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning during training
│ │
│ ├── docs <- Useful pdf files │ ├── docs <- Useful pdf files
│ │ │ │
│ ├── hack_utils <- Any extra scripts not belonging to training pipeline │ ├── hack_utils <- Any extra scripts not belonging to training pipeline
│ │ │ │
│ ├── notebooks <- Jupyter notebooks │ ├── notebooks <- Jupyter notebooks
│ │ │ │
│ ├── training_modules <- All modules useful for training deep learning models │ ├── lightning_modules <- PyTorch Lightning related modules
│ │ ├── callbacks.py <- Useful training callbacks │ │ ├── data_modules <- Data related modules
│ │ ├── datasets.py <- PyTorch "Dataset" modules │ │ │ ├── datamodules.py <- "LightningDataModule" modules (wrappers for PyTorch "Dataset")
│ │ ├── datamodules.py <- "LightningDataModule" modules (wrappers for PyTorch "Dataset") │ │ │ ├── datasets.py <- PyTorch "Dataset" modules
│ │ ├── lightning_wrapper.py <- Contains train/val/test step methods executed during training │ │ │ └── transforms.py <- Data transformations (data preprocessing)
│ │ ├── loggers.py <- Initializers for different loggers (wandb, tensorboard, etc.) │ │ │
│ │ ├── models.py <- Neural networks declarations │ │ ├── callbacks.py <- Training callbacks
│ │ └── transforms.py <- Data transformations (data preprocessing) │ │ └── init_utils.py <- Some useful initializers
│ │
│ ├── models <- All your models should be located here
│ │ ├── simple_mnist_classifier <- Example model folder name
│ │ │ ├── lightning_module.py <- Contains train/val/test step methods executed during training
│ │ │ ├── models.py <- Neural networks declarations
│ │ │ ├── predict.py <- Predicting from trained model
│ │ │ └── __init__.py
│ │ │
│ │ ├── ...
│ │ └── ...
│ │ │ │
│ ├── config.yaml <- Training configuration │ ├── config.yaml <- Training configuration
│ ├── execute_sweep.py <- Special file for executing wandb sweeps (hyperparameter search) │ ├── execute_sweep.py <- Special file for executing wandb sweeps (hyperparameter search)
│ ├── predict.py <- Make predictions with trained model
│ └── train.py <- Train model │ └── train.py <- Train model
│ │
├── .gitignore ├── .gitignore
├── LICENSE ├── LICENSE
├── README.md ├── README.md
├── SETUP.md
├── TIPS.md
└── requirements.txt └── requirements.txt
``` ```
<br>
## Setup
#### 1. Install anaconda
https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html
#### 2. Create anaconda env
```
conda create --name hack_env
conda activate hack_env
```
#### 3. Make sure proper python PATH is loaded
Unix
```
which python
```
Windows
```
for %i in (python.exe) do @echo. %~$PATH:i
```
Expected result: `PATH_TO_CONDA/envs/ENV_NAME/bin/python`
#### 4. Install pytorch with conda
Installation command generator: https://pytorch.org/get-started/locally/
```
conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch
```
#### 5. Clone repo
```
git clone https://github.com/kinoai/hackathon-template
```
#### 6. Install requirements with pip
```
cd hackathon-template
pip install -r requirements.txt
```
#### 7. Log into your wandb account
```
wandb login
```
#### 8. 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'"`
#### Important notes!
- 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 `config.yaml`:
```
num_of_gpus: 0
```
<br> <br>
## Config parameters
## [config.yaml](project/config.yaml) parameters explanation: #### [config.yaml](project/config.yaml):
```yaml ```yaml
num_of_gpus: -1 <- -1 means use all gpus available on your machine, 0 means train on cpu num_of_gpus: -1
hparams: <- you can add any parameters here and then acces them in your network model or datamodule, those parameters are always saved to wandb config model_configs:
max_epochs: 3 simple_mnist_classifier_v1:
batch_size: 64 model_folder_name: "simple_mnist_classifier"
lr: 0.001 max_epochs: 3
weight_decay: 0.000001 <- L2 normalization set in optimizer lr: 0.001
gradient_clip_val: 0.5 <- gradient clipping value (0 means don’t clip), helps with exploding gradient issues batch_size: 64
accumulate_grad_batches: 1 <- perform optimisation after accumulating gradient from n batches weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
input_size: 784
output_size: 10
lin1_size: 256
lin2_size: 256
lin3_size: 128
dataset:
class_name: "MNISTDataModule"
train_transforms: "minst_train_preprocess"
test_transforms: "minst_test_preprocess"
train_val_split_ratio: 0.8
num_workers: 1
pin_memory: False
resume: transfer_learning_cifar10_classifier_v1:
resume_from_ckpt: False <- set to True if you want to resume ...
wandb_run_id: "8uuomodb" <- id of wandb run you want to resume
ckpt_path: "epoch=2.ckpt" <- lightning checkpoint path transfer_learning_cifar10_classifier_v2:
...
resume_training:
lightning_ckpt:
resume_from_ckpt: False
ckpt_path: "logs/checkpoints/epoch=2.ckpt"
wandb:
resume_wandb_run: False
wandb_run_id: "8uuomodb"
loggers: loggers:
wandb: wandb:
project: "hackathon_template_test" <- wandb project name project: "hackathon_template_test"
team: "kino" <- entity name (your username or team name you belong to) team: "kino"
group: None group: None
job_type: "train" job_type: "train"
tags: [] tags: []
log_model: True <- True if you want to automatically upload your model to wandb at the end of training log_model: True
offline: False <- True if you don't want to send any data to wandb server offline: False
callbacks: callbacks:
checkpoint: checkpoint:
monitor: "val_acc" <- name of the logged metric that determines when ckpt is saved monitor: "val_acc"
save_top_k: 1 <- save k best models (determined by above metric) save_top_k: 1
save_last: True <- additionaly always save model from last epoch save_last: True
mode: "max" <- determine whether improving means minimizing or maximizing metrics score (alternatively "min") mode: "max"
early_stop: early_stop:
monitor: "val_acc" <- name of the logged metric that determines when training is stopped monitor: "val_acc"
patience: 100 <- for how long metric needs to not improve in order to stop training patience: 100
mode: "max" <- determine whether improving means minimizing or maximizing metrics score (alternatively "min") mode: "max"
printing: printing:
progress_bar_refresh_rate: 5 <- refresh rate of training bar in terminal progress_bar_refresh_rate: 5
weights_summary: "top" <- print summary of model an the beginning of the run (alternatively "full") weights_summary: "top"
profiler: False <- True will print mean execution time of all methods at the end of the training profiler: False
``` ```
<br> <br>
<br>
## Tips
## Useful tips Read [TIPS.md](TIPS.md)
- PyTorch Lightning Bolts is official collection of prebuilt models across many research domains:
- https://pytorch-lightning.readthedocs.io/en/latest/bolts.html
- https://github.com/PyTorchLightning/pytorch-lightning-bolts
- Pre-trained pytorch model repository designed for research exploration:
- https://pytorch.org/hub/
- List of all tools in PyTorch ecosystem:
- https://pytorch.org/ecosystem/
- Additional pl.Trainer() parameters which can be useful:
- <b>accumulate_grad_batches=5</b> - perform optimisation after accumulating gradient from 5 batches
- <b>accumulate_grad_batches={5: 3, 10: 20}</b> - no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
- <b>auto_scale_batch_size='power'</b> - automatically find the largest batch size that fits into memory and is power of 2 (requires calling trainer.tune(model, datamodule))
- <b>check_val_every_n_epoch=10</b> - run validation loop every 10 training epochs
- <b>val_check_interval=0.25</b> - check validation set 4 times during a training epoch
- <b>fast_dev_run=True</b> - runs 1 train, val, test batch and program ends (great for debugging)
- <b>min_epochs=1</b> - force training for at least these many epochs
- <b>overfit_batches=0.01</b> - use only 1% of the train set (and use the train set for val and test)
- <b>overfit_batches=10</b> - use only 10 batches of the train set (and use the train set for val and test)
- <b>limit_train_batches=0.25</b> - run through only 25% of the training set each epoch
- <b>limit_val_batches=0.25</b>
- <b>limit_test_batches=0.25</b>
- <b>precision=16</b> - set tensor precision (default is 32 bits)
- <b>amp_backend='apex'</b> - apex backend for mixed precision training https://github.com/NVIDIA/apex
+62
View File
@@ -0,0 +1,62 @@
## Setup
#### 1. Install anaconda
https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html
#### 2. Create anaconda env
```
conda create --name hack_env
conda activate hack_env
```
#### 3. Make sure proper python PATH is loaded
Unix
```
which python
```
Windows
```
for %i in (python.exe) do @echo. %~$PATH:i
```
Expected result: `PATH_TO_CONDA/envs/ENV_NAME/bin/python`
#### 4. Install pytorch with conda
Installation command generator: https://pytorch.org/get-started/locally/
```
conda install pytorch torchvision torchaudio cudatoolkit=11.0 -c pytorch
```
#### 5. Clone repo
```
git clone https://github.com/kinoai/hackathon-template
```
#### 6. Install requirements with pip
```
cd hackathon-template
pip install -r requirements.txt
```
#### 7. Log into your wandb account
```
wandb login
```
#### 8. 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'"`
#### Important notes!
- 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 `config.yaml`:
```
num_of_gpus: 0
```
+26
View File
@@ -0,0 +1,26 @@
## Tips
- PyTorch Lightning Bolts is official collection of prebuilt models across many research domains:
- https://pytorch-lightning.readthedocs.io/en/latest/bolts.html
- https://github.com/PyTorchLightning/pytorch-lightning-bolts
- Pre-trained pytorch model repository designed for research exploration:
- https://pytorch.org/hub/
- List of all tools in PyTorch ecosystem:
- https://pytorch.org/ecosystem/
- Additional pl.Trainer() parameters which can be useful:
- <b>accumulate_grad_batches=5</b> - perform optimisation after accumulating gradient from 5 batches
- <b>accumulate_grad_batches={5: 3, 10: 20}</b> - no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
- <b>auto_scale_batch_size='power'</b> - automatically find the largest batch size that fits into memory and is power of 2 (requires calling trainer.tune(model, datamodule))
- <b>check_val_every_n_epoch=10</b> - run validation loop every 10 training epochs
- <b>val_check_interval=0.25</b> - check validation set 4 times during a training epoch
- <b>fast_dev_run=True</b> - runs 1 train, val, test batch and program ends (great for debugging)
- <b>min_epochs=1</b> - force training for at least these many epochs
- <b>overfit_batches=0.01</b> - use only 1% of the train set (and use the train set for val and test)
- <b>overfit_batches=10</b> - use only 10 batches of the train set (and use the train set for val and test)
- <b>limit_train_batches=0.25</b> - run through only 25% of the training set each epoch
- <b>limit_val_batches=0.25</b>
- <b>limit_test_batches=0.25</b>
- <b>precision=16</b> - set tensor precision (default is 32 bits)
- <b>amp_backend='apex'</b> - apex backend for mixed precision training https://github.com/NVIDIA/apex
+64 -18
View File
@@ -1,26 +1,72 @@
num_of_gpus: -1 num_of_gpus: -1
hparams: model_configs:
# these hyperparameters should always be in this file simple_mnist_classifier_v1: # everything inside will be saved to to wandb and in model checkpoint
max_epochs: 3 model_folder_name: "simple_mnist_classifier"
batch_size: 64 max_epochs: 3
lr: 0.001 lr: 0.001
weight_decay: 0.000001 batch_size: 64
gradient_clip_val: 0.5 weight_decay: 0.000001
accumulate_grad_batches: 1 gradient_clip_val: 0.5
accumulate_grad_batches: 1
input_size: 784 # img size is 28*28*1
output_size: 10
lin1_size: 256
lin2_size: 256
lin3_size: 128
dataset:
class_name: "MNISTDataModule"
train_transforms: "minst_train_preprocess"
test_transforms: "minst_test_preprocess"
train_val_split_ratio: 0.8
num_workers: 1
pin_memory: False
# these hyperparameters are custom, you can add here anything transfer_learning_cifar10_classifier_v1:
train_val_split_ratio: 0.9 model_folder_name: "transfer_learning_img_classifier"
output_size: 10 max_epochs: 3
lin1_size: 256 lr: 0.001
lin2_size: 256 batch_size: 128
lin3_size: 128 weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
output_size: 10
lin1_size: 512
lin2_size: 256
dataset:
class_name: "CIFAR10DataModule"
train_transforms: "cifar10_train_preprocess"
test_transforms: "cifar10_test_preprocess"
train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False
transfer_learning_cifar10_classifier_v2:
model_folder_name: "transfer_learning_img_classifier"
max_epochs: 3
lr: 0.001
batch_size: 128
weight_decay: 0.000001
gradient_clip_val: 0.5
accumulate_grad_batches: 1
output_size: 10
lin1_size: 512
lin2_size: 256
dataset:
class_name: "CIFAR10DataModule"
train_transforms: "cifar10_train_preprocess"
test_transforms: "cifar10_test_preprocess"
train_val_split_ratio: 0.9
num_workers: 1
pin_memory: False
resume: # this is for resuming training from lightning checkpoint resume_training:
resume_from_ckpt: False lightning_ckpt:
wandb_run_id: "8uuomodb" resume_from_ckpt: False
ckpt_path: "checkpoints/epoch=2.ckpt" ckpt_path: "logs/checkpoints/epoch=2.ckpt"
wandb:
resume_wandb_run: False
wandb_run_id: "8uuomodb"
loggers: loggers:
wandb: wandb:
Binary file not shown.
+9 -4
View File
@@ -2,8 +2,13 @@ import wandb
import train import train
# THIS FILE SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
# Load project config # Load project config
config = train.load_config() conf = train.load_config()
# Choose model for hyperparameter search
model_conf = conf["model_configs"]["simple_mnist_classifier_v1"]
# Initialize wandb # Initialize wandb
wandb.init() wandb.init()
@@ -11,8 +16,8 @@ wandb.init()
# Replace project config hyperparameters with the ones loaded from wandb sweep server # Replace project config hyperparameters with the ones loaded from wandb sweep server
sweep_hparams = wandb.Config._as_dict(wandb.config) sweep_hparams = wandb.Config._as_dict(wandb.config)
for key, value in sweep_hparams.items(): for key, value in sweep_hparams.items():
if key != "_wandb": if key != "_wandb" and not key.startswith("dataset/"):
config["hparams"][key] = value model_conf[key] = value
# Execute run # Execute run
train.train(config) train.train(config=conf, model_config=model_conf)
+21 -20
View File
@@ -47,26 +47,27 @@ def download_artifact():
print("Files are being downloaded now...") print("Files are being downloaded now...")
def download_model_from_wandb_run(): # TODO
""" # def download_model_from_wandb_run():
WARNING: This will overwrite your training_modules/models.py and training_modules/lightning_wrapper.py files! # """
""" # WARNING: This will overwrite your lightning_modules/models.py and lightning_modules/lightning_module.py files!
RUN_ID = "kino/hackathon_template_test/lx9voyom" # """
MODEL_PATH = "last.ckpt" # RUN_ID = "kino/hackathon_template_test/lx9voyom"
CODE_PATHS = [ # MODEL_PATH = "last.ckpt"
"code/training_modules/lightning_wrapper.py", # CODE_PATHS = [
"code/training_modules/models.py" # "code/lightning_modules/lightning_module.py",
] # "code/lightning_modules/models.py"
# ]
api = wandb.Api() #
run = api.run(path=RUN_ID) # api = wandb.Api()
# run = api.run(path=RUN_ID)
# download model #
run.file(MODEL_PATH).download(replace=True) # # download model
# run.file(MODEL_PATH).download(replace=True)
# download and replace your code #
for path in CODE_PATHS: # # download and replace your code
run.file(path).download(root="../training_modules/", replace=True) # for path in CODE_PATHS:
# run.file(path).download(root="../lightning_modules/", replace=True)
if __name__ == "__main__": if __name__ == "__main__":
@@ -1,7 +1,7 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import pytorch_lightning as pl import pytorch_lightning as pl
from shutil import copy, copyfile from shutil import copy
import seaborn import inspect
import torch import torch
import wandb import wandb
import os import os
@@ -88,6 +88,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
""" """
Generate f1, precision and recall heatmap calculated from each validation epoch outputs. Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
Works only for single label classification!
""" """
def __init__(self): def __init__(self):
self.preds = [] self.preds = []
@@ -128,25 +129,24 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
class SaveCodeToWandbCallback(pl.Callback): class SaveCodeToWandbCallback(pl.Callback):
""" """
Upload specified files to wandb at the beginning of the run. Upload specified code files to wandb at the beginning of the run.
""" """
def __init__(self, wandb_save_dir): def __init__(self, wandb_save_dir, lit_model):
self.wandb_save_dir = wandb_save_dir self.wandb_save_dir = wandb_save_dir
self.files_to_be_saved = [ self.additional_files_to_be_saved = [
"training_modules/callbacks.py", "lightning_modules/data_modules/datamodules.py",
"training_modules/datamodules.py", "lightning_modules/data_modules/datasets.py",
"training_modules/datasets.py", "lightning_modules/data_modules/transforms.py",
"training_modules/lightning_wrapper.py", "lightning_modules/callbacks.py",
"training_modules/loggers.py", "lightning_modules/init_utils.py",
"training_modules/models.py",
"training_modules/transforms.py",
"train.py", "train.py",
"config.yaml" "config.yaml"
] ]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
def on_sanity_check_end(self, trainer, pl_module): def on_sanity_check_end(self, trainer, pl_module):
"""Upload files when all validation sanity checks end.""" """Upload files when all validation sanity checks end."""
for file in self.files_to_be_saved: for file in self.additional_files_to_be_saved:
dst_path = os.path.join(self.wandb_save_dir, "code", file) dst_path = os.path.join(self.wandb_save_dir, "code", file)
path, filename = os.path.split(dst_path) path, filename = os.path.split(dst_path)
@@ -155,3 +155,16 @@ class SaveCodeToWandbCallback(pl.Callback):
copy(file, dst_path) copy(file, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate 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):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path),
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)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
@@ -1,31 +1,27 @@
from pl_bolts.models.self_supervised.cpc.transforms import CPCTrainTransformsImageNet128
from torch.utils.data import DataLoader, random_split from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST, CIFAR10 from torchvision.datasets import MNIST, CIFAR10
import pytorch_lightning as pl import pytorch_lightning as pl
import numpy as np
# custom # custom data_modules
from training_modules.transforms import *
from training_modules.datasets import *
class ExampleDataModule(pl.LightningDataModule): class ExampleDataModule(pl.LightningDataModule):
"""All datamodules should look like this!""" """All datamodules should look like this!"""
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90): def __init__(self, transforms, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.split_ratio = split_ratio self.data_split_ratio = data_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
# optional variables
self.input_dims = None
self.input_size = None
def prepare_data(self): def prepare_data(self):
"""Download data if needed.""" """Download data if needed."""
pass pass
@@ -35,30 +31,34 @@ class ExampleDataModule(pl.LightningDataModule):
pass pass
def train_dataloader(self): def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size) return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self): def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size) return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self): def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size) return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
class MNISTDataModule(pl.LightningDataModule): class MNISTDataModule(pl.LightningDataModule):
def __init__(self, data_dir='data/mnist', batch_size=64, split_ratio=0.90): def __init__(self, transforms, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.split_ratio = split_ratio self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
self.input_dims = None
self.input_size = None
def prepare_data(self): def prepare_data(self):
"""Download data if needed.""" """Download data if needed."""
MNIST(self.data_dir, train=True, download=True) MNIST(self.data_dir, train=True, download=True)
@@ -66,42 +66,43 @@ class MNISTDataModule(pl.LightningDataModule):
def setup(self, stage=None): def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test.""" """Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=transforms.ToTensor()) trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.split_ratio) train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length] train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
self.data_train, self.data_val = random_split(trainset, train_val_split) self.data_train, self.data_val = random_split(trainset, train_val_split)
self.data_test = MNIST(self.data_dir, train=False, transform=transforms.ToTensor()) self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms)
self.input_dims = self.data_train[0][0].shape
self.input_size = np.prod(self.input_dims)
def train_dataloader(self): def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size) return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self): def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size) return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self): def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size) return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
class CIFAR10DataModule(pl.LightningDataModule): class CIFAR10DataModule(pl.LightningDataModule):
def __init__(self, data_dir="data/cifar10", batch_size=64, split_ratio=0.90): def __init__(self, transforms, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False, **args):
super().__init__() super().__init__()
self.transforms = transforms
self.data_dir = data_dir self.data_dir = data_dir
self.batch_size = batch_size self.batch_size = batch_size
self.split_ratio = split_ratio self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.data_train = None self.data_train = None
self.data_val = None self.data_val = None
self.data_test = None self.data_test = None
self.input_dims = None
self.input_size = None
def prepare_data(self): def prepare_data(self):
"""Download data if needed.""" """Download data if needed."""
CIFAR10(self.data_dir, train=True, download=True) CIFAR10(self.data_dir, train=True, download=True)
@@ -109,22 +110,22 @@ class CIFAR10DataModule(pl.LightningDataModule):
def setup(self, stage=None): def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test.""" """Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = CIFAR10(self.data_dir, train=True, transform=transforms.ToTensor()) trainset = CIFAR10(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.split_ratio) train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length] train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
self.data_train, self.data_val = random_split(trainset, train_val_split) self.data_train, self.data_val = random_split(trainset, train_val_split)
self.data_test = CIFAR10(self.data_dir, train=False, transform=transforms.ToTensor()) self.data_test = CIFAR10(self.data_dir, train=False, transform=self.transforms)
self.input_dims = self.data_train[0][0].shape
self.input_size = np.prod(self.input_dims)
def train_dataloader(self): def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size) return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def val_dataloader(self): def val_dataloader(self):
return DataLoader(self.data_val, batch_size=self.batch_size) return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
def test_dataloader(self): def test_dataloader(self):
return DataLoader(self.data_test, batch_size=self.batch_size) return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
@@ -1,6 +1,14 @@
from torchvision import transforms from torchvision import transforms
minst_train_preprocess = transforms.Compose([
transforms.ToTensor(),
])
mnist_test_preprocess = transforms.Compose([
transforms.ToTensor()
])
img_augmentation_transformations = [ img_augmentation_transformations = [
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)), transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
transforms.RandomHorizontalFlip(p=0.65), transforms.RandomHorizontalFlip(p=0.65),
@@ -8,7 +16,7 @@ img_augmentation_transformations = [
transforms.ColorJitter(hue=.05, saturation=.05), transforms.ColorJitter(hue=.05, saturation=.05),
] ]
efficient_net_train_preprocess = transforms.Compose([ imagenet_train_preprocess = transforms.Compose([
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
transforms.RandomCrop(224), transforms.RandomCrop(224),
transforms.ToTensor(), transforms.ToTensor(),
@@ -16,8 +24,17 @@ efficient_net_train_preprocess = transforms.Compose([
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]) ])
efficient_net_test_preprocess = transforms.Compose([ imagenet_test_preprocess = transforms.Compose([
transforms.Resize((224, 224)), transforms.Resize((224, 224)),
transforms.ToTensor(), transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
]) ])
cifar10_train_preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.RandomHorizontalFlip(p=0.5),
])
cifar10_test_preprocess = transforms.Compose([
transforms.ToTensor(),
])
+71
View File
@@ -0,0 +1,71 @@
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from lightning_modules.data_modules import datamodules, transforms
import importlib
import os
def init_lit_model(model_config):
module_path = "models." + model_config["model_folder_name"] + ".lightning_module"
return importlib.import_module(module_path).LitModel(hparams=model_config)
def init_datamodule(model_config):
datamodule_class = getattr(datamodules, model_config["dataset"]["class_name"])
train_transforms = getattr(transforms, model_config["dataset"]["train_transforms"])
datamodule = datamodule_class(
transforms=train_transforms,
batch_size=model_config["batch_size"],
**model_config["dataset"]
)
datamodule.prepare_data()
datamodule.setup()
return datamodule
def init_main_callbacks(config):
callbacks = [
EarlyStopping(
monitor=config["callbacks"]["early_stop"]["monitor"],
patience=config["callbacks"]["early_stop"]["patience"],
mode=config["callbacks"]["early_stop"]["mode"],
),
ModelCheckpoint(
monitor=config["callbacks"]["checkpoint"]["monitor"],
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"],
mode=config["callbacks"]["checkpoint"]["mode"],
save_last=config["callbacks"]["checkpoint"]["save_last"],
)
]
return callbacks
def init_wandb_logger(config, lit_model, datamodule):
wandb_logger = WandbLogger(
project=config["loggers"]["wandb"]["project"],
job_type=config["loggers"]["wandb"]["job_type"],
tags=config["loggers"]["wandb"]["tags"],
entity=config["loggers"]["wandb"]["team"],
id=config["resume_training"]["wandb"]["wandb_run_id"]
if config["resume_training"]["wandb"]["resume_wandb_run"] else None,
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
save_dir="logs/",
save_code=False
)
if not os.path.exists("logs/"):
os.mkdir("logs/")
wandb_logger.watch(lit_model.model, log=None)
wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__,
"optimizer": lit_model.configure_optimizers().__class__.__name__,
"train_size": len(datamodule.data_train) if datamodule.data_train is not None else 0,
"val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0,
"test_size": len(datamodule.data_test) if datamodule.data_train is not None else 0,
})
return wandb_logger
def init_tensorboard_loggger():
"""TODO"""
return None
View File
Whitespace-only changes.
@@ -0,0 +1 @@
from .lightning_module import LitModel
@@ -1,11 +1,10 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score from sklearn.metrics import accuracy_score
from pl_bolts.models.regression import LinearRegression, LogisticRegression
from torch.nn.functional import one_hot
import torch.nn.functional as F
import pytorch_lightning as pl import pytorch_lightning as pl
import torch.nn.functional as F
import torch
# custom models # custom models
from training_modules.models import * from models.simple_mnist_classifier.models import *
class LitModel(pl.LightningModule): class LitModel(pl.LightningModule):
@@ -16,7 +15,7 @@ class LitModel(pl.LightningModule):
if hparams: if hparams:
self.save_hyperparameters(hparams) self.save_hyperparameters(hparams)
self.model = SimpleLinearMNIST(config=self.hparams) self.model = SimpleMNISTClassifier(config=self.hparams)
def forward(self, x): def forward(self, x):
return self.model(x) return self.model(x)
@@ -0,0 +1,32 @@
from torch import nn
class SimpleMNISTClassifier(nn.Module):
def __init__(self, config):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
nn.Linear(config["input_size"], config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin2_size"], config["lin3_size"]),
nn.BatchNorm1d(config["lin3_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin3_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
batch_size, channels, width, height = x.size()
# (b, 1, 28, 28) -> (b, 1*28*28)
x = x.view(batch_size, -1)
return self.model(x)
@@ -1,14 +1,12 @@
from training_modules.lightning_wrapper import LitModel from models.simple_mnist_classifier.lightning_module import LitModel
from training_modules.datamodules import * from lightning_modules.data_modules import transforms
from training_modules.datasets import *
from training_modules import transforms
from PIL import Image from PIL import Image
def predict(): def predict():
""" """
Loads model from checkpoint. Loads model from checkpoint.
Model used in training_modules/lightning_wrapper.py and declaration of that model in training_modules/models.py Model used in lightning_module.py and declaration of that model in models.py
should be the same as during training. should be the same as during training.
""" """
@@ -22,10 +20,10 @@ def predict():
pretrained_model.freeze() pretrained_model.freeze()
# load data # load data
img = Image.open("example_img.png").convert("RGB") img = Image.open("../../example_img.png").convert("L")
# preprocess # preprocess
img = transforms.efficient_net_test_preprocess(img) img = transforms.mnist_test_preprocess(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1 img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference # inference
@@ -0,0 +1 @@
from .lightning_module import LitModel
@@ -0,0 +1,70 @@
from sklearn.metrics import accuracy_score
import pytorch_lightning as pl
import torch.nn.functional as F
import torch
# custom models
from models.transfer_learning_img_classifier.models import *
class LitModel(pl.LightningModule):
def __init__(self, hparams=None):
super().__init__()
if hparams:
self.save_hyperparameters(hparams)
self.model = EfficientNetPretrained(config=self.hparams)
def forward(self, x):
return self.model(x)
# logic for a single training step
def training_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# training metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
return loss
# logic for a single validation step
def validation_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# validation metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
# we can return here anything and then read it in some callback
return preds, y
# logic for a single testing step
def test_step(self, batch, batch_idx):
x, y = batch
logits = self.model(x)
loss = F.nll_loss(logits, y)
# test metrics
preds = torch.argmax(logits, dim=1)
preds, y = preds.cpu(), y.cpu()
acc = accuracy_score(preds, y)
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"])
@@ -1,41 +1,7 @@
from pl_bolts.models.self_supervised import CPCV2 from pl_bolts.models.self_supervised import CPCV2
from efficientnet_pytorch import EfficientNet from efficientnet_pytorch import EfficientNet
import torch.nn.functional as F
from torchvision import models from torchvision import models
from torch import nn from torch import nn
import torch
class SimpleLinearMNIST(nn.Module):
def __init__(self, config):
super().__init__()
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
nn.Linear(28*28, config["lin1_size"]),
# nn.Linear(3*32*32, config["lin1_size"]), # for CIFAR10
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin2_size"], config["lin3_size"]),
nn.BatchNorm1d(config["lin3_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin3_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
batch_size, channels, width, height = x.size()
# (b, 1, 28, 28) -> (b, 1*28*28)
x = x.view(batch_size, -1)
return self.model(x)
class EfficientNetPretrained(nn.Module): class EfficientNetPretrained(nn.Module):
@@ -0,0 +1,35 @@
from models.transfer_learning_img_classifier.lightning_module import LitModel
from lightning_modules.data_modules import transforms
from PIL import Image
def predict():
"""
Loads model from checkpoint.
Model used in lightning_module.py and declaration of that model in models.py
should be the same as during training.
"""
CKPT_PATH = "epoch=0.ckpt"
# load model from checkpoint
pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# switch to evaluation mode
pretrained_model.eval()
pretrained_model.freeze()
# load data
img = Image.open("../../example_img.png").convert("RGB")
# preprocess
img = transforms.imagenet_test_preprocess(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = pretrained_model(img)
print(output)
if __name__ == "__main__":
predict()
+47 -49
View File
@@ -1,81 +1,70 @@
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from pytorch_lightning.profiler import SimpleProfiler from pytorch_lightning.profiler import SimpleProfiler
import yaml import yaml
# custom # lightning modules
from training_modules.lightning_wrapper import LitModel from lightning_modules.init_utils import *
from training_modules.loggers import * from lightning_modules.callbacks import *
from training_modules.datamodules import *
from training_modules.callbacks import *
def train(config): def train(config, model_config):
# Init data module
datamodule = MNISTDataModule(
batch_size=config["hparams"]["batch_size"],
split_ratio=config["hparams"]["train_val_split_ratio"]
)
datamodule.prepare_data()
datamodule.setup()
# Init our model # Init lightning model
model = LitModel(hparams=config["hparams"]) lit_model = init_lit_model(model_config)
# Init experiment logger # Init lightning datamodule
logger = get_wandb_logger(config, model, datamodule) datamodule = init_datamodule(model_config)
# Init logger
logger = init_wandb_logger(config, lit_model, datamodule)
# Init callbacks # Init callbacks
callbacks = [ callbacks = init_main_callbacks(config)
EarlyStopping( callbacks.extend([
monitor=config["callbacks"]["early_stop"]["monitor"],
patience=config["callbacks"]["early_stop"]["patience"],
mode=config["callbacks"]["early_stop"]["mode"],
),
ModelCheckpoint(
monitor=config["callbacks"]["checkpoint"]["monitor"],
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"],
mode=config["callbacks"]["checkpoint"]["mode"],
save_last=config["callbacks"]["checkpoint"]["save_last"],
),
# MetricsHeatmapLoggerCallback(), # MetricsHeatmapLoggerCallback(),
# UnfreezeModelCallback(wait_epochs=5), # UnfreezeModelCallback(wait_epochs=5),
# ImagePredictionLoggerCallback(datamodule=datamodule), # ImagePredictionLoggerCallback(datamodule=datamodule),
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir), SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model),
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir) # SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
] ])
# Init trainer # Init trainer
trainer = pl.Trainer( trainer = pl.Trainer(
logger=logger, logger=logger,
callbacks=callbacks, callbacks=callbacks,
gpus=config["num_of_gpus"], gpus=config["num_of_gpus"],
max_epochs=config["hparams"]["max_epochs"],
resume_from_checkpoint=config["resume"]["ckpt_path"] if config["resume"]["resume_from_ckpt"] else None, resume_from_checkpoint=config["resume_training"]["lightning_ckpt"]["ckpt_path"]
accumulate_grad_batches=config["hparams"]["accumulate_grad_batches"], if config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
gradient_clip_val=config["hparams"]["gradient_clip_val"],
# model related:
max_epochs=model_config["max_epochs"],
accumulate_grad_batches=model_config["accumulate_grad_batches"],
gradient_clip_val=model_config["gradient_clip_val"],
# print related:
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"], progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
profiler=SimpleProfiler() if config["printing"]["profiler"] else None, profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
weights_summary=config["printing"]["weights_summary"], weights_summary=config["printing"]["weights_summary"],
# these are mostly for debugging (read TIPS.md for explanation):
fast_dev_run=False,
num_sanity_val_steps=3, num_sanity_val_steps=3,
default_root_dir="logs/lightning_logs" limit_train_batches=1.0,
# fast_dev_run=True, limit_val_batches=1.0,
# min_epochs=10, limit_test_batches=1.0,
# limit_train_batches=0.1 val_check_interval=1.0,
# limit_val_batches=0.01
# limit_test_batches=0.01 default_root_dir="logs/lightning_logs",
# auto_scale_batch_size="power",
# amp_backend='apex',
# precision=16,
) )
# Test before training # Test before training
# trainer.test(model=model, datamodule=datamodule) # trainer.test(model=lit_model, datamodule=datamodule)
# Save randomly initialized model # Save checkpoint
# trainer.save_checkpoint("random.ckpt") # trainer.save_checkpoint("random.ckpt")
# Train the model ⚡ # Train the model ⚡
trainer.fit(model=model, datamodule=datamodule) trainer.fit(model=lit_model, datamodule=datamodule)
# Evaluate model on test set # Evaluate model on test set
trainer.test() trainer.test()
@@ -88,4 +77,13 @@ def load_config():
if __name__ == "__main__": if __name__ == "__main__":
train(config=load_config()) conf = load_config()
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↓↓↓ --------------------------------------- #
model_conf = conf["model_configs"]["simple_mnist_classifier_v1"]
# model_conf = conf["model_configs"]["transfer_learning_cifar10_classifier_v1"]
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↑↑↑ --------------------------------------- #
train(config=conf, model_config=model_conf)
-37
View File
@@ -1,37 +0,0 @@
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
import os
def get_wandb_logger(config, lit_model, datamodule):
wandb_logger = WandbLogger(
project=config["loggers"]["wandb"]["project"],
job_type=config["loggers"]["wandb"]["job_type"],
tags=config["loggers"]["wandb"]["tags"],
entity=config["loggers"]["wandb"]["team"],
id=config["resume"]["wandb_run_id"] if config["resume"]["resume_from_ckpt"] else None,
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
save_dir="logs/",
save_code=False
)
if not os.path.exists("logs/"):
os.mkdir("logs/")
wandb_logger.watch(lit_model.model, log=None)
wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__,
"datamodule_name": datamodule.__class__.__name__,
"optimizer": lit_model.configure_optimizers().__class__.__name__,
"train_size": len(datamodule.data_train) if datamodule.data_train is not None else 0,
"val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0,
"test_size": len(datamodule.data_test) if datamodule.data_train is not None else 0,
"input_dims": datamodule.input_dims,
"input_size": datamodule.input_size,
})
# download model from a specific wandb run
# wandb.restore('model-best.h5', run_path="kino/some_project/a1b2c3d")
return wandb_logger
def get_tensorboard_loggger():
"""TODO"""
return None