18 files changed
+687
-492
No files matched your search
@@ -3,19 +3,20 @@ 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>
|
Click on <b>"Use this template"</b> button above to initialize new repository.<br>
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
- All advantages of PyTorch Lightning
|
|
||||||
- Predefined folder structure
|
- Predefined folder structure
|
||||||
- Storing project configuration in a convenient way ([project_config.yaml](project/project_config.yaml))
|
- 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))
|
- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml))
|
||||||
|
- All advantages of PyTorch Lightning
|
||||||
|
- Weights&Biases integration:
|
||||||
|
- Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud
|
||||||
|
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))
|
||||||
- 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)
|
- 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
|
- Scheduling execution of many experiments ([execute_all_runs.py](project/template_utils/execute_all_runs.py))
|
||||||
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/utils/execute_sweep.py))
|
|
||||||
- Scheduling execution of many experiments ([execute_all_runs.py](project/utils/execute_all_runs.py))
|
|
||||||
- Built in requirements ([requirements.txt](requirements.txt))
|
- Built in requirements ([requirements.txt](requirements.txt))
|
||||||
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
||||||
- Built in package setup ([setup.py](setup.py))
|
- Built in package setup ([setup.py](setup.py))
|
||||||
- Example with MNIST digits classification
|
- Example with MNIST digits classification
|
||||||
- Useful example callbacks ([callbacks.py](project/utils/callbacks.py))
|
- Useful example callbacks ([callbacks.py](project/template_utils/callbacks.py))
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
@@ -29,25 +30,25 @@ The directory structure of new project looks like this:
|
|||||||
│ │
|
│ │
|
||||||
│ ├── notebooks <- Jupyter notebooks
|
│ ├── notebooks <- Jupyter notebooks
|
||||||
│ │
|
│ │
|
||||||
│ ├── utils <- Different utilities
|
│ ├── template_utils <- Different utilities
|
||||||
│ │ ├── callbacks.py <- Useful training callbacks
|
│ │ ├── callbacks.py <- Useful training callbacks
|
||||||
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
|
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
|
||||||
│ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other
|
│ │ ├── execute_all_runs.py <- Special file for executing all specified runs one after the other
|
||||||
│ │ ├── init_utils.py <- Useful initializers
|
│ │ ├── initializers.py <- Useful initializers
|
||||||
│ │ └── predict_example.py <- Example of inference with trained model
|
│ │ └── predict_example.py <- Example of inference with trained model
|
||||||
│ │
|
│ │
|
||||||
│ ├── data_modules <- All your data modules should be located here!
|
│ ├── datamodules <- All your datamodules should be located here!
|
||||||
│ │ ├── example_datamodule <- Each datamodule should be located in separate folder!
|
│ │ ├── example_datamodule <- It's best to locate each datamodule in separate folder!
|
||||||
│ │ │ ├── datamodule.py <- Contains 'DataModule' class
|
│ │ │ ├── datamodule.py <- Contains class of type 'LightningDataModule'
|
||||||
│ │ │ ├── datasets.py <- Contains pytorch 'Dataset' classes (optional file)
|
│ │ │ ├── transforms.py <- Some optional file
|
||||||
│ │ │ └── transforms.py <- Contains data transformations (optional file)
|
│ │ │ └── ...
|
||||||
│ │ ├── ...
|
│ │ ├── ...
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
│ │
|
│ │
|
||||||
│ ├── models <- All your models should be located here!
|
│ ├── models <- All your models should be located here!
|
||||||
│ │ ├── example_model <- Each model should be located in separate folder!
|
│ │ ├── example_model <- It's best to locate each model in separate folder!
|
||||||
│ │ │ ├── lightning_module.py <- Contains 'LitModel' class with train/val/test step methods
|
│ │ │ ├── lightning_module.py <- Contains class of type 'LightningModule'
|
||||||
│ │ │ └── models.py <- Model architectures used by lightning_module.py (optional file)
|
│ │ │ └── models.py <- Model architectures used by 'LightningModule'
|
||||||
│ │ ├── ...
|
│ │ ├── ...
|
||||||
│ │ └── ...
|
│ │ └── ...
|
||||||
│ │
|
│ │
|
||||||
@@ -68,23 +69,24 @@ The directory structure of new project looks like this:
|
|||||||
## Project config parameters ([project_config.yaml](project/project_config.yaml))
|
## Project config parameters ([project_config.yaml](project/project_config.yaml))
|
||||||
Example project configuration:
|
Example project configuration:
|
||||||
```yaml
|
```yaml
|
||||||
num_of_gpus: -1 <- '-1' to use all gpus available, '0' to train on cpu
|
num_of_gpus: -1 <- '-1' to train on all GPUs available, '0' to train on CPU
|
||||||
|
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
project: "project_name" <- wandb project name
|
project: "project_name" <- wandb project name
|
||||||
entity: "some_name" <- wandb entity name
|
entity: "some_name" <- wandb entity name
|
||||||
log_model: True <- set True if you want to upload ckpts to wandb automatically
|
log_model: True <- set True if you want to upload ckpts to wandb automatically
|
||||||
|
log_gradients: False <- set True to log gradient histograms
|
||||||
offline: False <- set True if you want to store all data locally
|
offline: False <- set True if you want to store all data locally
|
||||||
|
|
||||||
callbacks:
|
default_callbacks:
|
||||||
checkpoint:
|
ModelCheckpoint:
|
||||||
monitor: "val_acc" <- name of the logged metric that determines when model is improving
|
monitor: "val_acc" <- name of the logged metric which determines when model is improving
|
||||||
save_top_k: 1 <- save k best models (determined by above metric)
|
save_top_k: 1 <- save k best models (determined by above metric)
|
||||||
save_last: True <- additionaly always save model from last epoch
|
save_last: True <- additionaly always save model from last epoch
|
||||||
mode: "max" <- can be "max" or "min"
|
mode: "max" <- can be "max" or "min"
|
||||||
early_stop:
|
EarlyStopping:
|
||||||
monitor: "val_acc" <- name of the logged metric that determines when model is improving
|
monitor: "val_acc" <- name of the logged metric which determines when model is improving
|
||||||
patience: 5 <- 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"
|
mode: "max" <- can be "max" or "min"
|
||||||
|
|
||||||
@@ -92,6 +94,9 @@ printing:
|
|||||||
progress_bar_refresh_rate: 5 <- refresh rate of training bar in terminal
|
progress_bar_refresh_rate: 5 <- refresh rate of training bar in terminal
|
||||||
weights_summary: "top" <- print summary of model (alternatively "full")
|
weights_summary: "top" <- print summary of model (alternatively "full")
|
||||||
profiler: False <- set True if you want to see execution time profiling
|
profiler: False <- set True if you want to see execution time profiling
|
||||||
|
|
||||||
|
data_dir: "data/" <- path to data folder
|
||||||
|
logs_dir: "logs/" <- path to logs folder
|
||||||
```
|
```
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
@@ -100,55 +105,55 @@ printing:
|
|||||||
You can store many run configurations in this file.<br>
|
You can store many run configurations in this file.<br>
|
||||||
Example run configuration:
|
Example run configuration:
|
||||||
```yaml
|
```yaml
|
||||||
MNIST_CLASSIFIER_V1:
|
SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||||
trainer: # these parameters will be passed directly to PyTorch Lightning 'Trainer' object
|
seed: 1234
|
||||||
max_epochs: 5
|
trainer:
|
||||||
gradient_clip_val: 0.5
|
args:
|
||||||
accumulate_grad_batches: 1
|
max_epochs: 10
|
||||||
limit_train_batches: 1.0
|
model:
|
||||||
model: # these parameters will be passed to 'LightningModule' object as 'hparams' dictionary
|
load_from:
|
||||||
model_folder: "simple_mnist_classifier"
|
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||||
|
model_class: "LitModel"
|
||||||
|
hparams:
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
weight_decay: 0.000001
|
weight_decay: 0.00001
|
||||||
input_size: 784
|
input_size: 784
|
||||||
output_size: 10
|
output_size: 10
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
dataset: # these parameters will be passed to 'LightningDataModule' object as 'hparams' dictionary
|
datamodule:
|
||||||
datamodule_folder: "mnist_digits_datamodule"
|
load_from:
|
||||||
batch_size: 256
|
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
||||||
train_val_split_ratio: 0.9
|
datamodule_class: "MNISTDataModule"
|
||||||
num_workers: 1
|
hparams:
|
||||||
pin_memory: False
|
batch_size: 64
|
||||||
callbacks:
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
ConfusionMatrixLoggerCallback:
|
|
||||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
|
||||||
wandb:
|
|
||||||
group: ""
|
|
||||||
tags: ["v1", "uwu"]
|
|
||||||
resume_training:
|
|
||||||
checkpoint_path: "path_to_checkpoint/last.ckpt"
|
|
||||||
wandb_run_id: None
|
|
||||||
```
|
```
|
||||||
Each run configuration needs to contain sections `trainer`, `model` and `dataset`. Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.<br>
|
To start training with this configuration run:<br>
|
||||||
|
`python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST`
|
||||||
|
|
||||||
Section `model` always needs to contain `model_folder` parameter (name of the folder from which `lightning_module.py` will be loaded, which should contain `LitModel` class).<br>
|
Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.<br>
|
||||||
Section `dataset` always needs to contain `datamodule_folder` parameter (name of the folder from which `datamodule.py` will be loaded, which should contain `DataModule` class).<br>
|
EVERY OTHER SECTION IS OPTIONAL! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<br>
|
||||||
|
|
||||||
Every parameter in `model` section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).<br>
|
|
||||||
Every parameter in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/data_modules/mnist_digits_datamodule/datamodule.py)).<br>
|
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).<br>
|
||||||
|
|
||||||
|
Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).<br>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## Workflow
|
## Workflow
|
||||||
1. Add your model to `project/models` folder. You need to create folder with `lightning_module.py` file containing `LitModel` class
|
1. Create PyTorch Lightning model
|
||||||
2. Add your datamodule to `project/data_modules` folder. You need to create folder with `datamodule.py` file containing `DataModule` class
|
2. Create PyTorch Lightning datamodule
|
||||||
3. Create new run config in [run_configs.yaml](project/run_configs.yaml) (specify there folders containing your model and datamodule)
|
3. Create new run config in [run_configs.yaml](project/run_configs.yaml)
|
||||||
3. Configure [project_config.yaml](project/project_config.yaml)
|
- specify path to your model class
|
||||||
|
- specify path to your datamodule class
|
||||||
|
- you can add there any hyperparameters you want!
|
||||||
|
3. Configure your project in [project_config.yaml](project/project_config.yaml)
|
||||||
4. Run training with chosen run config<br>
|
4. Run training with chosen run config<br>
|
||||||
```bash
|
```bash
|
||||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||||
```
|
```
|
||||||
<br><br>
|
<br><br>
|
||||||
|
|
||||||
@@ -192,7 +197,7 @@ Next, you can train model without logging
|
|||||||
# train model without Weights&Biases
|
# train model without Weights&Biases
|
||||||
# choose run config from project/run_configs.yaml
|
# choose run config from project/run_configs.yaml
|
||||||
cd project
|
cd project
|
||||||
python train.py --no_wandb --run_config MNIST_CLASSIFIER_V1
|
python train.py --no_wandb --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||||
```
|
```
|
||||||
|
|
||||||
Or you can train model with Weights&Biases logging
|
Or you can train model with Weights&Biases logging
|
||||||
@@ -207,10 +212,10 @@ loggers:
|
|||||||
# train model with Weights&Biases
|
# train model with Weights&Biases
|
||||||
# choose run config from project/run_configs.yaml
|
# choose run config from project/run_configs.yaml
|
||||||
cd project
|
cd project
|
||||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||||
```
|
```
|
||||||
|
|
||||||
Optionally you can install project as package with [setup.py](setup.py)
|
Optionally you can install project as a package with [setup.py](setup.py)
|
||||||
```bash
|
```bash
|
||||||
pip install -e .
|
pip install -e .
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,61 +0,0 @@
|
|||||||
from torch.utils.data import DataLoader, random_split
|
|
||||||
from torchvision.transforms import transforms
|
|
||||||
from torchvision.datasets import MNIST
|
|
||||||
import pytorch_lightning as pl
|
|
||||||
|
|
||||||
|
|
||||||
class DataModule(pl.LightningDataModule):
|
|
||||||
"""
|
|
||||||
This is example of datamodule for MNIST digits dataset.
|
|
||||||
All data modules should be located in separate folders with file named 'datamodule.py' containing class which
|
|
||||||
is always called 'DataModule'!
|
|
||||||
|
|
||||||
The folder name of datamodule used during training should be specified in run config and all parameters from
|
|
||||||
'dataset' section will be passed in 'hparams' dictionary.
|
|
||||||
|
|
||||||
All datamodules should have a structure like this one!
|
|
||||||
"""
|
|
||||||
def __init__(self, hparams):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
# hparams["data_dir"] is always automatically set to "path_to_project/data/"
|
|
||||||
self.data_dir = hparams["data_dir"]
|
|
||||||
|
|
||||||
self.batch_size = hparams.get("batch_size") or 64
|
|
||||||
self.train_val_split_ratio = hparams.get("train_val_split_ratio") or 0.9
|
|
||||||
self.num_workers = hparams.get("num_workers") or 1
|
|
||||||
self.pin_memory = hparams.get("pin_memory") or False
|
|
||||||
|
|
||||||
self.transforms = transforms.ToTensor()
|
|
||||||
|
|
||||||
self.data_train = None
|
|
||||||
self.data_val = None
|
|
||||||
self.data_test = None
|
|
||||||
|
|
||||||
def prepare_data(self):
|
|
||||||
"""Download data if needed."""
|
|
||||||
MNIST(self.data_dir, train=True, download=True)
|
|
||||||
MNIST(self.data_dir, train=False, download=True)
|
|
||||||
|
|
||||||
def setup(self, stage=None):
|
|
||||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
|
||||||
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
|
|
||||||
|
|
||||||
train_length = int(len(trainset) * self.train_val_split_ratio)
|
|
||||||
val_length = len(trainset) - train_length
|
|
||||||
train_val_split = [train_length, val_length]
|
|
||||||
|
|
||||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
|
||||||
self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms)
|
|
||||||
|
|
||||||
def train_dataloader(self):
|
|
||||||
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory, shuffle=True)
|
|
||||||
|
|
||||||
def val_dataloader(self):
|
|
||||||
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory)
|
|
||||||
|
|
||||||
def test_dataloader(self):
|
|
||||||
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory)
|
|
||||||
File renamed without changes.
@@ -0,0 +1,54 @@
|
|||||||
|
from torch.utils.data import DataLoader, ConcatDataset, random_split
|
||||||
|
from pytorch_lightning import LightningDataModule
|
||||||
|
from torchvision.transforms import transforms
|
||||||
|
from torchvision.datasets import MNIST
|
||||||
|
|
||||||
|
|
||||||
|
class MNISTDataModule(LightningDataModule):
|
||||||
|
"""
|
||||||
|
This is example of datamodule for MNIST dataset.
|
||||||
|
|
||||||
|
The path to datamodule should be specified in your run config. (run_configs.yaml)
|
||||||
|
The 'hparams' dict contains your hparams specified in run config. (run_configs.yaml)
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, data_dir: str, hparams: dict):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
self.data_dir = data_dir + "/MNIST" # data_dir is specified in project_config.yaml
|
||||||
|
|
||||||
|
self.batch_size = hparams.get("batch_size") or 64
|
||||||
|
self.train_val_test_split = hparams.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||||
|
self.num_workers = hparams.get("num_workers") or 1
|
||||||
|
self.pin_memory = hparams.get("pin_memory") or False
|
||||||
|
|
||||||
|
self.transforms = transforms.ToTensor()
|
||||||
|
|
||||||
|
self.data_train = None
|
||||||
|
self.data_val = None
|
||||||
|
self.data_test = None
|
||||||
|
|
||||||
|
def prepare_data(self):
|
||||||
|
"""Download data if needed."""
|
||||||
|
MNIST(self.data_dir, train=True, download=True)
|
||||||
|
MNIST(self.data_dir, train=False, download=True)
|
||||||
|
|
||||||
|
def setup(self, stage=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)
|
||||||
|
dataset = ConcatDataset(datasets=[trainset, testset])
|
||||||
|
|
||||||
|
self.data_train, self.data_val, self.data_test = random_split(dataset, self.train_val_test_split)
|
||||||
|
|
||||||
|
def train_dataloader(self):
|
||||||
|
return DataLoader(dataset=self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory, shuffle=True)
|
||||||
|
|
||||||
|
def val_dataloader(self):
|
||||||
|
return DataLoader(dataset=self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
|
def test_dataloader(self):
|
||||||
|
return DataLoader(dataset=self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
+5
-3
@@ -5,8 +5,9 @@ import os
|
|||||||
|
|
||||||
class TestDataset(Dataset):
|
class TestDataset(Dataset):
|
||||||
"""
|
"""
|
||||||
Example dataset class for loading images from folder.
|
Example dataset class for loading images from folder and converting them to monochromatic.
|
||||||
'Dataset' classes can be used by 'DataModule' class.
|
Can be used to perform inference with trained MNIST model.
|
||||||
|
'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by datamodules.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, img_dir, transform):
|
def __init__(self, img_dir, transform):
|
||||||
@@ -14,7 +15,8 @@ class TestDataset(Dataset):
|
|||||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
def __getitem__(self, idx):
|
||||||
image = Image.open(self.images[idx]).convert("RGB")
|
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||||
|
# image = Image.open(self.images[idx]).convert("RGB")
|
||||||
|
|
||||||
if self.transform is not None:
|
if self.transform is not None:
|
||||||
image = self.transform(image)
|
image = self.transform(image)
|
||||||
+3
@@ -1,3 +1,6 @@
|
|||||||
|
"""
|
||||||
|
Example file containing data transformations which can be used by datamodule.
|
||||||
|
"""
|
||||||
from torchvision import transforms
|
from torchvision import transforms
|
||||||
|
|
||||||
|
|
||||||
@@ -3,24 +3,22 @@ import pytorch_lightning as pl
|
|||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
# custom models
|
# import custom models
|
||||||
from models.simple_mnist_classifier.models import *
|
from models.simple_mnist_classifier.models import *
|
||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
"""
|
"""
|
||||||
This is example of lightning model for MNIST digits classification.
|
This is example of lightning model for MNIST digits classification.
|
||||||
All models should be located in separate folders with file named 'lightning_module.py' containing class which
|
|
||||||
is always called 'LitModel'!
|
|
||||||
|
|
||||||
The folder name of model used during training should be specified in run config and all parameters from
|
The path to model should be specified in your run config. (run_configs.yaml)
|
||||||
'model' section will be passed in 'hparams' dictionary.
|
The 'hparams' dict contains your hparams specified in your run config. (run_configs.yaml)
|
||||||
|
|
||||||
This class enables you to specify what happens during training, validation and test step.
|
This class enables you to specify what happens during training, validation and test step.
|
||||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, hparams=None):
|
def __init__(self, hparams: dict = None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
if hparams:
|
if hparams:
|
||||||
@@ -78,4 +76,4 @@ class LitModel(pl.LightningModule):
|
|||||||
return loss
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
def configure_optimizers(self):
|
||||||
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
|
return torch.optim.Adam(self.parameters(), lr=self.hparams["lr"], weight_decay=self.hparams["weight_decay"])
|
||||||
+37
-17
@@ -1,24 +1,44 @@
|
|||||||
num_of_gpus: 0
|
# set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||||
|
num_of_gpus: -1
|
||||||
|
|
||||||
|
|
||||||
|
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
project: "project_template_test"
|
project: "project_template_test"
|
||||||
entity: "kino"
|
entity: "kino" # change to your username or name of your team on wandb
|
||||||
log_model: True
|
log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
|
||||||
offline: False
|
log_gradients: False # set True to log gradient histograms (avoid this for very big models)
|
||||||
|
offline: False # set True to store all logs only locally
|
||||||
|
|
||||||
callbacks:
|
|
||||||
checkpoint:
|
|
||||||
monitor: "val_acc"
|
|
||||||
save_top_k: 1
|
|
||||||
save_last: True
|
|
||||||
mode: "max"
|
|
||||||
early_stop:
|
|
||||||
monitor: "val_acc"
|
|
||||||
patience: 100
|
|
||||||
mode: "max"
|
|
||||||
|
|
||||||
|
# default callbacks initialised on every run/experiment
|
||||||
|
# you can just remove this section or certain callback if you don't want tu use it
|
||||||
|
# you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py
|
||||||
|
# if you specify the same callback class also in run config then it will overwrite the one set here
|
||||||
|
# all of the callback parameters will be passed to it on initialization
|
||||||
|
default_callbacks:
|
||||||
|
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
|
||||||
|
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
||||||
|
save_top_k: 1 # save k best models (determined by above metric)
|
||||||
|
save_last: True # additionaly always save model from last epoch
|
||||||
|
mode: "max" # can be "max" or "min"
|
||||||
|
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
|
||||||
|
monitor: "val_acc" # name of the logged metric which determines when model is improving
|
||||||
|
patience: 5 # how many epochs of not improving until training stops
|
||||||
|
mode: "max" # can be "max" or "min"
|
||||||
|
|
||||||
|
|
||||||
|
# configure things which are printed in terminal
|
||||||
printing:
|
printing:
|
||||||
progress_bar_refresh_rate: 5
|
progress_bar_refresh_rate: 10 # refresh every 10 batches
|
||||||
weights_summary: "top" # "full"
|
weights_summary: "top" # print model summary (alternatively "full")
|
||||||
profiler: False
|
profiler: False # set True to print execution time profiling after training ends
|
||||||
|
|
||||||
|
|
||||||
|
# path to data folder (either absolute or relative to placement of 'train.py' file)
|
||||||
|
data_dir: "data/"
|
||||||
|
|
||||||
|
|
||||||
|
# path to logs folder (either absolute or relative to placement of 'train.py' file)
|
||||||
|
logs_dir: "logs/"
|
||||||
+75
-47
@@ -1,59 +1,87 @@
|
|||||||
MNIST_CLASSIFIER_V1:
|
# to execute this run:
|
||||||
|
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||||
|
SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||||
|
seed: 1234
|
||||||
trainer:
|
trainer:
|
||||||
max_epochs: 5
|
args:
|
||||||
gradient_clip_val: 0.5
|
max_epochs: 10
|
||||||
model:
|
model:
|
||||||
model_folder: "simple_mnist_classifier"
|
load_from:
|
||||||
|
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||||
|
model_class: "LitModel"
|
||||||
|
hparams:
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
weight_decay: 0.000001
|
weight_decay: 0.00001
|
||||||
|
input_size: 784
|
||||||
|
output_size: 10
|
||||||
|
lin1_size: 256
|
||||||
|
lin2_size: 256
|
||||||
|
lin3_size: 128
|
||||||
|
datamodule:
|
||||||
|
load_from:
|
||||||
|
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
||||||
|
datamodule_class: "MNISTDataModule"
|
||||||
|
hparams:
|
||||||
|
batch_size: 64
|
||||||
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
|
|
||||||
|
|
||||||
|
# to execute this run:
|
||||||
|
# python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST
|
||||||
|
ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||||
|
seed: 1234
|
||||||
|
trainer:
|
||||||
|
args:
|
||||||
|
min_epochs: 1 # train for at least this many epochs (denies early stopping)
|
||||||
|
max_epochs: 10
|
||||||
|
gradient_clip_val: 0.5 # gradient clipping (helps with exploding gradient issues)
|
||||||
|
accumulate_grad_batches: 2 # perform optimization step after accumulating gradient from 2 batches
|
||||||
|
fast_dev_run: False # execute 1 training, 1 validation and 1 test epoch only
|
||||||
|
limit_train_batches: 0.8 # train only on 80% of training data
|
||||||
|
limit_val_batches: 1.0 # validate on 100% of validation data
|
||||||
|
limit_test_batches: 1.0 # test on 100% of test data
|
||||||
|
val_check_interval: 0.5 # perform twice per epoch
|
||||||
|
model:
|
||||||
|
load_from:
|
||||||
|
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||||
|
model_class: "LitModel"
|
||||||
|
hparams: # you can add here any parameters you want and then read them in model!
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.00001
|
||||||
input_size: 784 # img size is 1*28*28
|
input_size: 784 # img size is 1*28*28
|
||||||
output_size: 10 # there are 10 digit classes
|
output_size: 10 # there are 10 digit classes
|
||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
dataset:
|
datamodule:
|
||||||
datamodule_folder: "mnist_digits_datamodule"
|
load_from:
|
||||||
batch_size: 64
|
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
||||||
train_val_split_ratio: 0.9
|
datamodule_class: "MNISTDataModule"
|
||||||
num_workers: 1
|
hparams: # you can add here any parameters you want and then read them in datamodule!
|
||||||
pin_memory: False
|
|
||||||
|
|
||||||
|
|
||||||
MNIST_CLASSIFIER_V2:
|
|
||||||
trainer:
|
|
||||||
min_epochs: 1
|
|
||||||
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
|
|
||||||
weight_decay: 0.00001
|
|
||||||
input_size: 784
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 512
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
dataset:
|
|
||||||
datamodule_folder: "mnist_digits_datamodule"
|
|
||||||
batch_size: 256
|
batch_size: 256
|
||||||
train_val_split_ratio: 0.9
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
num_workers: 1
|
num_workers: 1 # num of processes used for loading data in parallel
|
||||||
pin_memory: False
|
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
|
||||||
callbacks:
|
# the following sections of config are optional and can be removed:
|
||||||
ConfusionMatrixLoggerCallback:
|
wandb: # Weights&Biases run options
|
||||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
group: ""
|
||||||
MetricsHeatmapLoggerCallback:
|
job_type: "train"
|
||||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
|
||||||
wandb:
|
|
||||||
group: None
|
|
||||||
tags: ["v2", "uwu"]
|
tags: ["v2", "uwu"]
|
||||||
notes: "This is example run."
|
notes: "This is example run."
|
||||||
|
callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py
|
||||||
|
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
|
||||||
|
monitor: "val_acc"
|
||||||
|
patience: 5
|
||||||
|
mode: "max"
|
||||||
|
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
|
||||||
|
monitor: "val_acc"
|
||||||
|
save_top_k: 1
|
||||||
|
save_last: True
|
||||||
|
mode: "max"
|
||||||
|
ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py
|
||||||
|
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||||
|
MetricsHeatmapWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py
|
||||||
|
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||||
resume_training:
|
resume_training:
|
||||||
checkpoint_path: None
|
checkpoint_path: None # path to your checkpoint
|
||||||
wandb_run_id: None
|
wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
from pytorch_lightning import Callback
|
||||||
|
|
||||||
|
|
||||||
|
class ExampleCallback(Callback):
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def on_init_start(self, trainer):
|
||||||
|
print('Starting to initialize trainer!')
|
||||||
|
|
||||||
|
def on_init_end(self, trainer):
|
||||||
|
print('Trainer is initialized now.')
|
||||||
|
|
||||||
|
def on_train_end(self, trainer, pl_module):
|
||||||
|
print('Do something when training ends.')
|
||||||
|
|
||||||
|
|
||||||
|
class UnfreezeModelCallback(Callback):
|
||||||
|
"""
|
||||||
|
Unfreeze model after a few epochs.
|
||||||
|
"""
|
||||||
|
def __init__(self, wait_epochs=5):
|
||||||
|
self.wait_epochs = wait_epochs
|
||||||
|
|
||||||
|
def on_epoch_end(self, trainer, pl_module):
|
||||||
|
if trainer.current_epoch == self.wait_epochs:
|
||||||
|
for param in pl_module.model.model.parameters():
|
||||||
|
param.requires_grad = True
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
# YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS
|
# YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS
|
||||||
|
|
||||||
from argparse import ArgumentParser
|
from argparse import ArgumentParser
|
||||||
from train import train
|
import train
|
||||||
import wandb
|
import wandb
|
||||||
import yaml
|
import yaml
|
||||||
import os
|
import os
|
||||||
@@ -18,25 +18,17 @@ def main(project_config_path, run_configs_path):
|
|||||||
|
|
||||||
# EXECUTE ALL RUNS ONE AFTER THE OTHER
|
# EXECUTE ALL RUNS ONE AFTER THE OTHER
|
||||||
for conf_name in run_configs:
|
for conf_name in run_configs:
|
||||||
print()
|
print(f"\nEXECUTING RUN: {conf_name}\n")
|
||||||
print("EXECUTING RUN:", conf_name)
|
train.train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
|
||||||
print("CONFIG:")
|
|
||||||
for section in run_configs[conf_name]:
|
|
||||||
print(" " + section + ":")
|
|
||||||
for key in run_configs[conf_name][section]:
|
|
||||||
print(" " + key + ":", run_configs[conf_name][section][key])
|
|
||||||
print()
|
|
||||||
|
|
||||||
train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
|
|
||||||
wandb.finish()
|
wandb.finish()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
parser = ArgumentParser()
|
||||||
parser.add_argument("-p", "--project_config_path", type=str,
|
parser.add_argument("-p", "--project_config_path", type=str,
|
||||||
default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "project_config.yaml"))
|
default=os.path.join(train.BASE_DIR, "project_config.yaml"))
|
||||||
parser.add_argument("-r", "--run_configs_path", type=str,
|
parser.add_argument("-r", "--run_configs_path", type=str,
|
||||||
default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "run_configs.yaml"))
|
default=os.path.join(train.BASE_DIR, "run_configs.yaml"))
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path)
|
main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path)
|
||||||
@@ -6,7 +6,7 @@ import train
|
|||||||
|
|
||||||
|
|
||||||
# Choose which run config to optimize
|
# Choose which run config to optimize
|
||||||
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1"
|
RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
|
||||||
|
|
||||||
# Load configs
|
# Load configs
|
||||||
project_config = train.load_config("project_config.yaml")
|
project_config = train.load_config("project_config.yaml")
|
||||||
@@ -20,12 +20,12 @@ 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":
|
||||||
continue
|
continue
|
||||||
elif key in run_config["trainer"].keys():
|
elif key in run_config["trainer"]["args"]:
|
||||||
run_config["trainer"][key] = value
|
run_config["trainer"]["args"][key] = value
|
||||||
elif key in run_config["model"].keys():
|
elif key in run_config["model"]["hparams"]:
|
||||||
run_config["model"][key] = value
|
run_config["model"]["hparams"][key] = value
|
||||||
elif key in run_config["dataset"].keys():
|
elif key in run_config["datamodule"]["hparams"]:
|
||||||
run_config["dataset"][key] = value
|
run_config["datamodule"]["hparams"][key] = value
|
||||||
|
|
||||||
# Execute run
|
# Execute run
|
||||||
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
|
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
# pytorch lightning imports
|
||||||
|
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
|
||||||
|
from pytorch_lightning.profiler import SimpleProfiler
|
||||||
|
import pytorch_lightning as pl
|
||||||
|
|
||||||
|
# normal imports
|
||||||
|
from typing import List, Tuple
|
||||||
|
import importlib.util
|
||||||
|
import os
|
||||||
|
|
||||||
|
# template utils imports
|
||||||
|
from pytorch_lightning import callbacks as lightning_callbacks
|
||||||
|
from template_utils import callbacks as custom_callbacks
|
||||||
|
from template_utils import wandb_callbacks
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]:
|
||||||
|
"""
|
||||||
|
Convert all config paths to absolute paths relatively to base_dir and normalize them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if not os.path.isabs(project_config["data_dir"]):
|
||||||
|
project_config["data_dir"] = \
|
||||||
|
os.path.normpath(os.path.join(base_dir, project_config["data_dir"]))
|
||||||
|
|
||||||
|
if not os.path.isabs(project_config["logs_dir"]):
|
||||||
|
project_config["logs_dir"] =\
|
||||||
|
os.path.normpath(os.path.join(base_dir, project_config["logs_dir"]))
|
||||||
|
|
||||||
|
if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
|
||||||
|
run_config["model"]["load_from"]["model_path"] = \
|
||||||
|
os.path.normpath(os.path.join(base_dir, run_config["model"]["load_from"]["model_path"]))
|
||||||
|
|
||||||
|
if not os.path.isabs(run_config["datamodule"]["load_from"]["datamodule_path"]):
|
||||||
|
run_config["datamodule"]["load_from"]["datamodule_path"] = \
|
||||||
|
os.path.normpath(os.path.join(base_dir, run_config["datamodule"]["load_from"]["datamodule_path"]))
|
||||||
|
|
||||||
|
return project_config, run_config
|
||||||
|
|
||||||
|
|
||||||
|
def init_model(model_config: dict) -> pl.LightningModule:
|
||||||
|
"""
|
||||||
|
Load LightningModule from path specified in run config.
|
||||||
|
"""
|
||||||
|
|
||||||
|
model_path = model_config["load_from"]["model_path"]
|
||||||
|
model_class = model_config["load_from"]["model_class"]
|
||||||
|
|
||||||
|
assert os.path.isfile(model_path), f"incorrect model path: {model_path}"
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("lightning_model", model_path)
|
||||||
|
lightning_module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(lightning_module)
|
||||||
|
|
||||||
|
assert hasattr(lightning_module, model_class), \
|
||||||
|
f"model class {model_class} doesn't exists in file {model_path}"
|
||||||
|
|
||||||
|
LitModel = getattr(lightning_module, model_class)
|
||||||
|
|
||||||
|
assert issubclass(LitModel, pl.LightningModule), \
|
||||||
|
f"specified model class {model_class} is not a LightningModule"
|
||||||
|
|
||||||
|
model = LitModel(hparams=model_config["hparams"])
|
||||||
|
|
||||||
|
return model
|
||||||
|
|
||||||
|
|
||||||
|
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||||
|
"""
|
||||||
|
Load LightningDataModule from path specified in run config.
|
||||||
|
"""
|
||||||
|
|
||||||
|
datamodule_path = datamodule_config["load_from"]["datamodule_path"]
|
||||||
|
datamodule_class = datamodule_config["load_from"]["datamodule_class"]
|
||||||
|
|
||||||
|
assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}"
|
||||||
|
|
||||||
|
spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path)
|
||||||
|
lightning_module = importlib.util.module_from_spec(spec)
|
||||||
|
spec.loader.exec_module(lightning_module)
|
||||||
|
|
||||||
|
assert hasattr(lightning_module, datamodule_class), \
|
||||||
|
f"datamodule class {datamodule_class} doesn't exists in file {datamodule_path}"
|
||||||
|
|
||||||
|
DataModule = getattr(lightning_module, datamodule_class)
|
||||||
|
|
||||||
|
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||||
|
f"specified datamodule class {datamodule_class} is not a LightningDataModule"
|
||||||
|
|
||||||
|
datamodule = DataModule(data_dir=data_dir, hparams=datamodule_config["hparams"])
|
||||||
|
datamodule.prepare_data()
|
||||||
|
datamodule.setup()
|
||||||
|
|
||||||
|
return datamodule
|
||||||
|
|
||||||
|
|
||||||
|
def init_trainer(project_config: dict,
|
||||||
|
run_config: dict,
|
||||||
|
callbacks: List[pl.Callback],
|
||||||
|
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||||
|
"""
|
||||||
|
Initialize PyTorch Lightning Trainer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Get path to checkpoint that 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)
|
||||||
|
|
||||||
|
trainer = pl.Trainer(
|
||||||
|
# whether to use gpu and how many
|
||||||
|
gpus=project_config["num_of_gpus"],
|
||||||
|
|
||||||
|
# experiment logging
|
||||||
|
logger=loggers,
|
||||||
|
|
||||||
|
# useful callbacks
|
||||||
|
callbacks=callbacks,
|
||||||
|
|
||||||
|
# resume training from checkpoint if it was set in the run config
|
||||||
|
resume_from_checkpoint=resume_from_checkpoint
|
||||||
|
if resume_from_checkpoint != "None"
|
||||||
|
and resume_from_checkpoint != "False"
|
||||||
|
and resume_from_checkpoint is not False
|
||||||
|
else None,
|
||||||
|
|
||||||
|
# print related
|
||||||
|
progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
|
||||||
|
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
|
||||||
|
weights_summary=project_config["printing"]["weights_summary"],
|
||||||
|
|
||||||
|
# number of validation sanity checks
|
||||||
|
num_sanity_val_steps=3,
|
||||||
|
|
||||||
|
# default log dir if no logger is found
|
||||||
|
default_root_dir=os.path.join(project_config["logs_dir"], "lightning_logs"),
|
||||||
|
|
||||||
|
# insert all other trainer args specified in run config
|
||||||
|
**run_config["trainer"]["args"]
|
||||||
|
)
|
||||||
|
|
||||||
|
return trainer
|
||||||
|
|
||||||
|
|
||||||
|
def init_callbacks(project_config: dict,
|
||||||
|
run_config: dict,
|
||||||
|
use_wandb: bool,
|
||||||
|
base_dir: str) -> List[pl.Callback]:
|
||||||
|
"""
|
||||||
|
Initialize default callbacks and callbacks specified in run config.
|
||||||
|
"""
|
||||||
|
|
||||||
|
default_callbacks = project_config.get("default_callbacks", {})
|
||||||
|
run_callbacks = run_config.get("callbacks", {})
|
||||||
|
|
||||||
|
# namespaces in which callbacks will be searched for
|
||||||
|
namespaces = [
|
||||||
|
lightning_callbacks,
|
||||||
|
custom_callbacks,
|
||||||
|
wandb_callbacks,
|
||||||
|
]
|
||||||
|
|
||||||
|
callbacks = []
|
||||||
|
|
||||||
|
all_callback_configs = {}
|
||||||
|
for callback_config in default_callbacks:
|
||||||
|
all_callback_configs[callback_config] = default_callbacks[callback_config]
|
||||||
|
for callback_config in run_callbacks:
|
||||||
|
all_callback_configs[callback_config] = run_callbacks[callback_config]
|
||||||
|
|
||||||
|
for callback_config in all_callback_configs:
|
||||||
|
found = False
|
||||||
|
for namespace in namespaces:
|
||||||
|
if hasattr(namespace, callback_config):
|
||||||
|
callback_class = getattr(namespace, callback_config)
|
||||||
|
callbacks.append(callback_class(**all_callback_configs[callback_config]))
|
||||||
|
found = True
|
||||||
|
break
|
||||||
|
if not found:
|
||||||
|
raise ModuleNotFoundError(f"Callback '{callback_config}' not found.")
|
||||||
|
|
||||||
|
if use_wandb:
|
||||||
|
callbacks.append(
|
||||||
|
wandb_callbacks.SaveCodeToWandbCallback(
|
||||||
|
base_dir=base_dir,
|
||||||
|
wandb_save_dir=project_config["logs_dir"],
|
||||||
|
run_config=run_config
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return callbacks
|
||||||
|
|
||||||
|
|
||||||
|
def init_loggers(project_config: dict,
|
||||||
|
run_config: dict,
|
||||||
|
model: pl.LightningModule,
|
||||||
|
datamodule: pl.LightningDataModule,
|
||||||
|
use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
|
||||||
|
"""
|
||||||
|
Initialize loggers.
|
||||||
|
"""
|
||||||
|
loggers = []
|
||||||
|
if use_wandb:
|
||||||
|
wandb_logger = init_wandb_logger(
|
||||||
|
project_config=project_config,
|
||||||
|
run_config=run_config,
|
||||||
|
model=model,
|
||||||
|
datamodule=datamodule
|
||||||
|
)
|
||||||
|
if wandb_logger:
|
||||||
|
loggers.append(wandb_logger)
|
||||||
|
|
||||||
|
return loggers
|
||||||
|
|
||||||
|
|
||||||
|
def init_wandb_logger(project_config: dict,
|
||||||
|
run_config: dict,
|
||||||
|
model: pl.LightningModule,
|
||||||
|
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
||||||
|
"""
|
||||||
|
Initialize Weights&Biases logger.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if "loggers" not in project_config or "wandb" not in project_config["loggers"]:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
||||||
|
# instead of auto-creating a new run
|
||||||
|
os.environ["WANDB_RESUME"] = "must"
|
||||||
|
|
||||||
|
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=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"),
|
||||||
|
tags=run_config.get("wandb", {}).get("tags", []),
|
||||||
|
notes=run_config.get("wandb", {}).get("notes", ""),
|
||||||
|
|
||||||
|
# resume run only if ckpt was set in the run config
|
||||||
|
id=wandb_run_id
|
||||||
|
if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None
|
||||||
|
and resume_from_checkpoint is not False and wandb_run_id is not False
|
||||||
|
else None,
|
||||||
|
|
||||||
|
save_dir=project_config["logs_dir"],
|
||||||
|
save_code=False
|
||||||
|
)
|
||||||
|
|
||||||
|
if not os.path.exists(project_config["logs_dir"]):
|
||||||
|
os.makedirs(project_config["logs_dir"])
|
||||||
|
|
||||||
|
if hasattr(model, 'model'):
|
||||||
|
if project_config["loggers"]["wandb"]["log_gradients"]:
|
||||||
|
wandb_logger.watch(model.model, log='gradients')
|
||||||
|
else:
|
||||||
|
wandb_logger.watch(model.model, log=None)
|
||||||
|
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
||||||
|
else:
|
||||||
|
if project_config["loggers"]["wandb"]["log_gradients"]:
|
||||||
|
wandb_logger.watch(model, log='gradients')
|
||||||
|
else:
|
||||||
|
wandb_logger.watch(model, log=None)
|
||||||
|
|
||||||
|
wandb_logger.log_hyperparams({
|
||||||
|
"optimizer": model.configure_optimizers().__class__.__name__,
|
||||||
|
"train_size": len(datamodule.data_train)
|
||||||
|
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||||
|
"val_size": len(datamodule.data_val)
|
||||||
|
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
||||||
|
"test_size": len(datamodule.data_test)
|
||||||
|
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
||||||
|
})
|
||||||
|
wandb_logger.log_hyperparams({"num_of_gpus": project_config["num_of_gpus"]})
|
||||||
|
wandb_logger.log_hyperparams(run_config["trainer"]["args"])
|
||||||
|
wandb_logger.log_hyperparams(run_config["model"]["hparams"])
|
||||||
|
wandb_logger.log_hyperparams(run_config["model"]["load_from"])
|
||||||
|
wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"])
|
||||||
|
wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"])
|
||||||
|
|
||||||
|
return wandb_logger
|
||||||
|
|
||||||
|
|
||||||
|
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
|
||||||
|
"""Initialize tensorboard logger"""
|
||||||
|
# TODO
|
||||||
|
return None
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
from data_modules.mnist_digits_datamodule import transforms
|
from datamodules.mnist_datamodule import transforms
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
# the LitModel you import should be the same as the one you used for training!
|
# the LitModel you import should be the same as the one you used for training!
|
||||||
@@ -1,27 +1,14 @@
|
|||||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
from sklearn.metrics import precision_score, recall_score, f1_score
|
||||||
import pytorch_lightning as pl
|
from pytorch_lightning.loggers import WandbLogger
|
||||||
|
from wandb.sdk.wandb_run import Run as wandb_run
|
||||||
|
from pytorch_lightning import Callback
|
||||||
from shutil import copy
|
from shutil import copy
|
||||||
import inspect
|
|
||||||
import torch
|
import torch
|
||||||
import wandb
|
import wandb
|
||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
class ExampleCallback(pl.Callback):
|
class SaveOnnxModelToWandbCallback(Callback):
|
||||||
def __init__(self):
|
|
||||||
pass
|
|
||||||
|
|
||||||
def on_init_start(self, trainer):
|
|
||||||
print('Starting to initialize trainer!')
|
|
||||||
|
|
||||||
def on_init_end(self, trainer):
|
|
||||||
print('Trainer is initialized now.')
|
|
||||||
|
|
||||||
def on_train_end(self, trainer, pl_module):
|
|
||||||
print('Do something when training ends.')
|
|
||||||
|
|
||||||
|
|
||||||
class SaveOnnxModelToWandbCallback(pl.Callback):
|
|
||||||
"""
|
"""
|
||||||
Save model in .onnx format and upload to wandb.
|
Save model in .onnx format and upload to wandb.
|
||||||
Might crash since not all models are compatible with onnx.
|
Might crash since not all models are compatible with onnx.
|
||||||
@@ -44,7 +31,7 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
|
|||||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||||
|
|
||||||
|
|
||||||
class ImagePredictionLoggerCallback(pl.Callback):
|
class ImagePredictionWandbLoggerCallback(Callback):
|
||||||
"""
|
"""
|
||||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||||
"""
|
"""
|
||||||
@@ -71,20 +58,7 @@ class ImagePredictionLoggerCallback(pl.Callback):
|
|||||||
]}, commit=False)
|
]}, commit=False)
|
||||||
|
|
||||||
|
|
||||||
class UnfreezeModelCallback(pl.Callback):
|
class MetricsHeatmapWandbLoggerCallback(Callback):
|
||||||
"""
|
|
||||||
Unfreeze model after a few epochs.
|
|
||||||
"""
|
|
||||||
def __init__(self, wait_epochs=5):
|
|
||||||
self.wait_epochs = wait_epochs
|
|
||||||
|
|
||||||
def on_epoch_end(self, trainer, pl_module):
|
|
||||||
if trainer.current_epoch == self.wait_epochs:
|
|
||||||
for param in pl_module.model.model.parameters():
|
|
||||||
param.requires_grad = True
|
|
||||||
|
|
||||||
|
|
||||||
class MetricsHeatmapLoggerCallback(pl.Callback):
|
|
||||||
"""
|
"""
|
||||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
@@ -116,8 +90,13 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
|||||||
r = recall_score(self.preds, self.targets, average=None)
|
r = recall_score(self.preds, self.targets, average=None)
|
||||||
p = precision_score(self.preds, self.targets, average=None)
|
p = precision_score(self.preds, self.targets, average=None)
|
||||||
|
|
||||||
trainer.logger.experiment.log({
|
logger = None
|
||||||
f"f1_p_r_heatmap_{trainer.current_epoch}": wandb.plots.HeatMap(
|
for some_logger in trainer.logger.experiment:
|
||||||
|
if isinstance(some_logger, wandb_run):
|
||||||
|
logger = some_logger
|
||||||
|
|
||||||
|
logger.log({
|
||||||
|
f"f1_p_r_heatmap_{trainer.current_epoch}_{logger.id}": wandb.plots.HeatMap(
|
||||||
x_labels=self.class_names,
|
x_labels=self.class_names,
|
||||||
y_labels=["f1", "precision", "recall"],
|
y_labels=["f1", "precision", "recall"],
|
||||||
matrix_values=[f1, p, r],
|
matrix_values=[f1, p, r],
|
||||||
@@ -128,7 +107,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
|||||||
self.targets = []
|
self.targets = []
|
||||||
|
|
||||||
|
|
||||||
class ConfusionMatrixLoggerCallback(pl.Callback):
|
class ConfusionMatrixWandbLoggerCallback(Callback):
|
||||||
"""
|
"""
|
||||||
Generate Confusion Matrix.
|
Generate Confusion Matrix.
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
@@ -157,7 +136,12 @@ class ConfusionMatrixLoggerCallback(pl.Callback):
|
|||||||
self.preds = torch.cat(self.preds).tolist()
|
self.preds = torch.cat(self.preds).tolist()
|
||||||
self.targets = torch.cat(self.targets).tolist()
|
self.targets = torch.cat(self.targets).tolist()
|
||||||
|
|
||||||
trainer.logger.experiment.log({
|
logger = None
|
||||||
|
for some_logger in trainer.logger.experiment:
|
||||||
|
if isinstance(some_logger, wandb_run):
|
||||||
|
logger = some_logger
|
||||||
|
|
||||||
|
logger.log({
|
||||||
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
||||||
self.preds,
|
self.preds,
|
||||||
self.targets,
|
self.targets,
|
||||||
@@ -168,18 +152,18 @@ class ConfusionMatrixLoggerCallback(pl.Callback):
|
|||||||
self.targets = []
|
self.targets = []
|
||||||
|
|
||||||
|
|
||||||
class SaveCodeToWandbCallback(pl.Callback):
|
class SaveCodeToWandbCallback(Callback):
|
||||||
"""
|
"""
|
||||||
Upload specified code files to wandb at the beginning of the run.
|
Upload specified code files to wandb at the beginning of the run.
|
||||||
"""
|
"""
|
||||||
def __init__(self, base_dir, wandb_save_dir, run_config):
|
def __init__(self, base_dir, wandb_save_dir, run_config):
|
||||||
self.base_dir = base_dir
|
self.base_dir = base_dir
|
||||||
self.wandb_save_dir = wandb_save_dir
|
self.wandb_save_dir = wandb_save_dir
|
||||||
self.model_folder = run_config["model"]["model_folder"]
|
self.model_folder = run_config["model"]["load_from"]["model_path"]
|
||||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
|
||||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||||
"utils/callbacks.py",
|
"template_utils/callbacks.py",
|
||||||
"utils/init_utils.py",
|
"template_utils/initializers.py",
|
||||||
"train.py",
|
"train.py",
|
||||||
"project_config.yaml",
|
"project_config.yaml",
|
||||||
"run_configs.yaml",
|
"run_configs.yaml",
|
||||||
@@ -188,41 +172,4 @@ class SaveCodeToWandbCallback(pl.Callback):
|
|||||||
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."""
|
||||||
# upload additional files
|
# upload additional files
|
||||||
for file in self.additional_files_to_be_saved:
|
pass
|
||||||
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(src_path, dst_path)
|
|
||||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
|
||||||
|
|
||||||
# upload model files
|
|
||||||
for filename in os.listdir(os.path.join(self.base_dir, "models", self.model_folder)):
|
|
||||||
|
|
||||||
if filename.endswith('.py'):
|
|
||||||
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)
|
|
||||||
|
|
||||||
copy(src_path, dst_path)
|
|
||||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
|
||||||
|
|
||||||
# upload datamodule files
|
|
||||||
for filename in os.listdir(os.path.join(self.base_dir, "data_modules", self.datamodule_folder)):
|
|
||||||
|
|
||||||
if filename.endswith('.py'):
|
|
||||||
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)
|
|
||||||
|
|
||||||
copy(src_path, dst_path)
|
|
||||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
|
||||||
+86
-30
@@ -1,66 +1,104 @@
|
|||||||
from pytorch_lightning.loggers import WandbLogger
|
# pytorch lightning imports
|
||||||
|
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
||||||
|
from pytorch_lightning.loggers import LightningLoggerBase
|
||||||
|
import torch
|
||||||
|
|
||||||
|
# normal imports
|
||||||
from argparse import ArgumentParser
|
from argparse import ArgumentParser
|
||||||
import pytorch_lightning as pl
|
|
||||||
from typing import List
|
from typing import List
|
||||||
|
import pprint
|
||||||
import yaml
|
import yaml
|
||||||
import os
|
import os
|
||||||
|
|
||||||
# utils
|
# template utils imports
|
||||||
from utils.init_utils import init_lit_model, init_data_module, init_trainer, init_callbacks, init_wandb_logger
|
from template_utils.initializers import (
|
||||||
|
normalize_config_paths,
|
||||||
|
init_model,
|
||||||
|
init_datamodule,
|
||||||
|
init_callbacks,
|
||||||
|
init_loggers,
|
||||||
|
init_trainer
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Everything will be loaded relatively to placement of 'train.py' file!
|
||||||
|
BASE_DIR: str = os.path.dirname(__file__)
|
||||||
|
|
||||||
|
|
||||||
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||||
|
|
||||||
|
# Set global PyTorch seed
|
||||||
|
if "seed" in run_config:
|
||||||
|
torch.manual_seed(run_config["seed"])
|
||||||
|
|
||||||
|
# Covert paths to absolute and normalize them
|
||||||
|
project_config, run_config = normalize_config_paths(
|
||||||
|
project_config=project_config,
|
||||||
|
run_config=run_config,
|
||||||
|
base_dir=BASE_DIR
|
||||||
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
lit_model: pl.LightningModule = init_lit_model(hparams=run_config["model"])
|
model: LightningModule = init_model(
|
||||||
|
model_config=run_config["model"]
|
||||||
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
|
datamodule: LightningDataModule = init_datamodule(
|
||||||
|
datamodule_config=run_config["datamodule"],
|
||||||
|
data_dir=project_config["data_dir"]
|
||||||
|
)
|
||||||
|
|
||||||
# Init Weights&Biases logger
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
logger: pl.loggers.WandbLogger = init_wandb_logger(
|
callbacks: List[Callback] = init_callbacks(
|
||||||
project_config=project_config,
|
project_config=project_config,
|
||||||
run_config=run_config,
|
run_config=run_config,
|
||||||
lit_model=lit_model,
|
use_wandb=use_wandb,
|
||||||
|
base_dir=BASE_DIR
|
||||||
|
)
|
||||||
|
|
||||||
|
# Init PyTorch Lightning loggers ⚡
|
||||||
|
loggers: List[LightningLoggerBase] = init_loggers(
|
||||||
|
project_config=project_config,
|
||||||
|
run_config=run_config,
|
||||||
|
model=model,
|
||||||
datamodule=datamodule,
|
datamodule=datamodule,
|
||||||
log_path=os.path.join(os.path.dirname(__file__), "logs/")
|
|
||||||
) if use_wandb else None
|
|
||||||
|
|
||||||
# Init callbacks
|
|
||||||
callbacks: List[pl.Callback] = init_callbacks(
|
|
||||||
project_config=project_config,
|
|
||||||
run_config=run_config,
|
|
||||||
use_wandb=use_wandb
|
use_wandb=use_wandb
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: pl.Trainer = init_trainer(
|
trainer: Trainer = init_trainer(
|
||||||
project_config=project_config,
|
project_config=project_config,
|
||||||
run_config=run_config,
|
run_config=run_config,
|
||||||
logger=logger,
|
callbacks=callbacks,
|
||||||
callbacks=callbacks
|
loggers=loggers
|
||||||
)
|
)
|
||||||
|
|
||||||
# Evaluate model on test set before training
|
# Evaluate model on test set before training
|
||||||
# trainer.test(model=lit_model, datamodule=datamodule)
|
# trainer.test(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
# Train the model
|
# Train the model
|
||||||
trainer.fit(model=lit_model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
# Evaluate model on test set after training
|
# Evaluate model on test set after training
|
||||||
trainer.test()
|
trainer.test()
|
||||||
|
|
||||||
|
|
||||||
def load_config(filename):
|
def load_config(path):
|
||||||
path = os.path.join(os.path.dirname(__file__), filename)
|
abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path
|
||||||
with open(path, "r") as ymlfile:
|
with open(abs_path, "r") as ymlfile:
|
||||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
def main(run_config_name: str, use_wandb: bool):
|
def main(project_config_path: str, run_configs_path: str, run_config_name: str, use_wandb: bool):
|
||||||
# Load configs
|
# Load configs
|
||||||
project_config: dict = load_config("project_config.yaml")
|
project_config: dict = load_config(path=project_config_path)
|
||||||
run_config: dict = load_config("run_configs.yaml")[run_config_name]
|
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
||||||
|
|
||||||
|
print("EXECUTING RUN:", run_config_name)
|
||||||
|
# pprint.pprint(run_config, sort_dicts=False)
|
||||||
|
print()
|
||||||
|
|
||||||
# Train model
|
# Train model
|
||||||
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||||
@@ -68,9 +106,27 @@ def main(run_config_name: str, use_wandb: bool):
|
|||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
parser = ArgumentParser()
|
||||||
parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V2")
|
parser.add_argument("--project_config_path",
|
||||||
parser.add_argument("-n", "--no_wandb", dest='use_wandb', action='store_false')
|
type=str,
|
||||||
|
default="project_config.yaml",
|
||||||
|
help="Path to file containing your project configuration")
|
||||||
|
parser.add_argument("--run_configs_path",
|
||||||
|
type=str,
|
||||||
|
default="run_configs.yaml",
|
||||||
|
help="Path to file containing your run configurations")
|
||||||
|
parser.add_argument("--run_config_name",
|
||||||
|
type=str,
|
||||||
|
default="SIMPLE_CONFIG_EXAMPLE_MNIST",
|
||||||
|
help="Name of you configuration in run_configs.yaml")
|
||||||
|
parser.add_argument("--no_wandb",
|
||||||
|
dest='use_wandb',
|
||||||
|
action='store_false',
|
||||||
|
help="Whether to use Weights&Biases or not")
|
||||||
|
|
||||||
parser.set_defaults(use_wandb=True)
|
parser.set_defaults(use_wandb=True)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
main(run_config_name=args.run_config, use_wandb=args.use_wandb)
|
main(project_config_path=args.project_config_path,
|
||||||
|
run_configs_path=args.run_configs_path,
|
||||||
|
run_config_name=args.run_config_name,
|
||||||
|
use_wandb=args.use_wandb)
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
|
||||||
from pytorch_lightning.profiler import SimpleProfiler
|
|
||||||
from pytorch_lightning.loggers import WandbLogger
|
|
||||||
import pytorch_lightning as pl
|
|
||||||
from typing import List
|
|
||||||
import utils.callbacks
|
|
||||||
import importlib
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
def init_lit_model(hparams: dict) -> pl.LightningModule:
|
|
||||||
"""Load LitModel from folder specified in run config."""
|
|
||||||
|
|
||||||
module_path = "models." + hparams["model_folder"] + ".lightning_module"
|
|
||||||
lit_model = importlib.import_module(module_path).LitModel(hparams=hparams)
|
|
||||||
|
|
||||||
return lit_model
|
|
||||||
|
|
||||||
|
|
||||||
def init_data_module(hparams: dict) -> pl.LightningDataModule:
|
|
||||||
"""Load DataModule from folder specified in run config."""
|
|
||||||
|
|
||||||
module_path = "data_modules." + hparams["datamodule_folder"] + ".datamodule"
|
|
||||||
hparams["data_dir"] = os.path.join(os.path.dirname(os.path.dirname(__file__)), "data")
|
|
||||||
datamodule = importlib.import_module(module_path).DataModule(hparams=hparams)
|
|
||||||
datamodule.prepare_data()
|
|
||||||
datamodule.setup()
|
|
||||||
|
|
||||||
return datamodule
|
|
||||||
|
|
||||||
|
|
||||||
def init_trainer(project_config: dict, run_config: dict, logger, callbacks: list) -> pl.Trainer:
|
|
||||||
"""Initialize PyTorch Lightning Trainer"""
|
|
||||||
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
trainer = pl.Trainer(
|
|
||||||
# whether to use gpu and how many
|
|
||||||
gpus=project_config["num_of_gpus"],
|
|
||||||
|
|
||||||
# experiment logging
|
|
||||||
logger=logger,
|
|
||||||
|
|
||||||
# useful callbacks
|
|
||||||
callbacks=callbacks,
|
|
||||||
|
|
||||||
# resume training from checkpoint if it was set in the run config
|
|
||||||
resume_from_checkpoint=resume_from_checkpoint
|
|
||||||
if resume_from_checkpoint != "None"
|
|
||||||
and resume_from_checkpoint != "False"
|
|
||||||
and resume_from_checkpoint is not False
|
|
||||||
else None,
|
|
||||||
|
|
||||||
# print related
|
|
||||||
progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"],
|
|
||||||
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
|
|
||||||
weights_summary=project_config["printing"]["weights_summary"],
|
|
||||||
|
|
||||||
# number of validation sanity checks
|
|
||||||
num_sanity_val_steps=3,
|
|
||||||
|
|
||||||
# default log dir if no logger is found
|
|
||||||
default_root_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs/lightning_logs"),
|
|
||||||
|
|
||||||
# insert all other trainer parameters specified in run config
|
|
||||||
**run_config["trainer"]
|
|
||||||
)
|
|
||||||
|
|
||||||
return trainer
|
|
||||||
|
|
||||||
|
|
||||||
def init_callbacks(project_config: dict, run_config: dict, use_wandb: bool) -> List[pl.Callback]:
|
|
||||||
"""Initialize default callbacks ana callbacks specified in run config."""
|
|
||||||
|
|
||||||
callbacks = [
|
|
||||||
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"],
|
|
||||||
)
|
|
||||||
]
|
|
||||||
if use_wandb:
|
|
||||||
callbacks.append(
|
|
||||||
utils.callbacks.SaveCodeToWandbCallback(
|
|
||||||
base_dir=os.path.dirname(os.path.dirname(__file__)),
|
|
||||||
wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"),
|
|
||||||
run_config=run_config
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
callbacks_config = run_config.get("callbacks", {})
|
|
||||||
for conf in callbacks_config:
|
|
||||||
callback = getattr(utils.callbacks, conf)
|
|
||||||
callbacks.append(callback(**callbacks_config[conf]))
|
|
||||||
|
|
||||||
return callbacks
|
|
||||||
|
|
||||||
|
|
||||||
def init_wandb_logger(project_config: dict,
|
|
||||||
run_config: dict,
|
|
||||||
lit_model: pl.LightningModule,
|
|
||||||
datamodule: pl.LightningDataModule,
|
|
||||||
log_path: str = "logs/") -> pl.loggers.WandbLogger:
|
|
||||||
"""Initialize Weights&Biases logger."""
|
|
||||||
|
|
||||||
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
|
||||||
# instead of auto-creating a new run
|
|
||||||
os.environ["WANDB_RESUME"] = "must"
|
|
||||||
|
|
||||||
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=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"),
|
|
||||||
tags=run_config.get("wandb", {}).get("tags", []),
|
|
||||||
notes=run_config.get("wandb", {}).get("notes", ""),
|
|
||||||
|
|
||||||
# resume run only if ckpt was set in the run config
|
|
||||||
id=wandb_run_id
|
|
||||||
if resume_from_checkpoint != "None" and wandb_run_id != "None" and resume_from_checkpoint is not None
|
|
||||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
|
||||||
else None,
|
|
||||||
|
|
||||||
save_dir=log_path,
|
|
||||||
save_code=False
|
|
||||||
)
|
|
||||||
|
|
||||||
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:
|
|
||||||
wandb_logger.watch(lit_model, log=None)
|
|
||||||
|
|
||||||
wandb_logger.log_hyperparams({
|
|
||||||
"model": lit_model.model.__class__.__name__,
|
|
||||||
"optimizer": lit_model.configure_optimizers().__class__.__name__,
|
|
||||||
"train_size": len(datamodule.data_train)
|
|
||||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
|
||||||
"val_size": len(datamodule.data_val)
|
|
||||||
if hasattr(datamodule, 'data_val') and datamodule.data_val is not None else 0,
|
|
||||||
"test_size": len(datamodule.data_test)
|
|
||||||
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
|
||||||
})
|
|
||||||
wandb_logger.log_hyperparams(run_config["trainer"])
|
|
||||||
wandb_logger.log_hyperparams(run_config["model"])
|
|
||||||
wandb_logger.log_hyperparams(run_config["dataset"])
|
|
||||||
|
|
||||||
return wandb_logger
|
|
||||||
|
|
||||||
|
|
||||||
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
|
|
||||||
"""TODO"""
|
|
||||||
return None
|
|
||||||
@@ -5,3 +5,4 @@ pytorch-lightning>=1.0.8
|
|||||||
wandb>=0.10.12
|
wandb>=0.10.12
|
||||||
PyYAML>=5.3.1
|
PyYAML>=5.3.1
|
||||||
scikit-learn>=0.23.2
|
scikit-learn>=0.23.2
|
||||||
|
pandas>=1.1.5
|
||||||
Reference in new issue
Block a user