start remaking project
This commit is contained in:
1 parent
06e479d9ff
commit
392552a5aa
14 files changed
+409
-273
No files matched your search
@@ -9,13 +9,13 @@ Click on <b>"Use this template"</b> button above to initialize new repository.<b
|
||||
- Storing many run configurations in a convenient way ([run_configs.yaml](project/run_configs.yaml))
|
||||
- Automates the whole training process and initialization, you only need to create `model` and `datamodule` and specify them in [run_configs.yaml](project/run_configs.yaml)
|
||||
- Automatically stores all relevant code, configs and model checkpoints in Weights&Biases cloud
|
||||
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/utils/execute_sweep.py))
|
||||
- Scheduling execution of many experiments ([execute_all_runs.py](project/utils/execute_all_runs.py))
|
||||
- Hyperparameter search with Weights&Biases sweeps ([execute_sweep.py](project/template_utils/execute_sweep.py))
|
||||
- Scheduling execution of many experiments ([execute_all_runs.py](project/template_utils/execute_all_runs.py))
|
||||
- Built in requirements ([requirements.txt](requirements.txt))
|
||||
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
||||
- Built in package setup ([setup.py](setup.py))
|
||||
- Example with MNIST digits classification
|
||||
- Useful example callbacks ([callbacks.py](project/utils/callbacks.py))
|
||||
- Useful example callbacks ([callbacks.py](project/template_utils/callbacks.py))
|
||||
<br>
|
||||
|
||||
|
||||
@@ -116,7 +116,7 @@ MNIST_CLASSIFIER_V1:
|
||||
lin2_size: 256
|
||||
lin3_size: 128
|
||||
dataset: # these parameters will be passed to 'LightningDataModule' object as 'hparams' dictionary
|
||||
datamodule_folder: "mnist_digits_datamodule"
|
||||
datamodule_folder: "mnist_datamodule"
|
||||
batch_size: 256
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 1
|
||||
@@ -137,7 +137,7 @@ Section `model` always needs to contain `model_folder` parameter (name of the fo
|
||||
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 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 in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).<br>
|
||||
<br>
|
||||
|
||||
|
||||
|
||||
File renamed without changes.
+9
-7
@@ -1,10 +1,10 @@
|
||||
from torch.utils.data import DataLoader, random_split
|
||||
from pytorch_lightning import LightningDataModule
|
||||
from torchvision.transforms import transforms
|
||||
from torchvision.datasets import MNIST
|
||||
import pytorch_lightning as pl
|
||||
|
||||
|
||||
class DataModule(pl.LightningDataModule):
|
||||
class MNISTDataModule(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
|
||||
@@ -18,11 +18,12 @@ class DataModule(pl.LightningDataModule):
|
||||
def __init__(self, hparams):
|
||||
super().__init__()
|
||||
|
||||
# hparams["data_dir"] is always automatically set to "path_to_project/data/"
|
||||
# hparams["data_dir"] is always automatically set to 'data_path' from 'project_config.yaml'
|
||||
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.train_val_split = hparams.get("train_val_split") or None
|
||||
self.num_workers = hparams.get("num_workers") or 1
|
||||
self.pin_memory = hparams.get("pin_memory") or False
|
||||
|
||||
@@ -41,11 +42,12 @@ class DataModule(pl.LightningDataModule):
|
||||
"""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]
|
||||
if not self.train_val_split:
|
||||
train_length = int(len(trainset) * self.train_val_split_ratio)
|
||||
val_length = len(trainset) - train_length
|
||||
self.train_val_split = [train_length, val_length]
|
||||
|
||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
||||
self.data_train, self.data_val = random_split(trainset, self.train_val_split)
|
||||
self.data_test = MNIST(self.data_dir, train=False, transform=self.transforms)
|
||||
|
||||
def train_dataloader(self):
|
||||
File renamed without changes.
File renamed without changes.
+34
-13
@@ -1,5 +1,8 @@
|
||||
# set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||
num_of_gpus: 0
|
||||
|
||||
|
||||
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
|
||||
loggers:
|
||||
wandb:
|
||||
project: "project_template_test"
|
||||
@@ -7,18 +10,36 @@ loggers:
|
||||
log_model: True
|
||||
offline: False
|
||||
|
||||
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
|
||||
default_callbacks:
|
||||
checkpoint:
|
||||
callback_class: "ModelCheckpoint"
|
||||
args:
|
||||
monitor: "val_acc"
|
||||
save_top_k: 1
|
||||
save_last: True
|
||||
mode: "max"
|
||||
early_stop:
|
||||
callback_class: "EarlyStopping"
|
||||
args:
|
||||
monitor: "val_acc"
|
||||
patience: 100
|
||||
mode: "max"
|
||||
|
||||
|
||||
# configure things which are printed in terminal
|
||||
printing:
|
||||
progress_bar_refresh_rate: 5
|
||||
weights_summary: "top" # "full"
|
||||
profiler: False
|
||||
progress_bar_refresh_rate: 10 # refresh every 10 batches
|
||||
weights_summary: "top" # model summary (alternatively "full")
|
||||
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_path: "data/"
|
||||
|
||||
|
||||
# path to logs folder (either absolute or relative to placement of 'train.py' file)
|
||||
logs_path: "logs/"
|
||||
+52
-36
@@ -1,25 +1,32 @@
|
||||
MNIST_CLASSIFIER_V1:
|
||||
# make sure parameters from different sections have different names
|
||||
# or they will overwrite themselvess in Weights&Biases config
|
||||
EXAMPLE_MNIST_RUN_CONFIG:
|
||||
trainer:
|
||||
max_epochs: 5
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
model:
|
||||
model_folder: "simple_mnist_classifier"
|
||||
lr: 0.001
|
||||
weight_decay: 0.000001
|
||||
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
|
||||
dataset:
|
||||
datamodule_folder: "mnist_digits_datamodule"
|
||||
batch_size: 64
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
load_from:
|
||||
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||
model_class: "LitModel"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
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:
|
||||
batch_size: 64
|
||||
train_val_split: [50_000, 10_000]
|
||||
|
||||
|
||||
MNIST_CLASSIFIER_V2:
|
||||
|
||||
EXAMPLE_MNIST_RUN_CONFIG_ADVANCED:
|
||||
trainer:
|
||||
min_epochs: 1
|
||||
max_epochs: 10
|
||||
@@ -31,27 +38,36 @@ MNIST_CLASSIFIER_V2:
|
||||
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
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
load_from:
|
||||
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||
model_class: "LitModel"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
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: 256
|
||||
train_val_split: [60_000, 10_000] # use either this or 'train_val_split_ratio'
|
||||
# train_val_split_ratio: 0.9
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
callbacks:
|
||||
ConfusionMatrixLoggerCallback:
|
||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
MetricsHeatmapLoggerCallback:
|
||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
early_stop:
|
||||
callback_class: "EarlyStopping"
|
||||
args:
|
||||
monitor: "val_acc"
|
||||
patience: 5
|
||||
mode: "max"
|
||||
wandb:
|
||||
group: None
|
||||
group: ""
|
||||
tags: ["v2", "uwu"]
|
||||
notes: "This is example run."
|
||||
resume_training:
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||
import pytorch_lightning as pl
|
||||
from pytorch_lightning import Callback
|
||||
import pytorch_lightning.callbacks
|
||||
from shutil import copy
|
||||
import inspect
|
||||
import torch
|
||||
import wandb
|
||||
import os
|
||||
|
||||
|
||||
class ExampleCallback(pl.Callback):
|
||||
class ExampleCallback(Callback):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@@ -21,7 +21,7 @@ class ExampleCallback(pl.Callback):
|
||||
print('Do something when training ends.')
|
||||
|
||||
|
||||
class SaveOnnxModelToWandbCallback(pl.Callback):
|
||||
class SaveOnnxModelToWandbCallback(Callback):
|
||||
"""
|
||||
Save model in .onnx format and upload to wandb.
|
||||
Might crash since not all models are compatible with onnx.
|
||||
@@ -44,7 +44,7 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
|
||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(pl.Callback):
|
||||
class ImagePredictionLoggerCallback(Callback):
|
||||
"""
|
||||
Each epoch upload to wandb a couple of the same images with predicted labels.
|
||||
"""
|
||||
@@ -71,7 +71,7 @@ class ImagePredictionLoggerCallback(pl.Callback):
|
||||
]}, commit=False)
|
||||
|
||||
|
||||
class UnfreezeModelCallback(pl.Callback):
|
||||
class UnfreezeModelCallback(Callback):
|
||||
"""
|
||||
Unfreeze model after a few epochs.
|
||||
"""
|
||||
@@ -84,7 +84,7 @@ class UnfreezeModelCallback(pl.Callback):
|
||||
param.requires_grad = True
|
||||
|
||||
|
||||
class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
class MetricsHeatmapLoggerCallback(Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
@@ -128,7 +128,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
self.targets = []
|
||||
|
||||
|
||||
class ConfusionMatrixLoggerCallback(pl.Callback):
|
||||
class ConfusionMatrixLoggerCallback(Callback):
|
||||
"""
|
||||
Generate Confusion Matrix.
|
||||
Expects validation step to return predictions and targets.
|
||||
@@ -168,7 +168,7 @@ class ConfusionMatrixLoggerCallback(pl.Callback):
|
||||
self.targets = []
|
||||
|
||||
|
||||
class SaveCodeToWandbCallback(pl.Callback):
|
||||
class SaveCodeToWandbCallback(Callback):
|
||||
"""
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
"""
|
||||
@@ -178,8 +178,8 @@ class SaveCodeToWandbCallback(pl.Callback):
|
||||
self.model_folder = run_config["model"]["model_folder"]
|
||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||
"utils/callbacks.py",
|
||||
"utils/init_utils.py",
|
||||
"template_utils/callbacks.py",
|
||||
"template_utils/initializers.py",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
"run_configs.yaml",
|
||||
@@ -214,11 +214,11 @@ class SaveCodeToWandbCallback(pl.Callback):
|
||||
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)):
|
||||
for filename in os.listdir(os.path.join(self.base_dir, "datamodules", 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)
|
||||
src_path = os.path.join(self.base_dir, "datamodules", self.datamodule_folder, filename)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "datamodules", self.datamodule_folder, filename)
|
||||
|
||||
path, filename = os.path.split(dst_path)
|
||||
if not os.path.exists(path):
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,238 @@
|
||||
# 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
|
||||
import importlib.util
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
import template_utils.callbacks
|
||||
|
||||
|
||||
def init_model(model_config: dict, base_dir: str) -> 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"]
|
||||
|
||||
if not os.path.isabs(model_path):
|
||||
model_path = os.path.join(base_dir, model_path)
|
||||
|
||||
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_path: str, base_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"]
|
||||
|
||||
if not os.path.isabs(datamodule_path):
|
||||
datamodule_path = os.path.join(base_dir, datamodule_path)
|
||||
assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}"
|
||||
|
||||
if not os.path.isabs(data_path):
|
||||
datamodule_config["hparams"]["data_dir"] = os.path.join(base_dir, data_path)
|
||||
else:
|
||||
datamodule_config["hparams"]["data_dir"] = data_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(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(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,
|
||||
base_dir: str) -> List[pl.Callback]:
|
||||
"""
|
||||
Initialize default callbacks and callbacks specified in run config.
|
||||
"""
|
||||
|
||||
default_callbacks = project_config["default_callbacks"]
|
||||
run_callbacks = run_config["callbacks"]
|
||||
|
||||
callbacks = []
|
||||
|
||||
for callback_config in default_callbacks:
|
||||
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
callbacks.append(callback_class(**callback_config["args"]))
|
||||
|
||||
for callback_config in run_callbacks:
|
||||
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
callbacks.append(callback_class(**callback_config["args"]))
|
||||
|
||||
if use_wandb:
|
||||
callbacks.append(
|
||||
template_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
|
||||
)
|
||||
)
|
||||
|
||||
return callbacks
|
||||
|
||||
|
||||
def init_loggers(project_config: dict,
|
||||
run_config: dict,
|
||||
lit_model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
|
||||
"""
|
||||
Initialize loggers.
|
||||
"""
|
||||
|
||||
return []
|
||||
|
||||
|
||||
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__ if hasattr(lit_model, 'model') else None,
|
||||
"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:
|
||||
"""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
|
||||
|
||||
# the LitModel you import should be the same as the one you used for training!
|
||||
+56
-29
@@ -1,43 +1,65 @@
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
# pytorch lightning imports
|
||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
|
||||
# normal imports
|
||||
from argparse import ArgumentParser
|
||||
import pytorch_lightning as pl
|
||||
from typing import List
|
||||
import yaml
|
||||
import os
|
||||
|
||||
# utils
|
||||
from utils.init_utils import init_lit_model, init_data_module, init_trainer, init_callbacks, init_wandb_logger
|
||||
# template utils imports
|
||||
from template_utils.initializers import (
|
||||
init_model,
|
||||
init_datamodule,
|
||||
init_callbacks,
|
||||
init_loggers,
|
||||
init_trainer
|
||||
)
|
||||
|
||||
|
||||
# Everything will be loaded relatively to placement of this file!
|
||||
BASE_DIR: str = os.path.dirname(__file__)
|
||||
|
||||
|
||||
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
# Init PyTorch Lightning model ⚡
|
||||
lit_model: pl.LightningModule = init_lit_model(hparams=run_config["model"])
|
||||
lit_model: LightningModule = init_model(
|
||||
model_config=run_config["model"],
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning datamodule ⚡
|
||||
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
|
||||
datamodule: LightningDataModule = init_datamodule(
|
||||
datamodule_config=run_config["datamodule"],
|
||||
data_path=project_config["data_path"],
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
|
||||
# Init Weights&Biases logger
|
||||
logger: pl.loggers.WandbLogger = init_wandb_logger(
|
||||
# Init PyTorch Lightning callbacks ⚡
|
||||
callbacks: List[Callback] = init_callbacks(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
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,
|
||||
lit_model=lit_model,
|
||||
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,
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
trainer: pl.Trainer = init_trainer(
|
||||
trainer: Trainer = init_trainer(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
logger=logger,
|
||||
callbacks=callbacks
|
||||
callbacks=callbacks,
|
||||
loggers=loggers
|
||||
)
|
||||
|
||||
# Evaluate model on test set before training
|
||||
@@ -47,20 +69,20 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
trainer.fit(model=lit_model, datamodule=datamodule)
|
||||
|
||||
# Evaluate model on test set after training
|
||||
trainer.test()
|
||||
# trainer.test()
|
||||
|
||||
|
||||
def load_config(filename):
|
||||
path = os.path.join(os.path.dirname(__file__), filename)
|
||||
with open(path, "r") as ymlfile:
|
||||
def load_config(path):
|
||||
abs_path = os.path.join(BASE_DIR, path) if not os.path.isabs(path) else path
|
||||
with open(abs_path, "r") as ymlfile:
|
||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||
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
|
||||
project_config: dict = load_config("project_config.yaml")
|
||||
run_config: dict = load_config("run_configs.yaml")[run_config_name]
|
||||
project_config: dict = load_config(path=project_config_path)
|
||||
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
||||
|
||||
# Train model
|
||||
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||
@@ -68,9 +90,14 @@ def main(run_config_name: str, use_wandb: bool):
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V2")
|
||||
parser.add_argument("-n", "--no_wandb", dest='use_wandb', action='store_false')
|
||||
parser.set_defaults(use_wandb=True)
|
||||
parser.add_argument("--project_config_path", type=str, default="project_config.yaml")
|
||||
parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml")
|
||||
parser.add_argument("--run_config_name", type=str, default="EXAMPLE_MNIST_RUN_CONFIG")
|
||||
parser.add_argument("--no_wandb", dest='use_wandb', action='store_false')
|
||||
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
|
||||
Reference in new issue
Block a user