everything except callbacks works
This commit is contained in:
1 parent
f46f380261
commit
757f0fc25a
7 files changed
+189
-148
No files matched your search
@@ -5,8 +5,8 @@ import os
|
||||
|
||||
class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder.
|
||||
'Dataset' classes can be used by 'DataModule' class.
|
||||
Example dataset class for loading images from folder.
|
||||
'Dataset' classes can be used by 'DataModule' class.
|
||||
"""
|
||||
|
||||
def __init__(self, img_dir, transform):
|
||||
@@ -14,7 +14,8 @@ class TestDataset(Dataset):
|
||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||
|
||||
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:
|
||||
image = self.transform(image)
|
||||
|
||||
@@ -9,18 +9,16 @@ from models.simple_mnist_classifier.models import *
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
"""
|
||||
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'!
|
||||
This is example of lightning model for MNIST digits classification.
|
||||
|
||||
The folder name of model used during training should be specified in run config and all parameters from
|
||||
'model' section will be passed in 'hparams' dictionary.
|
||||
The path to model should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml)
|
||||
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
|
||||
def __init__(self, hparams=None):
|
||||
def __init__(self, hparams: dict = None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
|
||||
+12
-11
@@ -4,11 +4,12 @@ num_of_gpus: 0
|
||||
|
||||
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
|
||||
loggers:
|
||||
Weights&Biases_config:
|
||||
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
|
||||
offline: False # set True to store all logs only locally
|
||||
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 callbacks initialised on every run/experiment
|
||||
@@ -18,14 +19,14 @@ loggers:
|
||||
# all of the callback parameters will be passed to it on initialization
|
||||
default_callbacks:
|
||||
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
|
||||
monitor: "val_acc",
|
||||
patience: 5,
|
||||
mode: "max",
|
||||
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",
|
||||
monitor: "val_acc"
|
||||
save_top_k: 1
|
||||
save_last: True
|
||||
mode: "max"
|
||||
|
||||
|
||||
# configure things which are printed in terminal
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
# execute this run like this:
|
||||
# to execute this run:
|
||||
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||
SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
seed: 1234
|
||||
@@ -11,7 +11,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
model_class: "LitModel"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
weight_decay: 0.00001
|
||||
input_size: 784
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
@@ -26,7 +26,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
|
||||
|
||||
# execute this run like this:
|
||||
# to execute this run:
|
||||
# python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST
|
||||
ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
seed: 1234
|
||||
@@ -47,7 +47,7 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
model_class: "LitModel"
|
||||
hparams: # you can add here any parameters you want and then read them in model!
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
weight_decay: 0.00001
|
||||
input_size: 784 # img size is 1*28*28
|
||||
output_size: 10 # there are 10 digit classes
|
||||
lin1_size: 256
|
||||
@@ -70,14 +70,14 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
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",
|
||||
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",
|
||||
monitor: "val_acc"
|
||||
save_top_k: 1
|
||||
save_last: True
|
||||
mode: "max"
|
||||
ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py
|
||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
resume_training:
|
||||
|
||||
@@ -4,15 +4,40 @@ from pytorch_lightning.profiler import SimpleProfiler
|
||||
import pytorch_lightning as pl
|
||||
|
||||
# normal imports
|
||||
from typing import List
|
||||
from typing import List, Tuple
|
||||
import importlib.util
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
import template_utils.callbacks
|
||||
from template_utils import callbacks as custom_callbacks
|
||||
from template_utils import wandb_callbacks
|
||||
|
||||
|
||||
def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
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.
|
||||
"""
|
||||
@@ -20,9 +45,6 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
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)
|
||||
@@ -42,7 +64,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
return model
|
||||
|
||||
|
||||
def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl.LightningDataModule:
|
||||
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||
"""
|
||||
Load LightningDataModule from path specified in run config.
|
||||
"""
|
||||
@@ -50,13 +72,8 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl
|
||||
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_dir):
|
||||
data_dir = os.path.join(base_dir, data_dir)
|
||||
|
||||
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)
|
||||
@@ -79,8 +96,7 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl
|
||||
def init_trainer(project_config: dict,
|
||||
run_config: dict,
|
||||
callbacks: List[pl.Callback],
|
||||
loggers: List[pl.loggers.LightningLoggerBase],
|
||||
base_dir: str) -> pl.Trainer:
|
||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||
"""
|
||||
Initialize PyTorch Lightning Trainer.
|
||||
"""
|
||||
@@ -125,8 +141,7 @@ def init_trainer(project_config: dict,
|
||||
|
||||
def init_callbacks(project_config: dict,
|
||||
run_config: dict,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.Callback]:
|
||||
use_wandb: bool) -> List[pl.Callback]:
|
||||
"""
|
||||
Initialize default callbacks and callbacks specified in run config.
|
||||
"""
|
||||
@@ -134,26 +149,26 @@ def init_callbacks(project_config: dict,
|
||||
default_callbacks = project_config.get("default_callbacks", {})
|
||||
run_callbacks = run_config.get("callbacks", {})
|
||||
|
||||
print(default_callbacks)
|
||||
# print(default_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
|
||||
)
|
||||
)
|
||||
# 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(
|
||||
# wandb_callbacks.SaveCodeToWandbCallback(
|
||||
# base_dir=os.path.dirname(os.path.dirname(__file__)),
|
||||
# wandb_save_dir=project_config["logs_dir"],
|
||||
# run_config=run_config
|
||||
# )
|
||||
# )
|
||||
|
||||
return callbacks
|
||||
|
||||
@@ -162,24 +177,35 @@ def init_loggers(project_config: dict,
|
||||
run_config: dict,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
|
||||
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 []
|
||||
return loggers
|
||||
|
||||
|
||||
def init_wandb_logger(project_config: dict,
|
||||
run_config: dict,
|
||||
lit_model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
log_path: str = "logs/") -> pl.loggers.WandbLogger:
|
||||
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"
|
||||
@@ -204,21 +230,27 @@ def init_wandb_logger(project_config: dict,
|
||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
||||
else None,
|
||||
|
||||
save_dir=log_path,
|
||||
save_dir=project_config["logs_dir"],
|
||||
save_code=False
|
||||
)
|
||||
|
||||
if not os.path.exists(log_path):
|
||||
os.makedirs(log_path)
|
||||
if not os.path.exists(project_config["logs_dir"]):
|
||||
os.makedirs(project_config["logs_dir"])
|
||||
|
||||
if hasattr(lit_model, 'model'):
|
||||
wandb_logger.watch(lit_model.model, log=None)
|
||||
wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__})
|
||||
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:
|
||||
wandb_logger.watch(lit_model, log=None)
|
||||
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": lit_model.configure_optimizers().__class__.__name__,
|
||||
"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)
|
||||
@@ -226,9 +258,12 @@ def init_wandb_logger(project_config: dict,
|
||||
"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"])
|
||||
wandb_logger.log_hyperparams(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
|
||||
|
||||
|
||||
+19
-11
@@ -1,16 +1,18 @@
|
||||
# pytorch lightning imports
|
||||
import torch
|
||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
import torch
|
||||
|
||||
# normal imports
|
||||
from argparse import ArgumentParser
|
||||
from typing import List
|
||||
import pprint
|
||||
import yaml
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
from template_utils.initializers import (
|
||||
normalize_config_paths,
|
||||
init_model,
|
||||
init_datamodule,
|
||||
init_callbacks,
|
||||
@@ -29,25 +31,29 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
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 ⚡
|
||||
model: LightningModule = init_model(
|
||||
model_config=run_config["model"],
|
||||
base_dir=BASE_DIR
|
||||
model_config=run_config["model"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning datamodule ⚡
|
||||
datamodule: LightningDataModule = init_datamodule(
|
||||
datamodule_config=run_config["datamodule"],
|
||||
data_dir=project_config["data_dir"],
|
||||
base_dir=BASE_DIR
|
||||
data_dir=project_config["data_dir"]
|
||||
)
|
||||
|
||||
# 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
|
||||
use_wandb=use_wandb
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning loggers ⚡
|
||||
@@ -56,8 +62,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
run_config=run_config,
|
||||
model=model,
|
||||
datamodule=datamodule,
|
||||
use_wandb=use_wandb,
|
||||
base_dir=BASE_DIR
|
||||
use_wandb=use_wandb
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
@@ -65,8 +70,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
callbacks=callbacks,
|
||||
loggers=loggers,
|
||||
base_dir=BASE_DIR
|
||||
loggers=loggers
|
||||
)
|
||||
|
||||
# Evaluate model on test set before training
|
||||
@@ -91,6 +95,10 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str,
|
||||
project_config: dict = load_config(path=project_config_path)
|
||||
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(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||
|
||||
|
||||
Reference in new issue
Block a user