7 files changed
+75
-38
No files matched your search
+2
-1
@@ -1,7 +1,7 @@
|
||||
num_of_gpus: -1
|
||||
|
||||
hparams:
|
||||
max_epochs: 20
|
||||
max_epochs: 10
|
||||
batch_size: 64
|
||||
lr: 0.001
|
||||
accumulate_grad_batches: 1
|
||||
@@ -26,6 +26,7 @@ loggers:
|
||||
job_type: "train"
|
||||
tags: []
|
||||
log_model: True
|
||||
offline: False
|
||||
|
||||
callbacks:
|
||||
checkpoint:
|
||||
|
||||
Binary file not shown.
@@ -5,6 +5,8 @@ import os
|
||||
|
||||
|
||||
class ExampleCallback(Callback):
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
def on_init_start(self, trainer):
|
||||
print('Starting to initialize trainer!')
|
||||
@@ -17,12 +19,12 @@ class ExampleCallback(Callback):
|
||||
|
||||
|
||||
class SaveOnnxToWandbCallback(Callback):
|
||||
|
||||
def __init__(self, dataloader, wandb_save_dir):
|
||||
first_batch = next(iter(dataloader))
|
||||
"""Save model in .onnx format."""
|
||||
def __init__(self, datamodule, save_dir):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
x, y = first_batch
|
||||
self.dummy_input = x
|
||||
self.save_dir = wandb_save_dir
|
||||
self.save_dir = save_dir
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
@@ -37,6 +39,7 @@ class SaveOnnxToWandbCallback(Callback):
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(Callback):
|
||||
"""Each epoch upload to wandb a couple of the same images with predicted labels."""
|
||||
def __init__(self, val_samples, num_samples=32):
|
||||
super().__init__()
|
||||
self.val_imgs, self.val_labels = val_samples[:num_samples]
|
||||
@@ -47,8 +50,39 @@ class ImagePredictionLoggerCallback(Callback):
|
||||
logits = pl_module(val_imgs)
|
||||
preds = torch.argmax(logits, -1)
|
||||
|
||||
trainer.logger.experiment.log({
|
||||
"examples": [wandb.Image(x, caption=f"Pred:{pred}, Label:{y}")
|
||||
for x, pred, y in zip(val_imgs, preds, self.val_labels)],
|
||||
"global_step": trainer.global_step
|
||||
})
|
||||
trainer.logger.experiment.log({"examples": [
|
||||
wandb.Image(x, caption=f"Pred:{pred}, Label:{y}") for x, pred, y in zip(val_imgs, preds, self.val_labels)
|
||||
]})
|
||||
|
||||
|
||||
class UnFreezeModelCallback(Callback):
|
||||
"""Unfreeze model after a few epochs."""
|
||||
def __init__(self, wait_epochs=5):
|
||||
self.wait_epochs = wait_epochs
|
||||
|
||||
def on_epoch_end(self, trainer, pl_module):
|
||||
if trainer.current_epoch == self.wait_epochs:
|
||||
for param in pl_module.model.model.parameters():
|
||||
param.requires_grad = True
|
||||
|
||||
|
||||
class ConfusionMatrixLoggerCallback(Callback):
|
||||
"""Log confusion matrix calculated from each validation epoch."""
|
||||
def __init__(self):
|
||||
self.val_loop_outputs = []
|
||||
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.val_loop_outputs.append(outputs)
|
||||
|
||||
def on_validation_epoch_end(self, trainer, pl_module):
|
||||
if self.ready:
|
||||
for outputs in self.val_loop_outputs:
|
||||
preds, targets = outputs
|
||||
self.val_loop_outputs = []
|
||||
@@ -10,6 +10,7 @@ from pipeline_modules.datasets import *
|
||||
|
||||
|
||||
class ExampleDataModule(pl.LightningDataModule):
|
||||
"""All datamodules should look like this!"""
|
||||
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90):
|
||||
super().__init__()
|
||||
|
||||
|
||||
@@ -32,9 +32,9 @@ class LitModel(pl.LightningModule):
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
f1 = f1_score(preds, y, average="micro")
|
||||
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True)
|
||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True)
|
||||
self.log('train_f1', f1, on_step=False, on_epoch=True, logger=True)
|
||||
self.log('train_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('train_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('train_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
|
||||
return loss
|
||||
|
||||
@@ -49,11 +49,11 @@ class LitModel(pl.LightningModule):
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
f1 = f1_score(preds, y, average="micro")
|
||||
self.log('val_loss', loss, prog_bar=True, logger=True)
|
||||
self.log('val_acc', acc, prog_bar=True, logger=True)
|
||||
self.log('val_f1', f1, prog_bar=True, logger=True)
|
||||
self.log('val_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('val_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('val_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
|
||||
return loss
|
||||
return preds, y
|
||||
|
||||
# logic for a single testing step
|
||||
def test_step(self, batch, batch_idx):
|
||||
@@ -66,9 +66,9 @@ class LitModel(pl.LightningModule):
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
f1 = f1_score(preds, y, average="micro")
|
||||
self.log('test_loss', loss, prog_bar=True, logger=True)
|
||||
self.log('test_acc', acc, prog_bar=True, logger=True)
|
||||
self.log('test_f1', f1, prog_bar=True, logger=True)
|
||||
self.log('test_loss', loss, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('test_acc', acc, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
self.log('test_f1', f1, on_step=False, on_epoch=True, logger=True, prog_bar=True)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
@@ -12,25 +12,23 @@ class SimpleLinearMNIST(nn.Module):
|
||||
super().__init__()
|
||||
|
||||
# mnist images are (1, 28, 28) (channels, width, height)
|
||||
self.layer_1 = nn.Linear(28 * 28, config["lin1_size"])
|
||||
self.layer_2 = nn.Linear(config["lin1_size"], config["lin2_size"])
|
||||
self.layer_3 = nn.Linear(config["lin2_size"], config["lin3_size"])
|
||||
self.layer_4 = nn.Linear(config["lin3_size"], config["output_size"])
|
||||
self.model = nn.Sequential(
|
||||
nn.Linear(28 * 28, config["lin1_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Linear(config["lin1_size"], config["lin2_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Linear(config["lin2_size"], config["lin3_size"]),
|
||||
nn.ReLU(),
|
||||
nn.Linear(config["lin3_size"], config["output_size"]),
|
||||
nn.LogSoftmax(dim=1),
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
batch_size, channels, width, height = x.size()
|
||||
|
||||
# (b, 1, 28, 28) -> (b, 1*28*28)
|
||||
x = x.view(batch_size, -1)
|
||||
x = self.layer_1(x)
|
||||
x = F.relu(x)
|
||||
x = self.layer_2(x)
|
||||
x = F.relu(x)
|
||||
x = self.layer_3(x)
|
||||
x = F.relu(x)
|
||||
x = self.layer_4(x)
|
||||
|
||||
return F.log_softmax(x, dim=1)
|
||||
return self.model(x)
|
||||
|
||||
|
||||
class EfficientNetPretrained(nn.Module):
|
||||
@@ -42,7 +40,7 @@ class EfficientNetPretrained(nn.Module):
|
||||
# self.model = EfficientNet.from_pretrained('efficientnet-b7')
|
||||
|
||||
for param in self.model.parameters():
|
||||
param.requires_grad = True
|
||||
param.requires_grad = False
|
||||
|
||||
self.model._fc = nn.Sequential(
|
||||
nn.Linear(self.model._fc.in_features, config["lin1_size"]),
|
||||
@@ -100,7 +98,7 @@ class ResnetPretrained(nn.Module):
|
||||
# nn.ReLU(),
|
||||
# nn.Dropout(p=0.15),
|
||||
# nn.Linear(config["lin1_size"], config["output_size"]),
|
||||
# nn.LogSoftmax()
|
||||
# nn.LogSoftmax(dim=1)
|
||||
# )
|
||||
#
|
||||
# def forward(self, x):
|
||||
|
||||
+6
-3
@@ -6,6 +6,7 @@ import yaml
|
||||
# custom
|
||||
from pipeline_modules.lightning_wrapper import LitModel
|
||||
from project.pipeline_modules.data_modules import *
|
||||
from project.pipeline_modules.callbacks import *
|
||||
|
||||
|
||||
def train(config):
|
||||
@@ -38,8 +39,9 @@ def train(config):
|
||||
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
||||
),
|
||||
# ExampleCallback(),
|
||||
# LearningRateMonitor(),
|
||||
# SaveOnnxToWandbCallback(dataloader=datamodule.train_dataloader(), wandb_save_dir=wandb_logger.save_dir)
|
||||
# ConfusionMatrixLoggerCallback(),
|
||||
# UnFreezeModelCallback(wait_epochs=5),
|
||||
# SaveOnnxToWandbCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
|
||||
]
|
||||
|
||||
# Init trainer
|
||||
@@ -54,6 +56,7 @@ def train(config):
|
||||
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
|
||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
||||
weights_summary=config["printing"]["weights_summary"],
|
||||
num_sanity_val_steps=3,
|
||||
# fast_dev_run=True,
|
||||
# min_epochs=10,
|
||||
# limit_train_batches=0.01
|
||||
@@ -85,7 +88,7 @@ def init_wandb(config, model, dataloader):
|
||||
entity=config["loggers"]["wandb"]["team"],
|
||||
id=config["resume"]["wandb_run_id"] if config["resume"]["resume_from_ckpt"] else None,
|
||||
log_model=config["loggers"]["wandb"]["log_model"],
|
||||
offline=False
|
||||
offline=config["loggers"]["wandb"]["offline"]
|
||||
)
|
||||
wandb_logger.watch(model.model, log=None)
|
||||
wandb_logger.log_hyperparams({
|
||||
|
||||
Reference in new issue
Block a user