change folder structure
This commit is contained in:
1 parent
fbe2464426
commit
9a5a4eb192
23 files changed
+148
-120
No files matched your search
@@ -16,7 +16,7 @@ Click on <b>"Use this template"</b> button above to initialize new repository.<b
|
|||||||
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
- Built in conda environment initialization ([conda_env.yaml](conda_env.yaml))
|
||||||
- Built in package setup ([setup.py](setup.py))
|
- Built in package setup ([setup.py](setup.py))
|
||||||
- Example with MNIST digits classification
|
- Example with MNIST digits classification
|
||||||
- Useful example callbacks ([callbacks.py](project/pytorch_modules/lightning_callbacks/custom_callbacks.py))
|
- Useful example callbacks ([callbacks.py](project/src/callbacks/custom_callbacks.py))
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
@@ -83,7 +83,7 @@ loggers:
|
|||||||
default_callbacks:
|
default_callbacks:
|
||||||
ModelCheckpoint:
|
ModelCheckpoint:
|
||||||
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
|
||||||
save_top_k: 1 <- save k best lightning_models (determined by above metric)
|
save_top_k: 1 <- save k best models (determined by above metric)
|
||||||
save_last: True <- additionaly always save model from last epoch
|
save_last: True <- additionaly always save model from last epoch
|
||||||
mode: "max" <- can be "max" or "min"
|
mode: "max" <- can be "max" or "min"
|
||||||
EarlyStopping:
|
EarlyStopping:
|
||||||
@@ -113,7 +113,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
|||||||
max_epochs: 10
|
max_epochs: 10
|
||||||
model:
|
model:
|
||||||
load_from:
|
load_from:
|
||||||
model_path: "lightning_models/simple_mnist_classifier/simple_mnist_classifier.py"
|
model_path: "models/simple_mnist_classifier/simple_mnist_classifier.py"
|
||||||
model_class: "LitModel"
|
model_class: "LitModel"
|
||||||
hparams:
|
hparams:
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
@@ -125,7 +125,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
|||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
datamodule:
|
datamodule:
|
||||||
load_from:
|
load_from:
|
||||||
datamodule_path: "lightning_datamodules/mnist_datamodule/mnist_datamodule.py"
|
datamodule_path: "datamodules/mnist_datamodule/mnist_datamodule.py"
|
||||||
datamodule_class: "MNISTDataModule"
|
datamodule_class: "MNISTDataModule"
|
||||||
hparams:
|
hparams:
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
@@ -138,9 +138,9 @@ Each run configuration needs to contain sections `trainer`, `model` and `datamod
|
|||||||
Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<br>
|
Every other section is optional! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<br>
|
||||||
|
|
||||||
|
|
||||||
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/pytorch_modules/lightning_models/simple_mnist_classifier.py)).<br>
|
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/src/models/simple_mnist_classifier.py)).<br>
|
||||||
|
|
||||||
Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/pytorch_modules/lightning_datamodules/mnist_datamodule.py)).<br>
|
Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_datamodule](project/src/datamodules/mnist_datamodule.py)).<br>
|
||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
#name: conda_env_name
|
#name: conda_env_name
|
||||||
|
|
||||||
channels:
|
channels:
|
||||||
- pytorch
|
- pytorch
|
||||||
- conda-forge
|
- conda-forge
|
||||||
- defaults
|
- defaults
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
- python=3.8
|
- python=3.8
|
||||||
- pip
|
- pip
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ model_checkpoint:
|
|||||||
class: pytorch_lightning.callbacks.ModelCheckpoint
|
class: pytorch_lightning.callbacks.ModelCheckpoint
|
||||||
args:
|
args:
|
||||||
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
|
||||||
save_top_k: 1 # save k best lightning_models (determined by above metric)
|
save_top_k: 1 # save k best models (determined by above metric)
|
||||||
save_last: True # additionaly always save model from last epoch
|
save_last: True # additionaly always save model from last epoch
|
||||||
mode: "max" # can be "max" or "min"
|
mode: "max" # can be "max" or "min"
|
||||||
filepath: "checkpoints/{epoch}"
|
filepath: "checkpoints/{epoch}"
|
||||||
|
|||||||
@@ -1,2 +1,5 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
|
defaults:
|
||||||
|
- default_callbacks.yaml
|
||||||
|
- wandb_callbacks.yaml
|
||||||
@@ -1,18 +1,31 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
save_best_metric_scores_to_wandb:
|
save_best_metric_scores_to_wandb:
|
||||||
class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
class: src.callbacks.wandb_callbacks.SaveBestMetricScoresToWandb
|
||||||
args: {}
|
args: {}
|
||||||
|
|
||||||
|
|
||||||
save_code_to_wandb_as_artifact:
|
#save_confusion_matrix_to_wandb:
|
||||||
class: pytorch_modules.lightning_callbacks.wandb_callbacks.SaveCodeToWandb
|
# class: src.callbacks.wandb_callbacks.SaveConfusionMatrixToWandb
|
||||||
args:
|
# args:
|
||||||
code_dir: ${work_dir}/
|
# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||||
|
#
|
||||||
|
#
|
||||||
|
#save_f1_precision_recall_heatmap_to_wandb:
|
||||||
|
# class: src.callbacks.wandb_callbacks.SaveMetricsHeatmapToWandb
|
||||||
|
# args:
|
||||||
|
# class_names: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
|
||||||
|
|
||||||
|
|
||||||
upload_ckpts_to_wandb_as_artifact:
|
#upload_code_to_wandb_as_artifact:
|
||||||
class: pytorch_modules.lightning_callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
# class: src.callbacks.wandb_callbacks.SaveCodeToWandb
|
||||||
args:
|
# args:
|
||||||
ckpt_dir: "checkpoints/"
|
# code_dir: ${work_dir}/
|
||||||
upload_best_only: True
|
|
||||||
|
|
||||||
|
#upload_ckpts_to_wandb_as_artifact:
|
||||||
|
# class: src.callbacks.wandb_callbacks.UploadAllCheckpointsToWandb
|
||||||
|
# args:
|
||||||
|
# ckpt_dir: "checkpoints/"
|
||||||
|
# upload_best_only: True
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ hydra:
|
|||||||
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
|
|
||||||
# extra things that are logged by all loggers as hyperparameters, before training starts
|
# extra things that are logged by all loggers as hyperparameters
|
||||||
extra_logs:
|
extra_logs:
|
||||||
log_seeds: True
|
log_seeds: True
|
||||||
|
|
||||||
@@ -33,6 +33,6 @@ extra_logs:
|
|||||||
log_model_class: True
|
log_model_class: True
|
||||||
log_optimizer_class: True
|
log_optimizer_class: True
|
||||||
log_datamodule_class: True
|
log_datamodule_class: True
|
||||||
|
log_model_architecture_class: True
|
||||||
|
|
||||||
log_train_val_test_sizes: True
|
log_train_val_test_sizes: False
|
||||||
log_model_architecture_class_name: True
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
class: pytorch_modules.lightning_datamodules.mnist_datamodule.MNISTDataModule
|
class: src.datamodules.mnist_datamodule.MNISTDataModule
|
||||||
args:
|
args:
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: [55_000, 5_000, 10_000]
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ trainer:
|
|||||||
limit_val_batches: 0.9 # validate on 90% of validation data
|
limit_val_batches: 0.9 # validate on 90% of validation data
|
||||||
limit_test_batches: 1.0 # test on 100% of test data
|
limit_test_batches: 1.0 # test on 100% of test data
|
||||||
val_check_interval: 0.5 # perform validation twice per epoch
|
val_check_interval: 0.5 # perform validation twice per epoch
|
||||||
# resume_from_checkpoint: ${work_dir}/last.ckpt # use this to resume training from checkpoint
|
# resume_from_checkpoint: ${work_dir}/last.ckpt # path to checkpoint (this can be also url for download)
|
||||||
|
|
||||||
model:
|
model:
|
||||||
args: # you can add here any params you want and then access them in lightning model
|
args: # you can add here any params you want and then access them in lightning model
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
class: pytorch_modules.lightning_models.simple_mnist_classifier.LitModel
|
class: src.models.simple_mnist_classifier.LitModel
|
||||||
args:
|
args:
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
weight_decay: 0.00001
|
weight_decay: 0.00001
|
||||||
|
|||||||
@@ -3,9 +3,11 @@
|
|||||||
# default args passed to Lightning Trainer on every experiment
|
# default args passed to Lightning Trainer on every experiment
|
||||||
# they can be combined or overwritten with args set in experiment config
|
# they can be combined or overwritten with args set in experiment config
|
||||||
args:
|
args:
|
||||||
gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||||
auto_select_gpus: True
|
auto_select_gpus: True
|
||||||
|
max_epochs: 10
|
||||||
num_sanity_val_steps: 3
|
num_sanity_val_steps: 3
|
||||||
progress_bar_refresh_rate: 10
|
progress_bar_refresh_rate: 10
|
||||||
weights_summary: null # null in yaml represents python None value
|
weights_summary: null # null in yaml represents python None value
|
||||||
default_root_dir: "lightning_logs/"
|
default_root_dir: "lightning_logs/"
|
||||||
|
auto_lr_find: False # "https://pytorch-lightning.readthedocs.io/en/stable/lr_finder.html"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# package file
|
||||||
File renamed without changes.
File renamed without changes.
+23
-54
@@ -47,7 +47,7 @@ class SaveMetricsHeatmapToWandb(Callback):
|
|||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
Works only for single label classification!
|
Works only for single label classification!
|
||||||
"""
|
"""
|
||||||
def __init__(self, class_names):
|
def __init__(self, class_names=None):
|
||||||
self.class_names = class_names
|
self.class_names = class_names
|
||||||
self.preds = []
|
self.preds = []
|
||||||
self.targets = []
|
self.targets = []
|
||||||
@@ -60,7 +60,7 @@ class SaveMetricsHeatmapToWandb(Callback):
|
|||||||
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||||
"""Gather data from single batch."""
|
"""Gather data from single batch."""
|
||||||
if self.ready:
|
if self.ready:
|
||||||
preds, targets = outputs["preds"], outputs["y"]
|
preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
|
||||||
self.preds.append(preds)
|
self.preds.append(preds)
|
||||||
self.targets.append(targets)
|
self.targets.append(targets)
|
||||||
|
|
||||||
@@ -96,7 +96,7 @@ class SaveConfusionMatrixToWandb(Callback):
|
|||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
Works only for single label classification!
|
Works only for single label classification!
|
||||||
"""
|
"""
|
||||||
def __init__(self, class_names):
|
def __init__(self, class_names=None):
|
||||||
self.class_names = class_names
|
self.class_names = class_names
|
||||||
self.preds = []
|
self.preds = []
|
||||||
self.targets = []
|
self.targets = []
|
||||||
@@ -109,7 +109,7 @@ class SaveConfusionMatrixToWandb(Callback):
|
|||||||
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
||||||
"""Gather data from single batch."""
|
"""Gather data from single batch."""
|
||||||
if self.ready:
|
if self.ready:
|
||||||
preds, targets = outputs["preds"], outputs["y"]
|
preds, targets = outputs["batch_val_preds"], outputs["batch_val_y"]
|
||||||
self.preds.append(preds)
|
self.preds.append(preds)
|
||||||
self.targets.append(targets)
|
self.targets.append(targets)
|
||||||
|
|
||||||
@@ -119,17 +119,14 @@ class SaveConfusionMatrixToWandb(Callback):
|
|||||||
self.preds = torch.cat(self.preds).tolist()
|
self.preds = torch.cat(self.preds).tolist()
|
||||||
self.targets = torch.cat(self.targets).tolist()
|
self.targets = torch.cat(self.targets).tolist()
|
||||||
|
|
||||||
logger = None
|
for logger in trainer.logger.experiment:
|
||||||
for some_logger in trainer.logger.experiment:
|
if isinstance(logger, wandb_run):
|
||||||
if isinstance(some_logger, wandb_run):
|
logger.log({
|
||||||
logger = some_logger
|
f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
|
||||||
|
preds=self.preds,
|
||||||
logger.log({
|
y_true=self.targets,
|
||||||
f"conf_mat_{trainer.current_epoch}_{logger.id}": wandb.plot.confusion_matrix(
|
class_names=self.class_names)
|
||||||
self.preds,
|
}, commit=False)
|
||||||
self.targets,
|
|
||||||
class_names=self.class_names)
|
|
||||||
}, commit=False)
|
|
||||||
|
|
||||||
self.preds = []
|
self.preds = []
|
||||||
self.targets = []
|
self.targets = []
|
||||||
@@ -137,62 +134,34 @@ class SaveConfusionMatrixToWandb(Callback):
|
|||||||
|
|
||||||
class SaveBestMetricScoresToWandb(Callback):
|
class SaveBestMetricScoresToWandb(Callback):
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.train_loss_list = []
|
|
||||||
self.train_acc_list = []
|
|
||||||
self.train_loss_best = None
|
self.train_loss_best = None
|
||||||
self.train_acc_best = None
|
self.train_acc_best = None
|
||||||
|
|
||||||
self.val_loss_list = []
|
|
||||||
self.val_acc_list = []
|
|
||||||
self.val_loss_best = None
|
self.val_loss_best = None
|
||||||
self.val_acc_best = None
|
self.val_acc_best = None
|
||||||
|
|
||||||
self.ready = False
|
self.ready = False
|
||||||
|
|
||||||
def clear_lists(self):
|
|
||||||
self.train_loss_list.clear()
|
|
||||||
self.train_acc_list.clear()
|
|
||||||
self.val_loss_list.clear()
|
|
||||||
self.val_acc_list.clear()
|
|
||||||
|
|
||||||
def on_sanity_check_end(self, trainer, pl_module):
|
def on_sanity_check_end(self, trainer, pl_module):
|
||||||
"""Start executing this callback only after all validation sanity checks end."""
|
"""Start executing this callback only after all validation sanity checks end."""
|
||||||
self.ready = True
|
self.ready = True
|
||||||
|
|
||||||
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
|
||||||
"""Gather data from single batch."""
|
|
||||||
# This is bugged :/ - lets wait for lightning 1.2 update
|
|
||||||
# if self.ready:
|
|
||||||
# self.train_loss_list.append(outputs["loss"])
|
|
||||||
# self.train_acc_list.append(outputs["acc"])
|
|
||||||
pass
|
|
||||||
|
|
||||||
def on_validation_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
|
||||||
"""Gather data from single batch."""
|
|
||||||
if self.ready:
|
|
||||||
self.val_loss_list.append(outputs["loss"])
|
|
||||||
self.val_acc_list.append(outputs["acc"])
|
|
||||||
|
|
||||||
def on_epoch_end(self, trainer, pl_module):
|
def on_epoch_end(self, trainer, pl_module):
|
||||||
if self.ready:
|
if self.ready:
|
||||||
for logger in trainer.logger.experiment:
|
for logger in trainer.logger.experiment:
|
||||||
|
metrics = trainer.callback_metrics
|
||||||
if isinstance(logger, wandb_run):
|
if isinstance(logger, wandb_run):
|
||||||
# loss = sum(self.train_loss_list) / len(self.train_loss_list)
|
if self.train_loss_best is None or metrics["train_loss"] < self.train_loss_best:
|
||||||
# acc = sum(self.train_acc_list) / len(self.train_acc_list)
|
self.train_loss_best = metrics["train_loss"]
|
||||||
# self.train_loss_best = loss if self.train_loss_best is None or loss < self.train_loss_best else self.train_loss_best
|
if self.train_acc_best is None or metrics["train_acc"] > self.train_acc_best:
|
||||||
# self.train_acc_best = acc if self.train_acc_best is None or acc > self.train_acc_best else self.train_acc_best
|
self.train_acc_best = metrics["train_acc"]
|
||||||
# logger.log({"train_loss_best": self.train_loss_best}, commit=False)
|
if self.val_loss_best is None or metrics["val_loss"] < self.val_loss_best:
|
||||||
# logger.log({"train_acc_best": self.train_acc_best}, commit=False)
|
self.val_loss_best = metrics["val_loss"]
|
||||||
|
if self.val_acc_best is None or metrics["val_acc"] > self.val_acc_best:
|
||||||
loss = sum(self.val_loss_list) / len(self.val_loss_list)
|
self.val_acc_best = metrics["val_acc"]
|
||||||
acc = sum(self.val_acc_list) / len(self.val_acc_list)
|
logger.log({"train_loss_best": self.train_loss_best}, commit=False)
|
||||||
self.val_loss_best = loss if self.val_loss_best is None or loss < self.val_loss_best else self.val_loss_best
|
logger.log({"train_acc_best": self.train_acc_best}, commit=False)
|
||||||
self.val_acc_best = acc if self.val_acc_best is None or acc > self.val_acc_best else self.val_acc_best
|
|
||||||
logger.log({"val_loss_best": self.val_loss_best}, commit=False)
|
logger.log({"val_loss_best": self.val_loss_best}, commit=False)
|
||||||
logger.log({"val_acc_best": self.val_acc_best}, commit=False)
|
logger.log({"val_acc_best": self.val_acc_best}, commit=False)
|
||||||
|
|
||||||
self.clear_lists()
|
|
||||||
|
|
||||||
|
|
||||||
# class SaveImagePredictionsToWandb(Callback):
|
# class SaveImagePredictionsToWandb(Callback):
|
||||||
# """
|
# """
|
||||||
File renamed without changes.
File renamed without changes.
+12
-10
@@ -1,11 +1,11 @@
|
|||||||
from sklearn.metrics import accuracy_score
|
from pytorch_lightning.metrics.classification import Accuracy
|
||||||
|
from template_utils.initializers import load_class
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
import torch.nn.functional as F
|
import torch.nn.functional as F
|
||||||
import torch
|
import torch
|
||||||
from template_utils.initializers import load_class
|
|
||||||
|
|
||||||
# import custom architectures
|
# import custom architectures
|
||||||
from pytorch_modules.architectures.simple_mnist import SimpleMNISTClassifier
|
from src.architectures.simple_mnist import SimpleMNISTClassifier
|
||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
@@ -25,6 +25,8 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
self.model = SimpleMNISTClassifier(hparams=self.hparams)
|
||||||
|
|
||||||
|
self.accuracy = Accuracy()
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
|
|
||||||
@@ -36,12 +38,11 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# training metrics
|
# training metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = self.accuracy(preds, y)
|
||||||
self.log('train_loss', loss, on_step=False, on_epoch=True)
|
self.log('train_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log('train_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
# we can return here anything and then read it in some callback
|
return loss
|
||||||
return {"loss": loss, "acc": acc, "preds": preds, "y": y}
|
|
||||||
|
|
||||||
# logic for a single validation step
|
# logic for a single validation step
|
||||||
def validation_step(self, batch, batch_idx):
|
def validation_step(self, batch, batch_idx):
|
||||||
@@ -51,11 +52,12 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# validation metrics
|
# validation metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = self.accuracy(preds, y)
|
||||||
self.log('val_loss', loss, on_step=False, on_epoch=True)
|
self.log('val_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
self.log('val_acc', acc, on_step=False, on_epoch=True, prog_bar=True)
|
||||||
|
|
||||||
return {"loss": loss, "acc": acc, "preds": preds, "y": y}
|
# we can return here anything and then read it in some callback
|
||||||
|
return {"batch_val_loss": loss, "batch_val_acc": acc, "batch_val_preds": preds, "batch_val_y": y}
|
||||||
|
|
||||||
# logic for a single testing step
|
# logic for a single testing step
|
||||||
def test_step(self, batch, batch_idx):
|
def test_step(self, batch, batch_idx):
|
||||||
@@ -65,11 +67,11 @@ class LitModel(pl.LightningModule):
|
|||||||
|
|
||||||
# test metrics
|
# test metrics
|
||||||
preds = torch.argmax(logits, dim=1)
|
preds = torch.argmax(logits, dim=1)
|
||||||
acc = accuracy_score(preds.cpu(), y.cpu())
|
acc = self.accuracy(preds, y)
|
||||||
self.log('test_loss', loss, on_step=False, on_epoch=True)
|
self.log('test_loss', loss, on_step=False, on_epoch=True)
|
||||||
self.log('test_acc', acc, on_step=False, on_epoch=True)
|
self.log('test_acc', acc, on_step=False, on_epoch=True)
|
||||||
|
|
||||||
return {"loss": loss}
|
return loss
|
||||||
|
|
||||||
def configure_optimizers(self):
|
def configure_optimizers(self):
|
||||||
Optimizer = load_class(self.optimizer_config["class"])
|
Optimizer = load_class(self.optimizer_config["class"])
|
||||||
File renamed without changes.
@@ -1,31 +1,42 @@
|
|||||||
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
|
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
|
||||||
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
|
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
|
||||||
|
|
||||||
|
# hydra imports
|
||||||
|
from omegaconf import DictConfig
|
||||||
|
import hydra
|
||||||
|
|
||||||
|
# template utils imports
|
||||||
|
import template_utils.initializers as utils
|
||||||
|
|
||||||
import wandb
|
import wandb
|
||||||
import train
|
from train import train
|
||||||
|
|
||||||
|
|
||||||
# Choose which run config to optimize
|
|
||||||
RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
|
|
||||||
|
|
||||||
# Load configs
|
|
||||||
project_config = train.load_config("config.yaml")
|
|
||||||
run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
|
|
||||||
|
|
||||||
# Initialize wandb
|
|
||||||
wandb.init()
|
|
||||||
|
|
||||||
# Replace run config hyperparameters with the ones loaded from wandb sweep server
|
# Replace run config hyperparameters with the ones loaded from wandb sweep server
|
||||||
sweep_hparams = wandb.Config._as_dict(wandb.config)
|
def replace_hparams(config, sweep_hparams):
|
||||||
for key, value in sweep_hparams.items():
|
for key, value in sweep_hparams.items():
|
||||||
if key == "_wandb":
|
if key == "_wandb":
|
||||||
continue
|
continue
|
||||||
elif key in run_config["trainer"]["args"]:
|
elif key in config["trainer"]["args"]:
|
||||||
run_config["trainer"]["args"][key] = value
|
config["trainer"]["args"][key] = value
|
||||||
elif key in run_config["model"]["hparams"]:
|
elif key in config["model"]["args"]:
|
||||||
run_config["model"]["hparams"][key] = value
|
config["model"]["args"][key] = value
|
||||||
elif key in run_config["datamodule"]["hparams"]:
|
elif key in config["optimizer"]["args"]:
|
||||||
run_config["datamodule"]["hparams"][key] = value
|
config["optimizer"]["args"][key] = value
|
||||||
|
elif key in config["datamodule"]["args"]:
|
||||||
|
config["datamodule"]["args"][key] = value
|
||||||
|
|
||||||
# Execute run
|
|
||||||
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
|
def main(config: DictConfig) -> None:
|
||||||
|
wandb.init()
|
||||||
|
|
||||||
|
sweep_hparams = wandb.Config._as_dict(wandb.config)
|
||||||
|
utils.show_config(config) # print content of config
|
||||||
|
|
||||||
|
train(config)
|
||||||
|
wandb.finish()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
from pytorch_modules.transforms import mnist_transforms
|
from src.transforms import mnist_transforms
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
# the LitModel you import should be the same as the one you used for training!
|
# the LitModel you import should be the same as the one you used for training!
|
||||||
from pytorch_modules.lightning_models.simple_mnist_classifier import LitModel
|
from src.models.simple_mnist_classifier import LitModel
|
||||||
|
|
||||||
# ckpt can be a url!
|
# ckpt can be a url!
|
||||||
|
|
||||||
|
|||||||
@@ -138,11 +138,11 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
|
|||||||
log_hparams(loggers, config["datamodule"]["args"])
|
log_hparams(loggers, config["datamodule"]["args"])
|
||||||
|
|
||||||
if "log_model_class" in extra_logs and extra_logs["log_model_class"]:
|
if "log_model_class" in extra_logs and extra_logs["log_model_class"]:
|
||||||
log_hparams(loggers, {"model_class": config["model"]["class"]})
|
log_hparams(loggers, {"_class_model": config["model"]["class"]})
|
||||||
if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]:
|
if "log_optimizer_class" in extra_logs and extra_logs["log_optimizer_class"]:
|
||||||
log_hparams(loggers, {"optimizer_class": config["optimizer"]["class"]})
|
log_hparams(loggers, {"_class_optimizer": config["optimizer"]["class"]})
|
||||||
if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]:
|
if "log_datamodule_class" in extra_logs and extra_logs["log_datamodule_class"]:
|
||||||
log_hparams(loggers, {"datamodule_class": config["datamodule"]["class"]})
|
log_hparams(loggers, {"_class_datamodule": config["datamodule"]["class"]})
|
||||||
|
|
||||||
if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]:
|
if "log_train_val_test_sizes" in extra_logs and extra_logs["log_train_val_test_sizes"]:
|
||||||
hparams = {}
|
hparams = {}
|
||||||
@@ -154,9 +154,10 @@ def log_extra_hparams(loggers: List[pl.loggers.LightningLoggerBase],
|
|||||||
hparams["test_size"] = len(datamodule.data_test)
|
hparams["test_size"] = len(datamodule.data_test)
|
||||||
log_hparams(loggers, hparams)
|
log_hparams(loggers, hparams)
|
||||||
|
|
||||||
if "log_model_architecture_class_name" in extra_logs and extra_logs["log_model_architecture_class_name"]:
|
if "log_model_architecture_class" in extra_logs and extra_logs["log_model_architecture_class"]:
|
||||||
if hasattr(model, "model"):
|
if hasattr(model, "model"):
|
||||||
log_hparams(loggers, {"model_architecture_class_name": model.model.__class__.__name__})
|
obj = model.model
|
||||||
|
log_hparams(loggers, {"_class_model_architecture": obj.__module__ + "." + obj.__class__.__name__})
|
||||||
|
|
||||||
|
|
||||||
def show_init_info(model, datamodule, callbacks, loggers):
|
def show_init_info(model, datamodule, callbacks, loggers):
|
||||||
@@ -177,6 +178,19 @@ def show_init_info(model, datamodule, callbacks, loggers):
|
|||||||
log.info(message)
|
log.info(message)
|
||||||
|
|
||||||
|
|
||||||
|
def auto_find_lr(trainer, model, datamodule, loggers):
|
||||||
|
lr_finder = trainer.tuner.lr_find(model=model, datamodule=datamodule)
|
||||||
|
new_lr = lr_finder.suggestion()
|
||||||
|
|
||||||
|
# Save lr plot
|
||||||
|
fig = lr_finder.plot(suggest=True)
|
||||||
|
fig.savefig("lr_loss_curve.jpg")
|
||||||
|
|
||||||
|
# Set new lr
|
||||||
|
model.hparams.lr = new_lr
|
||||||
|
log_hparams(loggers, {"lr": new_lr})
|
||||||
|
|
||||||
|
|
||||||
def show_config(config: DictConfig):
|
def show_config(config: DictConfig):
|
||||||
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
|
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}")
|
||||||
|
|
||||||
|
|||||||
+6
-1
@@ -21,13 +21,18 @@ def my_app(cfg: DictConfig) -> None:
|
|||||||
def test_logger():
|
def test_logger():
|
||||||
logger = WandbLogger()
|
logger = WandbLogger()
|
||||||
print(logger)
|
print(logger)
|
||||||
|
print(logger.__class__)
|
||||||
|
print(logger.__class__.__name__)
|
||||||
|
print(logger.__module__)
|
||||||
|
print(logger.__module__ + "." + logger.__class__.__name__)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
my_app()
|
my_app()
|
||||||
|
|
||||||
|
|
||||||
# with open("epoch=0.ckpt", "rb") as file:
|
# with open("epoch=0.ckpt", "rb") as file:
|
||||||
# data = torch.load(file)
|
# data = torch.load(file)
|
||||||
# print(data)
|
# print(data)
|
||||||
|
|
||||||
# test_logger()
|
test_logger()
|
||||||
@@ -16,6 +16,7 @@ import template_utils.initializers as utils
|
|||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train(config):
|
||||||
|
# Validate the correctness of loaded config
|
||||||
utils.validate_config(config=config)
|
utils.validate_config(config=config)
|
||||||
|
|
||||||
# Set global PyTorch seed
|
# Set global PyTorch seed
|
||||||
@@ -56,6 +57,7 @@ def train(config):
|
|||||||
callbacks=callbacks
|
callbacks=callbacks
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Log info in terminal about all initialized objects
|
||||||
utils.show_init_info(model, datamodule, callbacks, loggers)
|
utils.show_init_info(model, datamodule, callbacks, loggers)
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
@@ -65,6 +67,10 @@ def train(config):
|
|||||||
loggers=loggers
|
loggers=loggers
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Automatically find learning rate if specified in config
|
||||||
|
if "auto_lr_find" in config["trainer"]["args"] and config["trainer"]["args"]["auto_lr_find"]:
|
||||||
|
utils.auto_find_lr(trainer, model, datamodule, loggers)
|
||||||
|
|
||||||
# Train the model
|
# Train the model
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=model, datamodule=datamodule)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user