start redesigning project structure for version 4.0
This commit is contained in:
1 parent
42652e3752
commit
fa8b9ecc16
18 files changed
+140
-130
No files matched your search
@@ -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)
|
||||
- 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)
|
||||
- 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 conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
||||
- Built in package setup ([setup.py](setup.py))
|
||||
- Example with MNIST digits classification
|
||||
- Useful example callbacks ([callbacks.py](project/template_utils/callbacks.py))
|
||||
- Useful example callbacks ([callbacks.py](project/pytorch_modules/lightning_callbacks/custom_callbacks.py))
|
||||
<br>
|
||||
|
||||
|
||||
@@ -83,7 +83,7 @@ loggers:
|
||||
default_callbacks:
|
||||
ModelCheckpoint:
|
||||
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
|
||||
mode: "max" <- can be "max" or "min"
|
||||
EarlyStopping:
|
||||
@@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
max_epochs: 10
|
||||
model:
|
||||
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"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
@@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
lin3_size: 128
|
||||
datamodule:
|
||||
load_from:
|
||||
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
||||
datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
|
||||
datamodule_class: "MNISTDataModule"
|
||||
hparams:
|
||||
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 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>
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
+59
@@ -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
|
||||
+28
@@ -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
|
||||
|
||||
# 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():
|
||||
@@ -10,7 +10,7 @@ def predict():
|
||||
This method is example of inference with a trained model.
|
||||
It Loads trained image classification model from checkpoint.
|
||||
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"
|
||||
Whitespace-only changes.
+30
-19
@@ -1,26 +1,37 @@
|
||||
# set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||
num_of_gpus: -1
|
||||
# default args passed to Lightning Trainer on every run/experiment
|
||||
# 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)
|
||||
loggers:
|
||||
wandb:
|
||||
project: "project_template_test"
|
||||
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_gradients: False # set True to log gradient histograms (avoid this for very big models)
|
||||
offline: False # set True to store all logs only locally
|
||||
# default loggers initialised on every run/experiment
|
||||
# if you specify this section in experiment config then it will be totally overwritten
|
||||
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"
|
||||
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
|
||||
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 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
|
||||
# if you specify the same callback class also in experiment 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_top_k: 1 # save k best lightning_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
|
||||
@@ -29,11 +40,11 @@ default_callbacks:
|
||||
mode: "max" # can be "max" or "min"
|
||||
|
||||
|
||||
# configure things which are printed in terminal
|
||||
printing:
|
||||
progress_bar_refresh_rate: 10 # refresh every 10 batches
|
||||
weights_summary: "top" # print model summary (alternatively "full")
|
||||
profiler: False # set True to print execution time profiling after training ends
|
||||
# use profiler to print execution time profiling after training ends
|
||||
profiler:
|
||||
use_profiler: True
|
||||
class: "pytorch_lightning.profiler.SimpleProfiler"
|
||||
args: {}
|
||||
|
||||
|
||||
# path to data folder (either absolute or relative to placement of 'train.py' file)
|
||||
|
||||
File renamed without changes.
+1
-1
@@ -7,7 +7,7 @@ class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder and converting them to monochromatic.
|
||||
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):
|
||||
File renamed without changes.
+2
-2
@@ -11,7 +11,7 @@ import os
|
||||
class SaveOnnxModelToWandbCallback(Callback):
|
||||
"""
|
||||
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):
|
||||
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.datamodule_folder = run_config["datamodule"]["load_from"]["datamodule_path"]
|
||||
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",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
File renamed without changes.
+2
-2
@@ -3,8 +3,8 @@ import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
# import custom models
|
||||
from models.simple_mnist_classifier.models import *
|
||||
# import custom lightning_models
|
||||
from pytorch_modules.lightning_models.simple_mnist_classifier.models import *
|
||||
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
File renamed without changes.
@@ -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
|
||||
File renamed without changes.
@@ -1,5 +1,5 @@
|
||||
# pytorch lightning imports
|
||||
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from pytorch_lightning.profiler import SimpleProfiler
|
||||
import pytorch_lightning as pl
|
||||
|
||||
@@ -10,8 +10,7 @@ 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
|
||||
from pytorch_modules.lightning_callbacks import wandb_callbacks, custom_callbacks as custom_callbacks
|
||||
|
||||
|
||||
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"]))
|
||||
|
||||
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"]))
|
||||
|
||||
if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
|
||||
@@ -112,7 +111,7 @@ def init_trainer(project_config: dict,
|
||||
# experiment logging
|
||||
logger=loggers,
|
||||
|
||||
# useful callbacks
|
||||
# useful lightning_callbacks
|
||||
callbacks=callbacks,
|
||||
|
||||
# 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,
|
||||
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", {})
|
||||
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 = [
|
||||
lightning_callbacks,
|
||||
custom_callbacks,
|
||||
|
||||
+1
-1
@@ -49,7 +49,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
data_dir=project_config["data_dir"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning callbacks ⚡
|
||||
# Init PyTorch Lightning lightning_callbacks ⚡
|
||||
callbacks: List[Callback] = init_callbacks(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
|
||||
Reference in new issue
Block a user