5 files changed
+145
-77
No files matched your search
@@ -58,9 +58,9 @@ The directory structure of new project looks like this:
|
||||
├── .gitignore
|
||||
├── LICENSE
|
||||
├── README.md
|
||||
├── setup.py
|
||||
├── conda_env.yaml
|
||||
└── requirements.txt
|
||||
├── requirements.txt
|
||||
└── setup.py
|
||||
```
|
||||
<br>
|
||||
|
||||
@@ -104,7 +104,7 @@ MNIST_CLASSIFIER_V1:
|
||||
trainer: <- parameters passed to lightning 'Trainer'
|
||||
max_epochs: 5
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 3
|
||||
accumulate_grad_batches: 1
|
||||
limit_train_batches: 1.0
|
||||
model: <- parameters passed to 'LitModel' in 'hparams' dictionary
|
||||
model_folder: "simple_mnist_classifier" <- name of folder from which 'lightning_module.py' (with 'LitMdodel' class) will be loaded
|
||||
@@ -138,7 +138,7 @@ MNIST_CLASSIFIER_V1:
|
||||
3. Configure [project_config.yaml](project/project_config.yaml)
|
||||
4. Run training<br>
|
||||
```bash
|
||||
python train.py --use_wandb=True --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
||||
```
|
||||
<br><br>
|
||||
|
||||
@@ -173,9 +173,6 @@ conda update conda
|
||||
conda env create -f conda_env.yaml -n your_env_name
|
||||
conda activate your_env_name
|
||||
|
||||
# optionally install project as package with setup.py
|
||||
pip install -e .
|
||||
|
||||
# install requirements
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
@@ -185,7 +182,7 @@ Next, you can train model without logging
|
||||
# train model without Weights&Biases
|
||||
# choose run config from project/run_configs.yaml
|
||||
cd project
|
||||
python train.py --use_wandb=False --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --no_wandb --run_config MNIST_CLASSIFIER_V1
|
||||
```
|
||||
|
||||
Or you can train model with Weights&Biases logging
|
||||
@@ -200,7 +197,12 @@ loggers:
|
||||
# train model with Weights&Biases
|
||||
# choose run config from project/run_configs.yaml
|
||||
cd project
|
||||
python train.py --use_wandb=True --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
||||
```
|
||||
|
||||
Optionally you can install project as package with [setup.py](setup.py)
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
<br>
|
||||
|
||||
|
||||
@@ -43,8 +43,13 @@ MNIST_CLASSIFIER_V2:
|
||||
datamodule_folder: "mnist_digits_datamodule"
|
||||
batch_size: 256
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 4
|
||||
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"]
|
||||
wandb:
|
||||
group: None
|
||||
tags: ["v2", "uwu"]
|
||||
|
||||
+13
-58
@@ -1,4 +1,3 @@
|
||||
from pytorch_lightning.profiler import SimpleProfiler
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from argparse import ArgumentParser
|
||||
import pytorch_lightning as pl
|
||||
@@ -7,8 +6,7 @@ import yaml
|
||||
import os
|
||||
|
||||
# utils
|
||||
from utils.init_utils import init_lit_model, init_data_module, init_main_callbacks, init_wandb_logger
|
||||
from utils.callbacks import *
|
||||
from utils.init_utils import init_lit_model, init_data_module, init_trainer, init_callbacks, init_wandb_logger
|
||||
|
||||
|
||||
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
@@ -27,55 +25,19 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
log_path=os.path.join(os.path.dirname(__file__), "logs/")
|
||||
) if use_wandb else None
|
||||
|
||||
# Init ModelCheckpoint and EarlyStopping callbacks
|
||||
callbacks: List[pl.Callback] = init_main_callbacks(project_config=project_config)
|
||||
|
||||
# Add custom callbacks from utils/callbacks.py
|
||||
callbacks.extend([
|
||||
# MetricsHeatmapLoggerCallback(),
|
||||
# UnfreezeModelCallback(wait_epochs=5),
|
||||
])
|
||||
if use_wandb:
|
||||
callbacks.append(
|
||||
SaveCodeToWandbCallback(
|
||||
base_dir=os.path.dirname(__file__),
|
||||
wandb_save_dir=logger.save_dir,
|
||||
run_config=run_config
|
||||
),
|
||||
# Init callbacks
|
||||
callbacks: List[pl.Callback] = init_callbacks(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
use_wandb=use_wandb
|
||||
)
|
||||
|
||||
# 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)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
trainer = pl.Trainer(
|
||||
# whether to use gpu and how many
|
||||
gpus=project_config["num_of_gpus"],
|
||||
|
||||
# experiment logging
|
||||
trainer: pl.Trainer = init_trainer(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
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 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.dirname(__file__) + "logs/lightning_logs",
|
||||
|
||||
# insert all other trainer parameters specified in run config
|
||||
**run_config["trainer"]
|
||||
callbacks=callbacks
|
||||
)
|
||||
|
||||
# Evaluate model on test set before training
|
||||
@@ -100,22 +62,15 @@ def main(run_config_name: str, use_wandb: bool):
|
||||
project_config: dict = load_config("project_config.yaml")
|
||||
run_config: dict = load_config("run_configs.yaml")[run_config_name]
|
||||
|
||||
# Print run config info
|
||||
print("EXECUTING RUN:", run_config_name)
|
||||
print("CONFIG:")
|
||||
for section in run_config:
|
||||
print(" " + section + ":")
|
||||
for key in run_config[section]:
|
||||
print(" " + key + ":", run_config[section][key])
|
||||
|
||||
# Train model
|
||||
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V1")
|
||||
parser.add_argument("-u", "--use_wandb", type=bool, default=True)
|
||||
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)
|
||||
args = parser.parse_args()
|
||||
|
||||
main(run_config_name=args.run_config, use_wandb=args.use_wandb)
|
||||
@@ -86,11 +86,12 @@ class UnfreezeModelCallback(pl.Callback):
|
||||
|
||||
class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
"""
|
||||
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
|
||||
Generate f1, precision and recall heatmap from validation epoch outputs.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self):
|
||||
def __init__(self, class_names):
|
||||
self.class_names = class_names
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
self.ready = False
|
||||
@@ -117,7 +118,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"f1_p_r_heatmap_{trainer.current_epoch}": wandb.plots.HeatMap(
|
||||
x_labels=[str(i) for i in range(len(f1))], # class names can be hardcoded here
|
||||
x_labels=self.class_names,
|
||||
y_labels=["f1", "precision", "recall"],
|
||||
matrix_values=[f1, p, r],
|
||||
show_text=True,
|
||||
@@ -127,6 +128,46 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
||||
self.targets = []
|
||||
|
||||
|
||||
class ConfusionMatrixLoggerCallback(pl.Callback):
|
||||
"""
|
||||
Generate Confusion Matrix.
|
||||
Expects validation step to return predictions and targets.
|
||||
Works only for single label classification!
|
||||
"""
|
||||
def __init__(self, class_names):
|
||||
self.class_names = class_names
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
self.ready = False
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
"""Start executing this callback only after all validation sanity checks end."""
|
||||
self.ready = True
|
||||
|
||||
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||
"""Gather data from single batch."""
|
||||
if self.ready:
|
||||
preds, targets = outputs
|
||||
self.preds.append(preds)
|
||||
self.targets.append(targets)
|
||||
|
||||
def on_validation_epoch_end(self, trainer, pl_module):
|
||||
"""Generate f1, precision and recall heatmap."""
|
||||
if self.ready:
|
||||
self.preds = torch.cat(self.preds).tolist()
|
||||
self.targets = torch.cat(self.targets).tolist()
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
f"conf_mat{trainer.current_epoch}": wandb.plot.confusion_matrix(
|
||||
self.preds,
|
||||
self.targets,
|
||||
class_names=self.class_names)
|
||||
}, commit=False)
|
||||
|
||||
self.preds = []
|
||||
self.targets = []
|
||||
|
||||
|
||||
class SaveCodeToWandbCallback(pl.Callback):
|
||||
"""
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
|
||||
@@ -1,30 +1,78 @@
|
||||
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_main_callbacks(project_config: dict) -> List[pl.Callback]:
|
||||
"""Initialize ModelCheckpoint and EarlyStopping callbacks."""
|
||||
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"],
|
||||
@@ -38,11 +86,27 @@ def init_main_callbacks(project_config: dict) -> List[pl.Callback]:
|
||||
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,
|
||||
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."""
|
||||
|
||||
@@ -83,7 +147,7 @@ def init_wandb_logger(project_config: dict, run_config: dict,
|
||||
wandb_logger.watch(lit_model, log=None)
|
||||
|
||||
wandb_logger.log_hyperparams({
|
||||
"model_name": lit_model.model.__class__.__name__,
|
||||
"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,
|
||||
@@ -95,9 +159,10 @@ def init_wandb_logger(project_config: dict, run_config: dict,
|
||||
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_loggger() -> pl.loggers.TensorBoardLogger:
|
||||
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger:
|
||||
"""TODO"""
|
||||
return None
|
||||
Reference in new issue
Block a user