start redesigning project structure for version 4.0

This commit is contained in:
hobogalaxy committed 2020-12-29 01:48:44 +01:00
1 parent 42652e3752
commit fa8b9ecc16
18 files changed
+136 -126

No files matched your search

+7 -7
View File
@@ -11,12 +11,12 @@ Click on <b>"Use this template"</b> button above to initialize new repository.<b
- ~~Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud~~ (TODO) - ~~Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud~~ (TODO)
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py)) - Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))
- Automates the whole training process, you only need to create model and datamodule and specify them in [run_configs.yaml](project/run_configs.yaml) - Automates the whole training process, you only need to create model and datamodule and specify them in [run_configs.yaml](project/run_configs.yaml)
- Scheduling execution of many runs/experiments ([execute_all_runs.py](project/template_utils/execute_all_runs.py)) - Scheduling execution of many runs/experiments ([execute_all_runs.py](project/template_utils/execute_all_experiments.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/template_utils/callbacks.py)) - Useful example callbacks ([callbacks.py](project/pytorch_modules/lightning_callbacks/custom_callbacks.py))
<br> <br>
@@ -83,7 +83,7 @@ loggers:
default_callbacks: default_callbacks:
ModelCheckpoint: ModelCheckpoint:
monitor: "val_acc" <- name of the logged metric which 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 lightning_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"
EarlyStopping: EarlyStopping:
@@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
max_epochs: 10 max_epochs: 10
model: model:
load_from: load_from:
model_path: "models/simple_mnist_classifier/lightning_module.py" model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py"
model_class: "LitModel" model_class: "LitModel"
hparams: hparams:
lr: 0.001 lr: 0.001
@@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
lin3_size: 128 lin3_size: 128
datamodule: datamodule:
load_from: load_from:
datamodule_path: "datamodules/mnist_datamodule/datamodule.py" datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
datamodule_class: "MNISTDataModule" datamodule_class: "MNISTDataModule"
hparams: hparams:
batch_size: 64 batch_size: 64
@@ -138,9 +138,9 @@ Each run configuration needs to contain sections `trainer`, `model` and `datamod
Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<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 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 model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/pytorch_modules/lightning_models/simple_mnist_classifier.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> 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/pytorch_modules/lightning_datamodules/mnist_datamodule.py)).<br>
<br> <br>
@@ -0,0 +1,59 @@
# to execute this run:
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST_v2
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 validation twice per epoch
model:
load_from:
model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.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
output_size: 10 # there are 10 digit classes
lin1_size: 256
lin2_size: 256
lin3_size: 128
datamodule:
load_from:
datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
datamodule_class: "MNISTDataModule"
hparams: # you can add here any parameters you want and then read them in datamodule!
batch_size: 256
train_val_test_split: [55_000, 5_000, 10_000]
num_workers: 1 # num of processes used for loading data in parallel
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
# the following sections of config are optional and can be removed:
wandb: # Weights&Biases run options
group: ""
job_type: "train"
tags: ["v2", "uwu"]
notes: "This is example run."
callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/custom_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:
checkpoint_path: None # path to your checkpoint
wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
@@ -0,0 +1,28 @@
# to execute this run:
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
seed: 1234
trainer_args:
max_epochs: 10
model:
load_from:
model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py"
model_class: "LitModel"
hparams:
lr: 0.001
weight_decay: 0.00001
input_size: 784
output_size: 10
lin1_size: 256
lin2_size: 256
lin3_size: 128
datamodule:
load_from:
datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
datamodule_class: "MNISTDataModule"
hparams:
batch_size: 64
train_val_test_split: [55_000, 5_000, 10_000]
@@ -1,8 +1,8 @@
from datamodules.mnist_datamodule import transforms from pytorch_modules.lightning_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!
from models.simple_mnist_classifier.lightning_module import LitModel from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
def predict(): def predict():
@@ -10,7 +10,7 @@ def predict():
This method is example of inference with a trained model. This method is example of inference with a trained model.
It Loads trained image classification model from checkpoint. It Loads trained image classification model from checkpoint.
Then it loads example image and predicts its label. Then it loads example image and predicts its label.
Model used in lightning_module.py should be the same as during training!!! Model used in simple_mnist_classifier.py should be the same as during training!!!
""" """
CKPT_PATH = "epoch=0.ckpt" CKPT_PATH = "epoch=0.ckpt"
View File
Whitespace-only changes.
+26 -15
View File
@@ -1,26 +1,37 @@
# set -1 to train on all GPUs abailable, set 0 to train on CPU only # default args passed to Lightning Trainer on every run/experiment
num_of_gpus: -1 # if you specify the same args in experiment config then they will overwrite the ones set here
default_trainer_args:
num_of_gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
progress_bar_refresh_rate: 10 # refresh terminal every 10 batches
weights_summary: "top" # print model summary (alternatively "full")
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) # default loggers initialised on every run/experiment
loggers: # if you specify this section in experiment config then it will be totally overwritten
wandb: default_loggers:
wandb: # Weights&Biases config (just remove this section if you don't want tu ever use Weights&Biases)
use_wandb: True
log_gradients: False # set True to log gradient histograms (avoid this for very big lightning_models)
log_optimizer_name: True
log_train_val_test_data_lengths: True
default_args:
project: "project_template_test" project: "project_template_test"
entity: "kino" # change to your username or name of your team on wandb entity: "kino" # change to your username or name of your team on wandb
log_model: True # set True to automatically upload model checkpoint to wandb cloud after training log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
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 offline: False # set True to store all logs only locally
tensorboard:
use_tensorboard: False
default_args: {}
# default callbacks initialised on every run/experiment # default lightning_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 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 experiment config then it will overwrite the one set here
# 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 # all of the callback parameters will be passed to it on initialization
default_callbacks: default_callbacks:
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
monitor: "val_acc" # name of the logged metric which 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 lightning_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"
EarlyStopping: # name of PyTorch Lightning class for early stopping callback EarlyStopping: # name of PyTorch Lightning class for early stopping callback
@@ -29,11 +40,11 @@ default_callbacks:
mode: "max" # can be "max" or "min" mode: "max" # can be "max" or "min"
# configure things which are printed in terminal # use profiler to print execution time profiling after training ends
printing: profiler:
progress_bar_refresh_rate: 10 # refresh every 10 batches use_profiler: True
weights_summary: "top" # print model summary (alternatively "full") class: "pytorch_lightning.profiler.SimpleProfiler"
profiler: False # set True to print execution time profiling after training ends args: {}
# path to data folder (either absolute or relative to placement of 'train.py' file) # path to data folder (either absolute or relative to placement of 'train.py' file)
@@ -7,7 +7,7 @@ class TestDataset(Dataset):
""" """
Example dataset class for loading images from folder and converting them to monochromatic. Example dataset class for loading images from folder and converting them to monochromatic.
Can be used to perform inference with trained MNIST model. 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. 'Dataset' type classes can also be used to create 'DataLoader' type classes which are used by lightning_datamodules.
""" """
def __init__(self, img_dir, transform): def __init__(self, img_dir, transform):
@@ -11,7 +11,7 @@ import os
class SaveOnnxModelToWandbCallback(Callback): class SaveOnnxModelToWandbCallback(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 lightning_models are compatible with onnx.
""" """
def __init__(self, datamodule, wandb_save_dir): def __init__(self, datamodule, wandb_save_dir):
first_batch = next(iter(datamodule.train_dataloader())) first_batch = next(iter(datamodule.train_dataloader()))
@@ -162,7 +162,7 @@ class SaveCodeToWandbCallback(Callback):
self.model_folder = run_config["model"]["load_from"]["model_path"] self.model_folder = run_config["model"]["load_from"]["model_path"]
self.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"] 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
"template_utils/callbacks.py", "template_utils/custom_callbacks.py",
"template_utils/initializers.py", "template_utils/initializers.py",
"train.py", "train.py",
"project_config.yaml", "project_config.yaml",
@@ -3,8 +3,8 @@ import pytorch_lightning as pl
import torch.nn.functional as F import torch.nn.functional as F
import torch import torch
# import custom models # import custom lightning_models
from models.simple_mnist_classifier.models import * from pytorch_modules.lightning_models.simple_mnist_classifier.models import *
class LitModel(pl.LightningModule): class LitModel(pl.LightningModule):
-87
View File
@@ -1,87 +0,0 @@
# to execute this run:
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
SIMPLE_CONFIG_EXAMPLE_MNIST:
seed: 1234
trainer:
args:
max_epochs: 10
model:
load_from:
model_path: "models/simple_mnist_classifier/lightning_module.py"
model_class: "LitModel"
hparams:
lr: 0.001
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
output_size: 10 # there are 10 digit classes
lin1_size: 256
lin2_size: 256
lin3_size: 128
datamodule:
load_from:
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
datamodule_class: "MNISTDataModule"
hparams: # you can add here any parameters you want and then read them in datamodule!
batch_size: 256
train_val_test_split: [55_000, 5_000, 10_000]
num_workers: 1 # num of processes used for loading data in parallel
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
# the following sections of config are optional and can be removed:
wandb: # Weights&Biases run options
group: ""
job_type: "train"
tags: ["v2", "uwu"]
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:
checkpoint_path: None # path to your checkpoint
wandb_run_id: None # you can add id of wandb run you want to resume but it's optional
+7 -8
View File
@@ -1,5 +1,5 @@
# pytorch lightning imports # pytorch lightning imports
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.profiler import SimpleProfiler from pytorch_lightning.profiler import SimpleProfiler
import pytorch_lightning as pl import pytorch_lightning as pl
@@ -10,8 +10,7 @@ import os
# template utils imports # template utils imports
from pytorch_lightning import callbacks as lightning_callbacks from pytorch_lightning import callbacks as lightning_callbacks
from template_utils import callbacks as custom_callbacks from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_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]: def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]:
@@ -24,7 +23,7 @@ def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str
os.path.normpath(os.path.join(base_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"]): if not os.path.isabs(project_config["logs_dir"]):
project_config["logs_dir"] =\ project_config["logs_dir"] = \
os.path.normpath(os.path.join(base_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"]): if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
@@ -112,7 +111,7 @@ def init_trainer(project_config: dict,
# experiment logging # experiment logging
logger=loggers, logger=loggers,
# useful callbacks # useful lightning_callbacks
callbacks=callbacks, callbacks=callbacks,
# resume training from checkpoint if it was set in the run config # resume training from checkpoint if it was set in the run config
@@ -145,13 +144,13 @@ def init_callbacks(project_config: dict,
use_wandb: bool, use_wandb: bool,
base_dir: str) -> List[pl.Callback]: base_dir: str) -> List[pl.Callback]:
""" """
Initialize default callbacks and callbacks specified in run config. Initialize default lightning_callbacks and lightning_callbacks specified in run config.
""" """
default_callbacks = project_config.get("default_callbacks", {}) default_callbacks = project_config.get("default_callbacks", {})
run_callbacks = run_config.get("callbacks", {}) run_callbacks = run_config.get("lightning_callbacks", {})
# namespaces in which callbacks will be searched for # namespaces in which lightning_callbacks will be searched for
namespaces = [ namespaces = [
lightning_callbacks, lightning_callbacks,
custom_callbacks, custom_callbacks,
+1 -1
View File
@@ -49,7 +49,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
data_dir=project_config["data_dir"] data_dir=project_config["data_dir"]
) )
# Init PyTorch Lightning callbacks ⚡ # Init PyTorch Lightning lightning_callbacks ⚡
callbacks: List[Callback] = init_callbacks( callbacks: List[Callback] = init_callbacks(
project_config=project_config, project_config=project_config,
run_config=run_config, run_config=run_config,