redesign project structure
This commit is contained in:
1 parent
104688be1b
commit
0ae8995eb3
19 files changed
+287
-188
No files matched your search
+1
-1
@@ -230,4 +230,4 @@ project/lightning_logs/
|
|||||||
project/wandb/
|
project/wandb/
|
||||||
project/logs/
|
project/logs/
|
||||||
|
|
||||||
project/config.yaml
|
project/train_config.yaml
|
||||||
@@ -99,7 +99,7 @@ Installation command generator: https://pytorch.org/get-started/locally/
|
|||||||
<br>
|
<br>
|
||||||
|
|
||||||
|
|
||||||
## [config.yaml](project/config.yaml) parameters explanation:
|
## [config.yaml](project/train_config.yaml) parameters explanation:
|
||||||
```yaml
|
```yaml
|
||||||
num_of_gpus: -1 <- -1 means use all gpus available on your machine, 0 means train on cpu
|
num_of_gpus: -1 <- -1 means use all gpus available on your machine, 0 means train on cpu
|
||||||
|
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
num_of_gpus: -1
|
|
||||||
|
|
||||||
hparams:
|
|
||||||
# these hyperparameters should always be in this file
|
|
||||||
max_epochs: 3
|
|
||||||
batch_size: 64
|
|
||||||
lr: 0.001
|
|
||||||
weight_decay: 0.000001
|
|
||||||
gradient_clip_val: 0.5
|
|
||||||
accumulate_grad_batches: 1
|
|
||||||
|
|
||||||
# these hyperparameters are custom, you can add here anything
|
|
||||||
train_val_split_ratio: 0.9
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 256
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
|
|
||||||
resume: # this is for resuming training from lightning checkpoint
|
|
||||||
resume_from_ckpt: False
|
|
||||||
wandb_run_id: "8uuomodb"
|
|
||||||
ckpt_path: "checkpoints/epoch=2.ckpt"
|
|
||||||
|
|
||||||
loggers:
|
|
||||||
wandb:
|
|
||||||
project: "hackathon_template_test"
|
|
||||||
team: "kino"
|
|
||||||
group: None
|
|
||||||
job_type: "train"
|
|
||||||
tags: []
|
|
||||||
log_model: True
|
|
||||||
offline: False
|
|
||||||
|
|
||||||
callbacks:
|
|
||||||
checkpoint:
|
|
||||||
monitor: "val_acc"
|
|
||||||
save_top_k: 1
|
|
||||||
save_last: True
|
|
||||||
mode: "max"
|
|
||||||
early_stop:
|
|
||||||
monitor: "val_acc"
|
|
||||||
patience: 100
|
|
||||||
mode: "max"
|
|
||||||
|
|
||||||
printing:
|
|
||||||
progress_bar_refresh_rate: 5
|
|
||||||
weights_summary: "top" # "full"
|
|
||||||
profiler: False
|
|
||||||
@@ -49,12 +49,12 @@ def download_artifact():
|
|||||||
|
|
||||||
def download_model_from_wandb_run():
|
def download_model_from_wandb_run():
|
||||||
"""
|
"""
|
||||||
WARNING: This will overwrite your training_modules/models.py and training_modules/lightning_wrapper.py files!
|
WARNING: This will overwrite your training_modules/models.py and training_modules/lightning_module.py files!
|
||||||
"""
|
"""
|
||||||
RUN_ID = "kino/hackathon_template_test/lx9voyom"
|
RUN_ID = "kino/hackathon_template_test/lx9voyom"
|
||||||
MODEL_PATH = "last.ckpt"
|
MODEL_PATH = "last.ckpt"
|
||||||
CODE_PATHS = [
|
CODE_PATHS = [
|
||||||
"code/training_modules/lightning_wrapper.py",
|
"code/training_modules/lightning_module.py",
|
||||||
"code/training_modules/models.py"
|
"code/training_modules/models.py"
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
hparams:
|
||||||
|
max_epochs: 3
|
||||||
|
batch_size: 64
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.000001
|
||||||
|
gradient_clip_val: 0.5
|
||||||
|
accumulate_grad_batches: 1
|
||||||
|
input_size: 784 # img size is 28*28*1
|
||||||
|
output_size: 10
|
||||||
|
lin1_size: 256
|
||||||
|
lin2_size: 256
|
||||||
|
lin3_size: 128
|
||||||
|
|
||||||
|
|
||||||
|
resume_training:
|
||||||
|
lightning_ckpt:
|
||||||
|
resume_from_ckpt: False
|
||||||
|
ckpt_path: "checkpoints/epoch=2.ckpt"
|
||||||
|
wandb:
|
||||||
|
resume_wandb_run: False
|
||||||
|
wandb_run_id: "8uuomodb"
|
||||||
+5
-6
@@ -1,11 +1,10 @@
|
|||||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
from sklearn.metrics import accuracy_score
|
||||||
from pl_bolts.models.regression import LinearRegression, LogisticRegression
|
|
||||||
from torch.nn.functional import one_hot
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
|
import torch.nn.functional as F
|
||||||
|
import torch
|
||||||
|
|
||||||
# custom models
|
# custom models
|
||||||
from training_modules.models import *
|
from models.simple_mnist_classifier.models import *
|
||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
@@ -16,7 +15,7 @@ class LitModel(pl.LightningModule):
|
|||||||
if hparams:
|
if hparams:
|
||||||
self.save_hyperparameters(hparams)
|
self.save_hyperparameters(hparams)
|
||||||
|
|
||||||
self.model = SimpleLinearMNIST(config=self.hparams)
|
self.model = SimpleMNISTClassifier(config=self.hparams)
|
||||||
|
|
||||||
def forward(self, x):
|
def forward(self, x):
|
||||||
return self.model(x)
|
return self.model(x)
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
from torch import nn
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleMNISTClassifier(nn.Module):
|
||||||
|
|
||||||
|
def __init__(self, config):
|
||||||
|
super().__init__()
|
||||||
|
|
||||||
|
# mnist images are (1, 28, 28) (channels, width, height)
|
||||||
|
self.model = nn.Sequential(
|
||||||
|
nn.Linear(config["input_size"], config["lin1_size"]),
|
||||||
|
nn.BatchNorm1d(config["lin1_size"]),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Dropout(p=0.3),
|
||||||
|
nn.Linear(config["lin1_size"], config["lin2_size"]),
|
||||||
|
nn.BatchNorm1d(config["lin2_size"]),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Dropout(p=0.25),
|
||||||
|
nn.Linear(config["lin2_size"], config["lin3_size"]),
|
||||||
|
nn.BatchNorm1d(config["lin3_size"]),
|
||||||
|
nn.ReLU(),
|
||||||
|
nn.Dropout(p=0.2),
|
||||||
|
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)
|
||||||
|
return self.model(x)
|
||||||
@@ -1,14 +1,12 @@
|
|||||||
from training_modules.lightning_wrapper import LitModel
|
from models.simple_mnist_classifier.lightning_module import LitModel
|
||||||
from training_modules.datamodules import *
|
from models.simple_mnist_classifier import transforms
|
||||||
from training_modules.datasets import *
|
|
||||||
from training_modules import transforms
|
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
def predict():
|
def predict():
|
||||||
"""
|
"""
|
||||||
Loads model from checkpoint.
|
Loads model from checkpoint.
|
||||||
Model used in training_modules/lightning_wrapper.py and declaration of that model in training_modules/models.py
|
Model used in lightning_module.py and declaration of that model in models.py
|
||||||
should be the same as during training.
|
should be the same as during training.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -22,10 +20,10 @@ def predict():
|
|||||||
pretrained_model.freeze()
|
pretrained_model.freeze()
|
||||||
|
|
||||||
# load data
|
# load data
|
||||||
img = Image.open("example_img.png").convert("RGB")
|
img = Image.open("../../example_img.png").convert("L")
|
||||||
|
|
||||||
# preprocess
|
# preprocess
|
||||||
img = transforms.efficient_net_test_preprocess(img)
|
img = transforms.test_preprocess(img)
|
||||||
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||||
|
|
||||||
# inference
|
# inference
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
from torchvision import transforms
|
||||||
|
|
||||||
|
|
||||||
|
img_augmentation_transformations = [
|
||||||
|
transforms.RandomAffine((-4, 4), translate=(0.2, 0.2)),
|
||||||
|
transforms.RandomHorizontalFlip(p=0.65),
|
||||||
|
transforms.RandomRotation((-20, 20)),
|
||||||
|
]
|
||||||
|
|
||||||
|
train_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor(),
|
||||||
|
transforms.RandomApply(img_augmentation_transformations, 0.5)
|
||||||
|
])
|
||||||
|
|
||||||
|
test_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor()
|
||||||
|
])
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
hparams:
|
||||||
|
max_epochs: 3
|
||||||
|
batch_size: 64
|
||||||
|
lr: 0.001
|
||||||
|
weight_decay: 0.000001
|
||||||
|
gradient_clip_val: 0.5
|
||||||
|
accumulate_grad_batches: 1
|
||||||
|
output_size: 10
|
||||||
|
lin1_size: 256
|
||||||
|
lin2_size: 256
|
||||||
|
|
||||||
|
|
||||||
|
resume_training:
|
||||||
|
lightning_ckpt:
|
||||||
|
resume_from_ckpt: False
|
||||||
|
ckpt_path: "checkpoints/epoch=2.ckpt"
|
||||||
|
wandb:
|
||||||
|
resume_wandb_run: False
|
||||||
|
wandb_run_id: "8uuomodb"
|
||||||
-34
@@ -1,41 +1,7 @@
|
|||||||
from pl_bolts.models.self_supervised import CPCV2
|
from pl_bolts.models.self_supervised import CPCV2
|
||||||
from efficientnet_pytorch import EfficientNet
|
from efficientnet_pytorch import EfficientNet
|
||||||
import torch.nn.functional as F
|
|
||||||
from torchvision import models
|
from torchvision import models
|
||||||
from torch import nn
|
from torch import nn
|
||||||
import torch
|
|
||||||
|
|
||||||
|
|
||||||
class SimpleLinearMNIST(nn.Module):
|
|
||||||
|
|
||||||
def __init__(self, config):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
# mnist images are (1, 28, 28) (channels, width, height)
|
|
||||||
self.model = nn.Sequential(
|
|
||||||
nn.Linear(28*28, config["lin1_size"]),
|
|
||||||
# nn.Linear(3*32*32, config["lin1_size"]), # for CIFAR10
|
|
||||||
nn.BatchNorm1d(config["lin1_size"]),
|
|
||||||
nn.ReLU(),
|
|
||||||
nn.Dropout(p=0.3),
|
|
||||||
nn.Linear(config["lin1_size"], config["lin2_size"]),
|
|
||||||
nn.BatchNorm1d(config["lin2_size"]),
|
|
||||||
nn.ReLU(),
|
|
||||||
nn.Dropout(p=0.25),
|
|
||||||
nn.Linear(config["lin2_size"], config["lin3_size"]),
|
|
||||||
nn.BatchNorm1d(config["lin3_size"]),
|
|
||||||
nn.ReLU(),
|
|
||||||
nn.Dropout(p=0.2),
|
|
||||||
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)
|
|
||||||
return self.model(x)
|
|
||||||
|
|
||||||
|
|
||||||
class EfficientNetPretrained(nn.Module):
|
class EfficientNetPretrained(nn.Module):
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
from models.transfer_learning_cifar10_classifier.lightning_module import LitModel
|
||||||
|
from models.transfer_learning_cifar10_classifier import transforms
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
|
def predict():
|
||||||
|
"""
|
||||||
|
Loads model from checkpoint.
|
||||||
|
Model used in lightning_module.py and declaration of that model in models.py
|
||||||
|
should be the same as during training.
|
||||||
|
"""
|
||||||
|
|
||||||
|
CKPT_PATH = "epoch=0.ckpt"
|
||||||
|
|
||||||
|
# load model from checkpoint
|
||||||
|
pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
|
||||||
|
|
||||||
|
# switch to evaluation mode
|
||||||
|
pretrained_model.eval()
|
||||||
|
pretrained_model.freeze()
|
||||||
|
|
||||||
|
# load data
|
||||||
|
img = Image.open("../../example_img.png").convert("RGB")
|
||||||
|
|
||||||
|
# preprocess
|
||||||
|
img = transforms.test_preprocess(img)
|
||||||
|
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
|
||||||
|
|
||||||
|
# inference
|
||||||
|
output = pretrained_model(img)
|
||||||
|
print(output)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
predict()
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
from torchvision import transforms
|
||||||
|
|
||||||
|
|
||||||
|
img_augmentation_transformations = [
|
||||||
|
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
||||||
|
transforms.RandomHorizontalFlip(p=0.65),
|
||||||
|
transforms.RandomRotation((-15, 15)),
|
||||||
|
transforms.ColorJitter(hue=.05, saturation=.05),
|
||||||
|
]
|
||||||
|
|
||||||
|
train_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor(),
|
||||||
|
transforms.RandomApply(img_augmentation_transformations, 0.5)
|
||||||
|
])
|
||||||
|
|
||||||
|
test_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor()
|
||||||
|
])
|
||||||
+42
-33
@@ -1,46 +1,54 @@
|
|||||||
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
||||||
from pytorch_lightning.profiler import SimpleProfiler
|
from pytorch_lightning.profiler import SimpleProfiler
|
||||||
|
import importlib
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
# custom
|
# training modules
|
||||||
from training_modules.lightning_wrapper import LitModel
|
import training_modules.datamodules
|
||||||
from training_modules.loggers import *
|
|
||||||
from training_modules.datamodules import *
|
|
||||||
from training_modules.callbacks import *
|
from training_modules.callbacks import *
|
||||||
|
from training_modules.loggers import *
|
||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train():
|
||||||
|
# Load train config
|
||||||
|
train_config = load_config(path="train_config.yaml")
|
||||||
|
|
||||||
|
# Load model config
|
||||||
|
model_config_path = os.path.join("models", train_config["model"], "config.yaml")
|
||||||
|
model_config = load_config(path=model_config_path)
|
||||||
|
|
||||||
|
# Init lightning model
|
||||||
|
module_path = "models." + train_config["model"] + ".lightning_module"
|
||||||
|
lit_model = importlib.import_module(module_path).LitModel(hparams=model_config["hparams"])
|
||||||
|
|
||||||
# Init data module
|
# Init data module
|
||||||
datamodule = MNISTDataModule(
|
datamodule_name = train_config["data"]
|
||||||
batch_size=config["hparams"]["batch_size"],
|
args = train_config["dataset_params"][datamodule_name]
|
||||||
split_ratio=config["hparams"]["train_val_split_ratio"]
|
args["batch_size"] = model_config["hparams"]["batch_size"]
|
||||||
)
|
datamodule = getattr(training_modules.datamodules, train_config["data"])(**args)
|
||||||
datamodule.prepare_data()
|
datamodule.prepare_data()
|
||||||
datamodule.setup()
|
datamodule.setup()
|
||||||
|
|
||||||
# Init our model
|
|
||||||
model = LitModel(hparams=config["hparams"])
|
|
||||||
|
|
||||||
# Init experiment logger
|
# Init experiment logger
|
||||||
logger = get_wandb_logger(config, model, datamodule)
|
logger = get_wandb_logger(train_config, model_config, lit_model, datamodule)
|
||||||
|
|
||||||
# Init callbacks
|
# Init callbacks
|
||||||
callbacks = [
|
callbacks = [
|
||||||
EarlyStopping(
|
EarlyStopping(
|
||||||
monitor=config["callbacks"]["early_stop"]["monitor"],
|
monitor=train_config["callbacks"]["early_stop"]["monitor"],
|
||||||
patience=config["callbacks"]["early_stop"]["patience"],
|
patience=train_config["callbacks"]["early_stop"]["patience"],
|
||||||
mode=config["callbacks"]["early_stop"]["mode"],
|
mode=train_config["callbacks"]["early_stop"]["mode"],
|
||||||
),
|
),
|
||||||
ModelCheckpoint(
|
ModelCheckpoint(
|
||||||
monitor=config["callbacks"]["checkpoint"]["monitor"],
|
monitor=train_config["callbacks"]["checkpoint"]["monitor"],
|
||||||
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"],
|
save_top_k=train_config["callbacks"]["checkpoint"]["save_top_k"],
|
||||||
mode=config["callbacks"]["checkpoint"]["mode"],
|
mode=train_config["callbacks"]["checkpoint"]["mode"],
|
||||||
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
save_last=train_config["callbacks"]["checkpoint"]["save_last"],
|
||||||
),
|
),
|
||||||
# MetricsHeatmapLoggerCallback(),
|
# MetricsHeatmapLoggerCallback(),
|
||||||
# UnfreezeModelCallback(wait_epochs=5),
|
# UnfreezeModelCallback(wait_epochs=5),
|
||||||
# ImagePredictionLoggerCallback(datamodule=datamodule),
|
# ImagePredictionLoggerCallback(datamodule=datamodule),
|
||||||
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir),
|
# SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir),
|
||||||
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
|
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -48,14 +56,15 @@ def train(config):
|
|||||||
trainer = pl.Trainer(
|
trainer = pl.Trainer(
|
||||||
logger=logger,
|
logger=logger,
|
||||||
callbacks=callbacks,
|
callbacks=callbacks,
|
||||||
gpus=config["num_of_gpus"],
|
gpus=train_config["num_of_gpus"],
|
||||||
max_epochs=config["hparams"]["max_epochs"],
|
max_epochs=model_config["hparams"]["max_epochs"],
|
||||||
resume_from_checkpoint=config["resume"]["ckpt_path"] if config["resume"]["resume_from_ckpt"] else None,
|
resume_from_checkpoint=model_config["resume_training"]["lightning_ckpt"]["ckpt_path"]
|
||||||
accumulate_grad_batches=config["hparams"]["accumulate_grad_batches"],
|
if model_config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
|
||||||
gradient_clip_val=config["hparams"]["gradient_clip_val"],
|
accumulate_grad_batches=model_config["hparams"]["accumulate_grad_batches"],
|
||||||
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
|
gradient_clip_val=model_config["hparams"]["gradient_clip_val"],
|
||||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
progress_bar_refresh_rate=train_config["printing"]["progress_bar_refresh_rate"],
|
||||||
weights_summary=config["printing"]["weights_summary"],
|
profiler=SimpleProfiler() if train_config["printing"]["profiler"] else None,
|
||||||
|
weights_summary=train_config["printing"]["weights_summary"],
|
||||||
num_sanity_val_steps=3,
|
num_sanity_val_steps=3,
|
||||||
default_root_dir="logs/lightning_logs"
|
default_root_dir="logs/lightning_logs"
|
||||||
# fast_dev_run=True,
|
# fast_dev_run=True,
|
||||||
@@ -75,17 +84,17 @@ def train(config):
|
|||||||
# trainer.save_checkpoint("random.ckpt")
|
# trainer.save_checkpoint("random.ckpt")
|
||||||
|
|
||||||
# Train the model ⚡
|
# Train the model ⚡
|
||||||
trainer.fit(model=model, datamodule=datamodule)
|
trainer.fit(model=lit_model, datamodule=datamodule)
|
||||||
|
|
||||||
# Evaluate model on test set
|
# Evaluate model on test set
|
||||||
trainer.test()
|
trainer.test()
|
||||||
|
|
||||||
|
|
||||||
def load_config():
|
def load_config(path):
|
||||||
with open("config.yaml", "r") as ymlfile:
|
with open(path, "r") as ymlfile:
|
||||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
train(config=load_config())
|
train()
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
model: "simple_mnist_classifier"
|
||||||
|
data: "MNISTDataModule"
|
||||||
|
|
||||||
|
num_of_gpus: -1
|
||||||
|
|
||||||
|
dataset_params:
|
||||||
|
MNISTDataModule:
|
||||||
|
train_val_split_ratio: 0.9
|
||||||
|
num_workers: 4
|
||||||
|
pin_memory: True
|
||||||
|
CIFAR10DataModule:
|
||||||
|
train_val_split_ratio: 0.9
|
||||||
|
num_workers: 4
|
||||||
|
pin_memory: True
|
||||||
|
|
||||||
|
loggers:
|
||||||
|
wandb:
|
||||||
|
project: "hackathon_template_test"
|
||||||
|
team: "kino"
|
||||||
|
group: None
|
||||||
|
job_type: "train"
|
||||||
|
tags: []
|
||||||
|
log_model: True
|
||||||
|
offline: False
|
||||||
|
|
||||||
|
callbacks:
|
||||||
|
checkpoint:
|
||||||
|
monitor: "val_acc"
|
||||||
|
save_top_k: 1
|
||||||
|
save_last: True
|
||||||
|
mode: "max"
|
||||||
|
early_stop:
|
||||||
|
monitor: "val_acc"
|
||||||
|
patience: 100
|
||||||
|
mode: "max"
|
||||||
|
|
||||||
|
printing:
|
||||||
|
progress_bar_refresh_rate: 5
|
||||||
|
weights_summary: "top" # "full"
|
||||||
|
profiler: False
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
from shutil import copy, copyfile
|
from shutil import copy
|
||||||
import seaborn
|
|
||||||
import torch
|
import torch
|
||||||
import wandb
|
import wandb
|
||||||
import os
|
import os
|
||||||
@@ -88,6 +87,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
|||||||
"""
|
"""
|
||||||
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
|
Generate f1, precision and recall heatmap calculated from each validation epoch outputs.
|
||||||
Expects validation step to return predictions and targets.
|
Expects validation step to return predictions and targets.
|
||||||
|
Works only for single label classification!
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.preds = []
|
self.preds = []
|
||||||
@@ -128,7 +128,7 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
|
|||||||
|
|
||||||
class SaveCodeToWandbCallback(pl.Callback):
|
class SaveCodeToWandbCallback(pl.Callback):
|
||||||
"""
|
"""
|
||||||
Upload specified files to wandb at the beginning of the run.
|
Upload specified code files to wandb at the beginning of the run.
|
||||||
"""
|
"""
|
||||||
def __init__(self, wandb_save_dir):
|
def __init__(self, wandb_save_dir):
|
||||||
self.wandb_save_dir = wandb_save_dir
|
self.wandb_save_dir = wandb_save_dir
|
||||||
@@ -136,12 +136,12 @@ class SaveCodeToWandbCallback(pl.Callback):
|
|||||||
"training_modules/callbacks.py",
|
"training_modules/callbacks.py",
|
||||||
"training_modules/datamodules.py",
|
"training_modules/datamodules.py",
|
||||||
"training_modules/datasets.py",
|
"training_modules/datasets.py",
|
||||||
"training_modules/lightning_wrapper.py",
|
"training_modules/lightning_module.py",
|
||||||
"training_modules/loggers.py",
|
"training_modules/loggers.py",
|
||||||
"training_modules/models.py",
|
"training_modules/models.py",
|
||||||
"training_modules/transforms.py",
|
"training_modules/transforms.py",
|
||||||
"train.py",
|
"train.py",
|
||||||
"config.yaml"
|
"train_config.yaml"
|
||||||
]
|
]
|
||||||
|
|
||||||
def on_sanity_check_end(self, trainer, pl_module):
|
def on_sanity_check_end(self, trainer, pl_module):
|
||||||
|
|||||||
@@ -1,22 +1,23 @@
|
|||||||
from pl_bolts.models.self_supervised.cpc.transforms import CPCTrainTransformsImageNet128
|
|
||||||
from torch.utils.data import DataLoader, random_split
|
from torch.utils.data import DataLoader, random_split
|
||||||
from torchvision.datasets import MNIST, CIFAR10
|
from torchvision.datasets import MNIST, CIFAR10
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
|
||||||
# custom
|
# custom
|
||||||
from training_modules.transforms import *
|
from models.transfer_learning_cifar10_classifier.transforms import *
|
||||||
from training_modules.datasets import *
|
|
||||||
|
|
||||||
|
|
||||||
class ExampleDataModule(pl.LightningDataModule):
|
class ExampleDataModule(pl.LightningDataModule):
|
||||||
"""All datamodules should look like this!"""
|
"""All datamodules should look like this!"""
|
||||||
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90):
|
def __init__(self, data_dir="data/example_data", batch_size=64, split_ratio=0.90, num_workers=1,
|
||||||
|
pin_memory=False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir
|
self.data_dir = data_dir
|
||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
self.split_ratio = split_ratio
|
self.split_ratio = split_ratio
|
||||||
|
self.num_workers = num_workers
|
||||||
|
self.pin_memory = pin_memory
|
||||||
|
|
||||||
self.data_train = None
|
self.data_train = None
|
||||||
self.data_val = None
|
self.data_val = None
|
||||||
@@ -35,22 +36,28 @@ class ExampleDataModule(pl.LightningDataModule):
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
def train_dataloader(self):
|
def train_dataloader(self):
|
||||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def val_dataloader(self):
|
def val_dataloader(self):
|
||||||
return DataLoader(self.data_val, batch_size=self.batch_size)
|
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def test_dataloader(self):
|
def test_dataloader(self):
|
||||||
return DataLoader(self.data_test, batch_size=self.batch_size)
|
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
|
|
||||||
class MNISTDataModule(pl.LightningDataModule):
|
class MNISTDataModule(pl.LightningDataModule):
|
||||||
def __init__(self, data_dir='data/mnist', batch_size=64, split_ratio=0.90):
|
def __init__(self, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||||
|
pin_memory=False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir
|
self.data_dir = data_dir
|
||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
self.split_ratio = split_ratio
|
self.train_val_split_ratio = train_val_split_ratio
|
||||||
|
self.num_workers = num_workers
|
||||||
|
self.pin_memory = pin_memory
|
||||||
|
|
||||||
self.data_train = None
|
self.data_train = None
|
||||||
self.data_val = None
|
self.data_val = None
|
||||||
@@ -68,7 +75,7 @@ class MNISTDataModule(pl.LightningDataModule):
|
|||||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
||||||
trainset = MNIST(self.data_dir, train=True, transform=transforms.ToTensor())
|
trainset = MNIST(self.data_dir, train=True, transform=transforms.ToTensor())
|
||||||
|
|
||||||
train_dataset_length = int(len(trainset) * self.split_ratio)
|
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
|
||||||
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
|
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
|
||||||
|
|
||||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
||||||
@@ -78,22 +85,28 @@ class MNISTDataModule(pl.LightningDataModule):
|
|||||||
self.input_size = np.prod(self.input_dims)
|
self.input_size = np.prod(self.input_dims)
|
||||||
|
|
||||||
def train_dataloader(self):
|
def train_dataloader(self):
|
||||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def val_dataloader(self):
|
def val_dataloader(self):
|
||||||
return DataLoader(self.data_val, batch_size=self.batch_size)
|
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def test_dataloader(self):
|
def test_dataloader(self):
|
||||||
return DataLoader(self.data_test, batch_size=self.batch_size)
|
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
|
|
||||||
class CIFAR10DataModule(pl.LightningDataModule):
|
class CIFAR10DataModule(pl.LightningDataModule):
|
||||||
def __init__(self, data_dir="data/cifar10", batch_size=64, split_ratio=0.90):
|
def __init__(self, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||||
|
pin_memory=False):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir
|
self.data_dir = data_dir
|
||||||
self.batch_size = batch_size
|
self.batch_size = batch_size
|
||||||
self.split_ratio = split_ratio
|
self.train_val_split_ratio = train_val_split_ratio
|
||||||
|
self.num_workers = num_workers
|
||||||
|
self.pin_memory = pin_memory
|
||||||
|
|
||||||
self.data_train = None
|
self.data_train = None
|
||||||
self.data_val = None
|
self.data_val = None
|
||||||
@@ -111,7 +124,7 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
|||||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
||||||
trainset = CIFAR10(self.data_dir, train=True, transform=transforms.ToTensor())
|
trainset = CIFAR10(self.data_dir, train=True, transform=transforms.ToTensor())
|
||||||
|
|
||||||
train_dataset_length = int(len(trainset) * self.split_ratio)
|
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
|
||||||
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
|
train_val_split = [train_dataset_length, len(trainset) - train_dataset_length]
|
||||||
|
|
||||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
||||||
@@ -121,10 +134,13 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
|||||||
self.input_size = np.prod(self.input_dims)
|
self.input_size = np.prod(self.input_dims)
|
||||||
|
|
||||||
def train_dataloader(self):
|
def train_dataloader(self):
|
||||||
return DataLoader(self.data_train, batch_size=self.batch_size)
|
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def val_dataloader(self):
|
def val_dataloader(self):
|
||||||
return DataLoader(self.data_val, batch_size=self.batch_size)
|
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
|
|
||||||
def test_dataloader(self):
|
def test_dataloader(self):
|
||||||
return DataLoader(self.data_test, batch_size=self.batch_size)
|
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||||
|
pin_memory=self.pin_memory)
|
||||||
@@ -2,15 +2,16 @@ from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogge
|
|||||||
import os
|
import os
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(config, lit_model, datamodule):
|
def get_wandb_logger(train_config, model_config, lit_model, datamodule):
|
||||||
wandb_logger = WandbLogger(
|
wandb_logger = WandbLogger(
|
||||||
project=config["loggers"]["wandb"]["project"],
|
project=train_config["loggers"]["wandb"]["project"],
|
||||||
job_type=config["loggers"]["wandb"]["job_type"],
|
job_type=train_config["loggers"]["wandb"]["job_type"],
|
||||||
tags=config["loggers"]["wandb"]["tags"],
|
tags=train_config["loggers"]["wandb"]["tags"],
|
||||||
entity=config["loggers"]["wandb"]["team"],
|
entity=train_config["loggers"]["wandb"]["team"],
|
||||||
id=config["resume"]["wandb_run_id"] if config["resume"]["resume_from_ckpt"] else None,
|
id=model_config["resume_training"]["wandb"]["wandb_run_id"]
|
||||||
log_model=config["loggers"]["wandb"]["log_model"],
|
if model_config["resume_training"]["wandb"]["resume_wandb_run"] else None,
|
||||||
offline=config["loggers"]["wandb"]["offline"],
|
log_model=train_config["loggers"]["wandb"]["log_model"],
|
||||||
|
offline=train_config["loggers"]["wandb"]["offline"],
|
||||||
save_dir="logs/",
|
save_dir="logs/",
|
||||||
save_code=False
|
save_code=False
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,23 +0,0 @@
|
|||||||
from torchvision import transforms
|
|
||||||
|
|
||||||
|
|
||||||
img_augmentation_transformations = [
|
|
||||||
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
|
||||||
transforms.RandomHorizontalFlip(p=0.65),
|
|
||||||
transforms.RandomRotation((-15, 15)),
|
|
||||||
transforms.ColorJitter(hue=.05, saturation=.05),
|
|
||||||
]
|
|
||||||
|
|
||||||
efficient_net_train_preprocess = transforms.Compose([
|
|
||||||
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
|
|
||||||
transforms.RandomCrop(224),
|
|
||||||
transforms.ToTensor(),
|
|
||||||
transforms.RandomApply(img_augmentation_transformations, 0.8),
|
|
||||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
|
||||||
])
|
|
||||||
|
|
||||||
efficient_net_test_preprocess = transforms.Compose([
|
|
||||||
transforms.Resize((224, 224)),
|
|
||||||
transforms.ToTensor(),
|
|
||||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
|
||||||
])
|
|
||||||
Reference in new issue
Block a user