Move wandb callbacks to the wandb-callbacks branch (#254)
* Remove `src/callbacks/` * Remove `configs/callbacks/wandb.yaml` * Update readme
This commit is contained in:
1 parent
2242ea1677
commit
ddbd1e3c78
4 files changed
+15
-326
No files matched your search
@@ -86,7 +86,6 @@ The directory structure of new project looks like this:
|
|||||||
├── scripts <- Shell scripts
|
├── scripts <- Shell scripts
|
||||||
│
|
│
|
||||||
├── src <- Source code
|
├── src <- Source code
|
||||||
│ ├── callbacks <- Lightning callbacks
|
|
||||||
│ ├── datamodules <- Lightning datamodules
|
│ ├── datamodules <- Lightning datamodules
|
||||||
│ ├── models <- Lightning models
|
│ ├── models <- Lightning models
|
||||||
│ ├── utils <- Utility scripts
|
│ ├── utils <- Utility scripts
|
||||||
@@ -105,7 +104,7 @@ The directory structure of new project looks like this:
|
|||||||
│
|
│
|
||||||
├── .env.example <- Template of the file for storing private environment variables
|
├── .env.example <- Template of the file for storing private environment variables
|
||||||
├── .gitignore <- List of files/folders ignored by git
|
├── .gitignore <- List of files/folders ignored by git
|
||||||
├── .pre-commit-config.yaml <- Configuration of pre-commit hooks
|
├── .pre-commit-config.yaml <- Configuration of pre-commit hooks for code formatting
|
||||||
├── requirements.txt <- File for installing python dependencies
|
├── requirements.txt <- File for installing python dependencies
|
||||||
├── setup.cfg <- Configuration of linters and pytest
|
├── setup.cfg <- Configuration of linters and pytest
|
||||||
└── README.md
|
└── README.md
|
||||||
@@ -453,20 +452,19 @@ It determines how config is composed when simply executing command `python train
|
|||||||
```yaml
|
```yaml
|
||||||
# specify here default training configuration
|
# specify here default training configuration
|
||||||
defaults:
|
defaults:
|
||||||
|
- _self_
|
||||||
- datamodule: mnist.yaml
|
- datamodule: mnist.yaml
|
||||||
- model: mnist.yaml
|
- model: mnist.yaml
|
||||||
- callbacks: default.yaml
|
- callbacks: default.yaml
|
||||||
- logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=tensorboard`)
|
||||||
- trainer: default.yaml
|
- trainer: default.yaml
|
||||||
|
|
||||||
# logging folder path
|
|
||||||
- log_dir: default.yaml
|
- log_dir: default.yaml
|
||||||
|
|
||||||
# experiment configs allow for version control of specific configurations
|
# experiment configs allow for version control of specific configurations
|
||||||
# e.g. best hyperparameters for each combination of model and datamodule
|
# e.g. best hyperparameters for each combination of model and datamodule
|
||||||
- experiment: null
|
- experiment: null
|
||||||
|
|
||||||
# debugging config (enable through command line, e.g. `python train.py debug=one_epoch)
|
# debugging config (enable through command line, e.g. `python train.py debug=default)
|
||||||
- debug: null
|
- debug: null
|
||||||
|
|
||||||
# config for hyperparameter optimization
|
# config for hyperparameter optimization
|
||||||
@@ -482,7 +480,6 @@ defaults:
|
|||||||
|
|
||||||
# path to original working directory
|
# path to original working directory
|
||||||
# hydra hijacks working directory by changing it to the new log directory
|
# hydra hijacks working directory by changing it to the new log directory
|
||||||
# so it's useful to have this path as a special variable
|
|
||||||
# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
|
# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory
|
||||||
original_work_dir: ${hydra:runtime.cwd}
|
original_work_dir: ${hydra:runtime.cwd}
|
||||||
|
|
||||||
@@ -827,21 +824,27 @@ You can easily modify the commands in the scripts for your use case. If 1 epoch
|
|||||||
|
|
||||||
### Callbacks
|
### Callbacks
|
||||||
|
|
||||||
Template contains example callbacks enabling better Weights&Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](src/callbacks/wandb_callbacks.py)).
|
The branch [`wandb-callbacks`](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks) contains example callbacks enabling better Weights&Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](https://github.com/ashleve/lightning-hydra-template/tree/wandb-callbacks/src/callbacks/wandb_callbacks.py)).
|
||||||
|
|
||||||
To support reproducibility:
|
Callbacks which support reproducibility:
|
||||||
|
|
||||||
- **WatchModel**
|
- **WatchModel**
|
||||||
- **UploadCodeAsArtifact**
|
- **UploadCodeAsArtifact**
|
||||||
- **UploadCheckpointsAsArtifact**
|
- **UploadCheckpointsAsArtifact**
|
||||||
|
|
||||||
To provide examples of logging custom visualisations with callbacks only:
|
Callbacks which provide examples of logging custom visualisations:
|
||||||
|
|
||||||
- **LogConfusionMatrix**
|
- **LogConfusionMatrix**
|
||||||
- **LogF1PrecRecHeatmap**
|
- **LogF1PrecRecHeatmap**
|
||||||
- **LogImagePredictions**
|
- **LogImagePredictions**
|
||||||
|
|
||||||
To try all of the callbacks at once, use:
|
To try all of the callbacks at once, switch to the right branch:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout wandb-callbacks
|
||||||
|
```
|
||||||
|
|
||||||
|
And then run the following command:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python train.py logger=wandb callbacks=wandb
|
python train.py logger=wandb callbacks=wandb
|
||||||
@@ -898,6 +901,7 @@ What provides reproducibility:
|
|||||||
- Pytorch Lightning takes care of creating training checkpoints
|
- Pytorch Lightning takes care of creating training checkpoints
|
||||||
- Example callbacks for wandb show how you can save and upload a snapshot of codebase every time the run is executed, as well as upload ckpts and track model gradients
|
- Example callbacks for wandb show how you can save and upload a snapshot of codebase every time the run is executed, as well as upload ckpts and track model gradients
|
||||||
|
|
||||||
|
<!--
|
||||||
You can load the config of previous run using:
|
You can load the config of previous run using:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -905,7 +909,7 @@ python train.py --config-path /logs/runs/.../.hydra/ --config-name config.yaml
|
|||||||
```
|
```
|
||||||
|
|
||||||
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the `hydra/` part of the config, meaning logging paths will revert to default!
|
The `config.yaml` from `.hydra` folder contains all overriden parameters and sections. This approach however is not officially supported by Hydra and doesn't override the `hydra/` part of the config, meaning logging paths will revert to default!
|
||||||
|
-->
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
### Limitations
|
### Limitations
|
||||||
|
|||||||
@@ -1,26 +0,0 @@
|
|||||||
defaults:
|
|
||||||
- default.yaml
|
|
||||||
|
|
||||||
watch_model:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.WatchModel
|
|
||||||
log: "all"
|
|
||||||
log_freq: 100
|
|
||||||
|
|
||||||
upload_code_as_artifact:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.UploadCodeAsArtifact
|
|
||||||
code_dir: ${original_work_dir}/src
|
|
||||||
|
|
||||||
upload_ckpts_as_artifact:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsAsArtifact
|
|
||||||
ckpt_dir: "checkpoints/"
|
|
||||||
upload_best_only: True
|
|
||||||
|
|
||||||
log_f1_precision_recall_heatmap:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmap
|
|
||||||
|
|
||||||
log_confusion_matrix:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrix
|
|
||||||
|
|
||||||
log_image_predictions:
|
|
||||||
_target_: src.callbacks.wandb_callbacks.LogImagePredictions
|
|
||||||
num_samples: 8
|
|
||||||
Whitespace-only changes.
@@ -1,289 +0,0 @@
|
|||||||
import subprocess
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
import matplotlib.pyplot as plt
|
|
||||||
import seaborn as sn
|
|
||||||
import torch
|
|
||||||
import wandb
|
|
||||||
from pytorch_lightning import Callback, Trainer
|
|
||||||
from pytorch_lightning.loggers import LoggerCollection, WandbLogger
|
|
||||||
from pytorch_lightning.utilities import rank_zero_only
|
|
||||||
from sklearn import metrics
|
|
||||||
from sklearn.metrics import f1_score, precision_score, recall_score
|
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
|
||||||
"""Safely get Weights&Biases logger from Trainer."""
|
|
||||||
|
|
||||||
if trainer.fast_dev_run:
|
|
||||||
raise Exception(
|
|
||||||
"Cannot use wandb callbacks since pytorch lightning disables loggers in `fast_dev_run=true` mode."
|
|
||||||
)
|
|
||||||
|
|
||||||
if isinstance(trainer.logger, WandbLogger):
|
|
||||||
return trainer.logger
|
|
||||||
|
|
||||||
if isinstance(trainer.logger, LoggerCollection):
|
|
||||||
for logger in trainer.logger:
|
|
||||||
if isinstance(logger, WandbLogger):
|
|
||||||
return logger
|
|
||||||
|
|
||||||
raise Exception(
|
|
||||||
"You are using wandb related callback, but WandbLogger was not found for some reason..."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class WatchModel(Callback):
|
|
||||||
"""Make wandb watch model at the beginning of the run."""
|
|
||||||
|
|
||||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
|
||||||
self.log = log
|
|
||||||
self.log_freq = log_freq
|
|
||||||
|
|
||||||
@rank_zero_only
|
|
||||||
def on_train_start(self, trainer, pl_module):
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq, log_graph=True)
|
|
||||||
|
|
||||||
|
|
||||||
class UploadCodeAsArtifact(Callback):
|
|
||||||
"""Upload all code files to wandb as an artifact, at the beginning of the run."""
|
|
||||||
|
|
||||||
def __init__(self, code_dir: str, use_git: bool = True):
|
|
||||||
"""
|
|
||||||
|
|
||||||
Args:
|
|
||||||
code_dir: the code directory
|
|
||||||
use_git: if using git, then upload all files that are not ignored by git.
|
|
||||||
if not using git, then upload all '*.py' file
|
|
||||||
"""
|
|
||||||
self.code_dir = code_dir
|
|
||||||
self.use_git = use_git
|
|
||||||
|
|
||||||
@rank_zero_only
|
|
||||||
def on_train_start(self, trainer, pl_module):
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
code = wandb.Artifact("project-source", type="code")
|
|
||||||
|
|
||||||
if self.use_git:
|
|
||||||
# get .git folder path
|
|
||||||
git_dir_path = Path(
|
|
||||||
subprocess.check_output(["git", "rev-parse", "--git-dir"]).strip().decode("utf8")
|
|
||||||
).resolve()
|
|
||||||
|
|
||||||
for path in Path(self.code_dir).resolve().rglob("*"):
|
|
||||||
|
|
||||||
# don't upload files ignored by git
|
|
||||||
# https://alexwlchan.net/2020/11/a-python-function-to-ignore-a-path-with-git-info-exclude/
|
|
||||||
command = ["git", "check-ignore", "-q", str(path)]
|
|
||||||
not_ignored = subprocess.run(command).returncode == 1
|
|
||||||
|
|
||||||
# don't upload files from .git folder
|
|
||||||
not_git = not str(path).startswith(str(git_dir_path))
|
|
||||||
|
|
||||||
if path.is_file() and not_git and not_ignored:
|
|
||||||
code.add_file(str(path), name=str(path.relative_to(self.code_dir)))
|
|
||||||
|
|
||||||
else:
|
|
||||||
for path in Path(self.code_dir).resolve().rglob("*.py"):
|
|
||||||
code.add_file(str(path), name=str(path.relative_to(self.code_dir)))
|
|
||||||
|
|
||||||
experiment.log_artifact(code)
|
|
||||||
|
|
||||||
|
|
||||||
class UploadCheckpointsAsArtifact(Callback):
|
|
||||||
"""Upload checkpoints to wandb as an artifact, at the end of run."""
|
|
||||||
|
|
||||||
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
|
||||||
self.ckpt_dir = ckpt_dir
|
|
||||||
self.upload_best_only = upload_best_only
|
|
||||||
|
|
||||||
@rank_zero_only
|
|
||||||
def on_keyboard_interrupt(self, trainer, pl_module):
|
|
||||||
self.on_train_end(trainer, pl_module)
|
|
||||||
|
|
||||||
@rank_zero_only
|
|
||||||
def on_train_end(self, trainer, pl_module):
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
ckpts = wandb.Artifact("experiment-ckpts", type="checkpoints")
|
|
||||||
|
|
||||||
if self.upload_best_only:
|
|
||||||
ckpts.add_file(trainer.checkpoint_callback.best_model_path)
|
|
||||||
else:
|
|
||||||
for path in Path(self.ckpt_dir).rglob("*.ckpt"):
|
|
||||||
ckpts.add_file(str(path))
|
|
||||||
|
|
||||||
experiment.log_artifact(ckpts)
|
|
||||||
|
|
||||||
|
|
||||||
class LogConfusionMatrix(Callback):
|
|
||||||
"""Generate confusion matrix every epoch and send it to wandb.
|
|
||||||
Expects validation step to return predictions and targets.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self):
|
|
||||||
self.preds = []
|
|
||||||
self.targets = []
|
|
||||||
self.ready = True
|
|
||||||
|
|
||||||
def on_sanity_check_start(self, trainer, pl_module) -> None:
|
|
||||||
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:
|
|
||||||
self.preds.append(outputs["preds"])
|
|
||||||
self.targets.append(outputs["targets"])
|
|
||||||
|
|
||||||
def on_validation_epoch_end(self, trainer, pl_module):
|
|
||||||
"""Generate confusion matrix."""
|
|
||||||
if self.ready:
|
|
||||||
logger = get_wandb_logger(trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
preds = torch.cat(self.preds).cpu().numpy()
|
|
||||||
targets = torch.cat(self.targets).cpu().numpy()
|
|
||||||
|
|
||||||
confusion_matrix = metrics.confusion_matrix(y_true=targets, y_pred=preds)
|
|
||||||
|
|
||||||
# set figure size
|
|
||||||
plt.figure(figsize=(14, 8))
|
|
||||||
|
|
||||||
# set labels size
|
|
||||||
sn.set(font_scale=1.4)
|
|
||||||
|
|
||||||
# set font size
|
|
||||||
sn.heatmap(confusion_matrix, annot=True, annot_kws={"size": 8}, fmt="g")
|
|
||||||
|
|
||||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
|
||||||
experiment.log({f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False)
|
|
||||||
|
|
||||||
# according to wandb docs this should also work but it crashes
|
|
||||||
# experiment.log(f{"confusion_matrix/{experiment.name}": plt})
|
|
||||||
|
|
||||||
# reset plot
|
|
||||||
plt.clf()
|
|
||||||
|
|
||||||
self.preds.clear()
|
|
||||||
self.targets.clear()
|
|
||||||
|
|
||||||
|
|
||||||
class LogF1PrecRecHeatmap(Callback):
|
|
||||||
"""Generate f1, precision, recall heatmap every epoch and send it to wandb.
|
|
||||||
Expects validation step to return predictions and targets.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, class_names: List[str] = None):
|
|
||||||
self.preds = []
|
|
||||||
self.targets = []
|
|
||||||
self.ready = True
|
|
||||||
|
|
||||||
def on_sanity_check_start(self, trainer, pl_module):
|
|
||||||
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:
|
|
||||||
self.preds.append(outputs["preds"])
|
|
||||||
self.targets.append(outputs["targets"])
|
|
||||||
|
|
||||||
def on_validation_epoch_end(self, trainer, pl_module):
|
|
||||||
"""Generate f1, precision and recall heatmap."""
|
|
||||||
if self.ready:
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
preds = torch.cat(self.preds).cpu().numpy()
|
|
||||||
targets = torch.cat(self.targets).cpu().numpy()
|
|
||||||
f1 = f1_score(targets, preds, average=None)
|
|
||||||
r = recall_score(targets, preds, average=None)
|
|
||||||
p = precision_score(targets, preds, average=None)
|
|
||||||
data = [f1, p, r]
|
|
||||||
|
|
||||||
# set figure size
|
|
||||||
plt.figure(figsize=(14, 3))
|
|
||||||
|
|
||||||
# set labels size
|
|
||||||
sn.set(font_scale=1.2)
|
|
||||||
|
|
||||||
# set font size
|
|
||||||
sn.heatmap(
|
|
||||||
data,
|
|
||||||
annot=True,
|
|
||||||
annot_kws={"size": 10},
|
|
||||||
fmt=".3f",
|
|
||||||
yticklabels=["F1", "Precision", "Recall"],
|
|
||||||
)
|
|
||||||
|
|
||||||
# names should be uniqe or else charts from different experiments in wandb will overlap
|
|
||||||
experiment.log({f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False)
|
|
||||||
|
|
||||||
# reset plot
|
|
||||||
plt.clf()
|
|
||||||
|
|
||||||
self.preds.clear()
|
|
||||||
self.targets.clear()
|
|
||||||
|
|
||||||
|
|
||||||
class LogImagePredictions(Callback):
|
|
||||||
"""Logs a validation batch and their predictions to wandb.
|
|
||||||
Example adapted from:
|
|
||||||
https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, num_samples: int = 8):
|
|
||||||
super().__init__()
|
|
||||||
self.num_samples = num_samples
|
|
||||||
self.ready = True
|
|
||||||
|
|
||||||
def on_sanity_check_start(self, trainer, pl_module):
|
|
||||||
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_epoch_end(self, trainer, pl_module):
|
|
||||||
if self.ready:
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
# get a validation batch from the validation dat loader
|
|
||||||
val_samples = next(iter(trainer.datamodule.val_dataloader()))
|
|
||||||
val_imgs, val_labels = val_samples
|
|
||||||
|
|
||||||
# run the batch through the network
|
|
||||||
val_imgs = val_imgs.to(device=pl_module.device)
|
|
||||||
logits = pl_module(val_imgs)
|
|
||||||
preds = torch.argmax(logits, dim=-1)
|
|
||||||
|
|
||||||
# log the images as wandb Image
|
|
||||||
experiment.log(
|
|
||||||
{
|
|
||||||
f"Images/{experiment.name}": [
|
|
||||||
wandb.Image(x, caption=f"Pred:{pred}, Label:{y}")
|
|
||||||
for x, pred, y in zip(
|
|
||||||
val_imgs[: self.num_samples],
|
|
||||||
preds[: self.num_samples],
|
|
||||||
val_labels[: self.num_samples],
|
|
||||||
)
|
|
||||||
]
|
|
||||||
}
|
|
||||||
)
|
|
||||||
Reference in new issue
Block a user