Dev (#105)
* add printing ckpt path * refactor wandb callbacks * fix code formatting
This commit is contained in:
1 parent
755cd89cf0
commit
fca999f527
7 files changed
+124
-103
No files matched your search
@@ -143,3 +143,4 @@ dmypy.json
|
|||||||
# Lightning-Hydra-Template
|
# Lightning-Hydra-Template
|
||||||
data/
|
data/
|
||||||
logs/
|
logs/
|
||||||
|
wandb/
|
||||||
@@ -351,19 +351,19 @@ python run.py -m '+experiment=glob(*)'
|
|||||||
|
|
||||||
</details>
|
</details>
|
||||||
|
|
||||||
<!--
|
<!--
|
||||||
<details>
|
<details>
|
||||||
<summary>Use Hydra tab completion</summary>
|
<summary>Use Hydra tab completion</summary>
|
||||||
|
|
||||||
> *Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Read more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).*
|
> *Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing `tab` key. Read more [here](https://hydra.cc/docs/tutorials/basic/running_your_app/tab_completion).*
|
||||||
|
|
||||||
> *To install tab completion for bash shell, navigate to project folder and run the command below.*
|
> *To install tab completion for bash shell, navigate to project folder and run the command below.*
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
eval "$(python run.py -sc install=bash)"
|
eval "$(python run.py -sc install=bash)"
|
||||||
```
|
```
|
||||||
|
|
||||||
</details>
|
</details>
|
||||||
-->
|
-->
|
||||||
|
|
||||||
<br>
|
<br>
|
||||||
@@ -652,7 +652,7 @@ System specific variables (e.g. absolute paths to datasets) should not be under
|
|||||||
|
|
||||||
|
|
||||||
Template contains `.env.tmp` file. Change its name to `.env` (this name is excluded from version control in .gitignore).
|
Template contains `.env.tmp` file. Change its name to `.env` (this name is excluded from version control in .gitignore).
|
||||||
You should use it for storing environment variables like this:
|
You should use it for storing environment variables like this:
|
||||||
``` bash
|
``` bash
|
||||||
export MY_VAR=/home/user/my_system_path
|
export MY_VAR=/home/user/my_system_path
|
||||||
```
|
```
|
||||||
@@ -753,7 +753,7 @@ OmegaConf.register_new_resolver(
|
|||||||
This way you can reference any datamodule attribute from your config like this:
|
This way you can reference any datamodule attribute from your config like this:
|
||||||
```yaml
|
```yaml
|
||||||
# this will get 'datamodule.some_param' field
|
# this will get 'datamodule.some_param' field
|
||||||
some_parameter: ${datamodule: some_param}
|
some_parameter: ${datamodule: some_param}
|
||||||
```
|
```
|
||||||
When later accessing this field, say in your lightning model, it will get automatically resolved based on all resolvers that are registered. Remember not to access this field before datamodule is initialized. **You also need to set resolve to false in print_config() in [run.py](run.py) method or it will throw errors!**
|
When later accessing this field, say in your lightning model, it will get automatically resolved based on all resolvers that are registered. Remember not to access this field before datamodule is initialized. **You also need to set resolve to false in print_config() in [run.py](run.py) method or it will throw errors!**
|
||||||
```python
|
```python
|
||||||
@@ -761,7 +761,7 @@ template_utils.print_config(config, resolve=False)
|
|||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
<!-- TODO:
|
<!-- TODO:
|
||||||
PrettyErrors and Rich exception handling,
|
PrettyErrors and Rich exception handling,
|
||||||
k-fold cross validation, faster tab completion import trick,
|
k-fold cross validation, faster tab completion import trick,
|
||||||
choosing metric names with '/' for wandb -->
|
choosing metric names with '/' for wandb -->
|
||||||
|
|||||||
@@ -14,4 +14,4 @@ early_stopping:
|
|||||||
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
monitor: "val/acc" # name of the logged metric which determines when model is improving
|
||||||
patience: 100 # how many epochs of not improving until training stops
|
patience: 100 # how many epochs of not improving until training stops
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # can be "max" or "min"
|
||||||
min_delta: 0.0 # minimum change in the monitored metric needed to qualify as an improvement
|
min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement
|
||||||
@@ -10,7 +10,7 @@ upload_code_to_wandb_as_artifact:
|
|||||||
upload_ckpts_to_wandb_as_artifact:
|
upload_ckpts_to_wandb_as_artifact:
|
||||||
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
|
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
|
||||||
ckpt_dir: "checkpoints/"
|
ckpt_dir: "checkpoints/"
|
||||||
upload_best_only: False
|
upload_best_only: True
|
||||||
|
|
||||||
|
|
||||||
watch_model_with_wandb:
|
watch_model_with_wandb:
|
||||||
@@ -19,16 +19,9 @@ watch_model_with_wandb:
|
|||||||
log_freq: 100
|
log_freq: 100
|
||||||
|
|
||||||
|
|
||||||
# BUGGED :(
|
|
||||||
# save_best_metric_scores_to_wandb:
|
|
||||||
# _target_: src.callbacks.wandb_callbacks.LogBestMetricScoresToWandb
|
|
||||||
|
|
||||||
|
|
||||||
save_f1_precision_recall_heatmap_to_wandb:
|
save_f1_precision_recall_heatmap_to_wandb:
|
||||||
_target_: src.callbacks.wandb_callbacks.LogF1PrecisionRecallHeatmapToWandb
|
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb
|
||||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
|
||||||
|
|
||||||
|
|
||||||
save_confusion_matrix_to_wandb:
|
save_confusion_matrix_to_wandb:
|
||||||
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb
|
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb
|
||||||
class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
|
||||||
@@ -24,3 +24,6 @@ python-dotenv
|
|||||||
pre-commit
|
pre-commit
|
||||||
dvc
|
dvc
|
||||||
scikit-learn
|
scikit-learn
|
||||||
|
pandas
|
||||||
|
matplotlib
|
||||||
|
seaborn
|
||||||
@@ -2,27 +2,25 @@ import glob
|
|||||||
import os
|
import os
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
import pytorch_lightning as pl
|
import matplotlib.pyplot as plt
|
||||||
|
import seaborn as sn
|
||||||
import torch
|
import torch
|
||||||
import wandb
|
import wandb
|
||||||
from pytorch_lightning import Callback
|
from pytorch_lightning import Callback, Trainer
|
||||||
from pytorch_lightning.loggers import WandbLogger
|
from pytorch_lightning.loggers import WandbLogger
|
||||||
|
from sklearn import metrics
|
||||||
from sklearn.metrics import f1_score, precision_score, recall_score
|
from sklearn.metrics import f1_score, precision_score, recall_score
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
|
def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||||
logger = None
|
for logger in trainer.logger:
|
||||||
for lg in trainer.logger:
|
if isinstance(logger, WandbLogger):
|
||||||
if isinstance(lg, WandbLogger):
|
return logger
|
||||||
logger = lg
|
|
||||||
|
|
||||||
if not logger:
|
raise Exception(
|
||||||
raise Exception(
|
"You are using wandb related callback,"
|
||||||
"You are using wandb related callback,"
|
"but WandbLogger was not found for some reason..."
|
||||||
"but WandbLogger was not found for some reason..."
|
)
|
||||||
)
|
|
||||||
|
|
||||||
return logger
|
|
||||||
|
|
||||||
|
|
||||||
class UploadCodeToWandbAsArtifact(Callback):
|
class UploadCodeToWandbAsArtifact(Callback):
|
||||||
@@ -43,7 +41,7 @@ class UploadCodeToWandbAsArtifact(Callback):
|
|||||||
|
|
||||||
|
|
||||||
class UploadCheckpointsToWandbAsArtifact(Callback):
|
class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||||
"""Upload checkpoints to wandb as an artifact, at the end of training."""
|
"""Upload checkpoints to wandb as an artifact, at the end of run."""
|
||||||
|
|
||||||
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
||||||
self.ckpt_dir = ckpt_dir
|
self.ckpt_dir = ckpt_dir
|
||||||
@@ -78,16 +76,17 @@ class WatchModelWithWandb(Callback):
|
|||||||
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
|
||||||
|
|
||||||
|
|
||||||
class LogF1PrecisionRecallHeatmapToWandb(Callback):
|
class LogConfusionMatrixToWandb(Callback):
|
||||||
"""
|
"""Generate confusion matrix every epoch and send it to wandb.
|
||||||
Generate f1, precision and recall heatmap from validation step outputs.
|
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, class_names: List[str] = None):
|
def __init__(self):
|
||||||
self.class_names = class_names
|
|
||||||
self.preds = []
|
self.preds = []
|
||||||
self.targets = []
|
self.targets = []
|
||||||
|
self.ready = True
|
||||||
|
|
||||||
|
def on_sanity_check_start(self, trainer, pl_module) -> None:
|
||||||
self.ready = False
|
self.ready = False
|
||||||
|
|
||||||
def on_sanity_check_end(self, trainer, pl_module):
|
def on_sanity_check_end(self, trainer, pl_module):
|
||||||
@@ -99,9 +98,68 @@ class LogF1PrecisionRecallHeatmapToWandb(Callback):
|
|||||||
):
|
):
|
||||||
"""Gather data from single batch."""
|
"""Gather data from single batch."""
|
||||||
if self.ready:
|
if self.ready:
|
||||||
preds, targets = outputs["preds"], outputs["targets"]
|
self.preds.append(outputs["preds"])
|
||||||
self.preds.append(preds)
|
self.targets.append(outputs["targets"])
|
||||||
self.targets.append(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 LogF1PrecRecHeatmapToWandb(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):
|
def on_validation_epoch_end(self, trainer, pl_module):
|
||||||
"""Generate f1, precision and recall heatmap."""
|
"""Generate f1, precision and recall heatmap."""
|
||||||
@@ -109,72 +167,35 @@ class LogF1PrecisionRecallHeatmapToWandb(Callback):
|
|||||||
logger = get_wandb_logger(trainer=trainer)
|
logger = get_wandb_logger(trainer=trainer)
|
||||||
experiment = logger.experiment
|
experiment = logger.experiment
|
||||||
|
|
||||||
self.preds = torch.cat(self.preds).cpu()
|
preds = torch.cat(self.preds).cpu().numpy()
|
||||||
self.targets = torch.cat(self.targets).cpu()
|
targets = torch.cat(self.targets).cpu().numpy()
|
||||||
f1 = f1_score(self.preds, self.targets, average=None)
|
f1 = f1_score(preds, targets, average=None)
|
||||||
r = recall_score(self.preds, self.targets, average=None)
|
r = recall_score(preds, targets, average=None)
|
||||||
p = precision_score(self.preds, self.targets, average=None)
|
p = precision_score(preds, targets, average=None)
|
||||||
|
data = [f1, p, r]
|
||||||
|
|
||||||
experiment.log(
|
# set figure size
|
||||||
{
|
plt.figure(figsize=(14, 3))
|
||||||
f"f1_p_r_heatmap/{trainer.current_epoch}_{experiment.id}": wandb.plots.HeatMap(
|
|
||||||
x_labels=self.class_names,
|
# set labels size
|
||||||
y_labels=["f1", "precision", "recall"],
|
sn.set(font_scale=1.2)
|
||||||
matrix_values=[f1, p, r],
|
|
||||||
show_text=True,
|
# set font size
|
||||||
)
|
sn.heatmap(
|
||||||
},
|
data,
|
||||||
commit=False,
|
annot=True,
|
||||||
|
annot_kws={"size": 10},
|
||||||
|
fmt=".3f",
|
||||||
|
yticklabels=["F1", "Precision", "Recall"],
|
||||||
)
|
)
|
||||||
|
|
||||||
self.preds = []
|
# names should be uniqe or else charts from different experiments in wandb will overlap
|
||||||
self.targets = []
|
|
||||||
|
|
||||||
|
|
||||||
class LogConfusionMatrixToWandb(Callback):
|
|
||||||
"""
|
|
||||||
Generate Confusion Matrix.
|
|
||||||
Expects validation step to return predictions and targets.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, class_names: List[str] = None):
|
|
||||||
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["preds"], outputs["targets"]
|
|
||||||
self.preds.append(preds)
|
|
||||||
self.targets.append(targets)
|
|
||||||
|
|
||||||
def on_validation_epoch_end(self, trainer, pl_module):
|
|
||||||
"""Generate confusion matrix."""
|
|
||||||
if self.ready:
|
|
||||||
logger = get_wandb_logger(trainer=trainer)
|
|
||||||
experiment = logger.experiment
|
|
||||||
|
|
||||||
self.preds = torch.cat(self.preds).tolist()
|
|
||||||
self.targets = torch.cat(self.targets).tolist()
|
|
||||||
|
|
||||||
experiment.log(
|
experiment.log(
|
||||||
{
|
{f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False
|
||||||
f"confusion_matrix/{trainer.current_epoch}_{experiment.id}": wandb.plot.confusion_matrix(
|
|
||||||
preds=self.preds,
|
|
||||||
y_true=self.targets,
|
|
||||||
class_names=self.class_names,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
commit=False,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.preds = []
|
# reset plot
|
||||||
self.targets = []
|
plt.clf()
|
||||||
|
|
||||||
|
self.preds.clear()
|
||||||
|
self.targets.clear()
|
||||||
@@ -93,6 +93,9 @@ def train(config: DictConfig) -> Optional[float]:
|
|||||||
logger=logger,
|
logger=logger,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Print path to best checkpoint
|
||||||
|
log.info(f"Best checkpoint path:\n{trainer.checkpoint_callback.best_model_path}")
|
||||||
|
|
||||||
# Return metric score for Optuna optimization
|
# Return metric score for Optuna optimization
|
||||||
optimized_metric = config.get("optimized_metric")
|
optimized_metric = config.get("optimized_metric")
|
||||||
if optimized_metric:
|
if optimized_metric:
|
||||||
|
|||||||
Reference in new issue
Block a user