config makes more sense now
This commit is contained in:
1 parent
0ae8995eb3
commit
50872fd3c6
13 files changed
+214
-162
No files matched your search
+1
-1
@@ -230,4 +230,4 @@ project/lightning_logs/
|
||||
project/wandb/
|
||||
project/logs/
|
||||
|
||||
project/train_config.yaml
|
||||
project/config.yaml
|
||||
@@ -99,7 +99,7 @@ Installation command generator: https://pytorch.org/get-started/locally/
|
||||
<br>
|
||||
|
||||
|
||||
## [config.yaml](project/train_config.yaml) parameters explanation:
|
||||
## [config.yaml](project/config.yaml) parameters explanation:
|
||||
```yaml
|
||||
num_of_gpus: -1 <- -1 means use all gpus available on your machine, 0 means train on cpu
|
||||
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
num_of_gpus: -1
|
||||
|
||||
|
||||
models:
|
||||
simple_mnist_classifier:
|
||||
hparams:
|
||||
max_epochs: 3
|
||||
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
|
||||
datasets:
|
||||
MNISTDataModule:
|
||||
batch_size: 64
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 4
|
||||
pin_memory: True
|
||||
|
||||
transfer_learning_cifar10_classifier:
|
||||
hparams:
|
||||
max_epochs: 3
|
||||
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
|
||||
datasets:
|
||||
CIFAR10DataModule:
|
||||
batch_size: 64
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 4
|
||||
pin_memory: True
|
||||
|
||||
|
||||
resume_training:
|
||||
lightning_ckpt:
|
||||
resume_from_ckpt: False
|
||||
ckpt_path: "checkpoints/epoch=2.ckpt"
|
||||
wandb:
|
||||
resume_wandb_run: False
|
||||
wandb_run_id: "8uuomodb"
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1 @@
|
||||
from .lightning_module import LitModel
|
||||
@@ -1,21 +0,0 @@
|
||||
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"
|
||||
@@ -0,0 +1 @@
|
||||
from .lightning_module import LitModel
|
||||
@@ -1,19 +0,0 @@
|
||||
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"
|
||||
@@ -0,0 +1,70 @@
|
||||
from sklearn.metrics import accuracy_score
|
||||
import pytorch_lightning as pl
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
# custom models
|
||||
from models.transfer_learning_cifar10_classifier.models import *
|
||||
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
|
||||
def __init__(self, hparams=None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
self.save_hyperparameters(hparams)
|
||||
|
||||
self.model = EfficientNetPretrained(config=self.hparams)
|
||||
|
||||
def forward(self, x):
|
||||
return self.model(x)
|
||||
|
||||
# logic for a single training step
|
||||
def training_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.model(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# training metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
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)
|
||||
|
||||
return loss
|
||||
|
||||
# logic for a single validation step
|
||||
def validation_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.model(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# validation metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
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)
|
||||
|
||||
# we can return here anything and then read it in some callback
|
||||
return preds, y
|
||||
|
||||
# logic for a single testing step
|
||||
def test_step(self, batch, batch_idx):
|
||||
x, y = batch
|
||||
logits = self.model(x)
|
||||
loss = F.nll_loss(logits, y)
|
||||
|
||||
# test metrics
|
||||
preds = torch.argmax(logits, dim=1)
|
||||
preds, y = preds.cpu(), y.cpu()
|
||||
acc = accuracy_score(preds, y)
|
||||
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)
|
||||
|
||||
return loss
|
||||
|
||||
def configure_optimizers(self):
|
||||
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"])
|
||||
+51
-47
@@ -1,49 +1,48 @@
|
||||
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
||||
from pytorch_lightning.profiler import SimpleProfiler
|
||||
import importlib
|
||||
import yaml
|
||||
|
||||
# training modules
|
||||
import training_modules.datamodules
|
||||
from training_modules.datamodules import *
|
||||
from training_modules.callbacks import *
|
||||
from training_modules.loggers import *
|
||||
|
||||
# custom models
|
||||
from models import simple_mnist_classifier
|
||||
from models import transfer_learning_cifar10_classifier
|
||||
|
||||
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)
|
||||
def train(config):
|
||||
|
||||
# Init lightning model
|
||||
module_path = "models." + train_config["model"] + ".lightning_module"
|
||||
lit_model = importlib.import_module(module_path).LitModel(hparams=model_config["hparams"])
|
||||
# CHOOSE MODEL AND DATASET HERE!!
|
||||
MODEL = simple_mnist_classifier
|
||||
DATASET = MNISTDataModule
|
||||
MODEL_PARAMS = config["models"]["simple_mnist_classifier"]["hparams"]
|
||||
DATASET_PARAMS = config["models"]["simple_mnist_classifier"]["datasets"]["MNISTDataModule"]
|
||||
|
||||
# Init data module
|
||||
datamodule_name = train_config["data"]
|
||||
args = train_config["dataset_params"][datamodule_name]
|
||||
args["batch_size"] = model_config["hparams"]["batch_size"]
|
||||
datamodule = getattr(training_modules.datamodules, train_config["data"])(**args)
|
||||
# Init model
|
||||
lit_model = MODEL.LitModel(hparams=MODEL_PARAMS)
|
||||
|
||||
# Init dataset
|
||||
datamodule = DATASET(**DATASET_PARAMS)
|
||||
datamodule.prepare_data()
|
||||
datamodule.setup()
|
||||
|
||||
# Init experiment logger
|
||||
logger = get_wandb_logger(train_config, model_config, lit_model, datamodule)
|
||||
# Init logger
|
||||
logger = get_wandb_logger(config, lit_model, datamodule)
|
||||
|
||||
# Init callbacks
|
||||
callbacks = [
|
||||
EarlyStopping(
|
||||
monitor=train_config["callbacks"]["early_stop"]["monitor"],
|
||||
patience=train_config["callbacks"]["early_stop"]["patience"],
|
||||
mode=train_config["callbacks"]["early_stop"]["mode"],
|
||||
monitor=config["callbacks"]["early_stop"]["monitor"],
|
||||
patience=config["callbacks"]["early_stop"]["patience"],
|
||||
mode=config["callbacks"]["early_stop"]["mode"],
|
||||
),
|
||||
ModelCheckpoint(
|
||||
monitor=train_config["callbacks"]["checkpoint"]["monitor"],
|
||||
save_top_k=train_config["callbacks"]["checkpoint"]["save_top_k"],
|
||||
mode=train_config["callbacks"]["checkpoint"]["mode"],
|
||||
save_last=train_config["callbacks"]["checkpoint"]["save_last"],
|
||||
monitor=config["callbacks"]["checkpoint"]["monitor"],
|
||||
save_top_k=config["callbacks"]["checkpoint"]["save_top_k"],
|
||||
mode=config["callbacks"]["checkpoint"]["mode"],
|
||||
save_last=config["callbacks"]["checkpoint"]["save_last"],
|
||||
),
|
||||
# MetricsHeatmapLoggerCallback(),
|
||||
# UnfreezeModelCallback(wait_epochs=5),
|
||||
@@ -56,25 +55,30 @@ def train():
|
||||
trainer = pl.Trainer(
|
||||
logger=logger,
|
||||
callbacks=callbacks,
|
||||
gpus=train_config["num_of_gpus"],
|
||||
max_epochs=model_config["hparams"]["max_epochs"],
|
||||
resume_from_checkpoint=model_config["resume_training"]["lightning_ckpt"]["ckpt_path"]
|
||||
if model_config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
|
||||
accumulate_grad_batches=model_config["hparams"]["accumulate_grad_batches"],
|
||||
gradient_clip_val=model_config["hparams"]["gradient_clip_val"],
|
||||
progress_bar_refresh_rate=train_config["printing"]["progress_bar_refresh_rate"],
|
||||
profiler=SimpleProfiler() if train_config["printing"]["profiler"] else None,
|
||||
weights_summary=train_config["printing"]["weights_summary"],
|
||||
num_sanity_val_steps=3,
|
||||
default_root_dir="logs/lightning_logs"
|
||||
# fast_dev_run=True,
|
||||
# min_epochs=10,
|
||||
# limit_train_batches=0.1
|
||||
# limit_val_batches=0.01
|
||||
# limit_test_batches=0.01
|
||||
# auto_scale_batch_size="power",
|
||||
# amp_backend='apex',
|
||||
# precision=16,
|
||||
gpus=config["num_of_gpus"],
|
||||
|
||||
resume_from_checkpoint=config["resume_training"]["lightning_ckpt"]["ckpt_path"]
|
||||
if config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
|
||||
|
||||
# model related:
|
||||
max_epochs=MODEL_PARAMS["max_epochs"],
|
||||
accumulate_grad_batches=MODEL_PARAMS["accumulate_grad_batches"],
|
||||
gradient_clip_val=MODEL_PARAMS["gradient_clip_val"],
|
||||
|
||||
# printing related:
|
||||
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
|
||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
||||
weights_summary=config["printing"]["weights_summary"],
|
||||
|
||||
# these are mostly for debugging:
|
||||
# fast_dev_run=False,
|
||||
# num_sanity_val_steps=3,
|
||||
# limit_train_batches=1.0,
|
||||
# limit_val_batches=1.0,
|
||||
# limit_test_batches=1.0,
|
||||
# val_check_interval=1.0,
|
||||
|
||||
default_root_dir="logs/lightning_logs",
|
||||
)
|
||||
|
||||
# Test before training
|
||||
@@ -90,11 +94,11 @@ def train():
|
||||
trainer.test()
|
||||
|
||||
|
||||
def load_config(path):
|
||||
with open(path, "r") as ymlfile:
|
||||
def load_config():
|
||||
with open("config.yaml", "r") as ymlfile:
|
||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||
return config
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
train()
|
||||
train(config=load_config())
|
||||
@@ -1,40 +0,0 @@
|
||||
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
|
||||
@@ -141,7 +141,7 @@ class SaveCodeToWandbCallback(pl.Callback):
|
||||
"training_modules/models.py",
|
||||
"training_modules/transforms.py",
|
||||
"train.py",
|
||||
"train_config.yaml"
|
||||
"config.yaml"
|
||||
]
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
from torch.utils.data import DataLoader, random_split
|
||||
from torchvision.datasets import MNIST, CIFAR10
|
||||
import pytorch_lightning as pl
|
||||
import numpy as np
|
||||
|
||||
# custom
|
||||
from models.transfer_learning_cifar10_classifier.transforms import *
|
||||
@@ -23,10 +22,6 @@ class ExampleDataModule(pl.LightningDataModule):
|
||||
self.data_val = None
|
||||
self.data_test = None
|
||||
|
||||
# optional variables
|
||||
self.input_dims = None
|
||||
self.input_size = None
|
||||
|
||||
def prepare_data(self):
|
||||
"""Download data if needed."""
|
||||
pass
|
||||
@@ -63,9 +58,6 @@ class MNISTDataModule(pl.LightningDataModule):
|
||||
self.data_val = None
|
||||
self.data_test = None
|
||||
|
||||
self.input_dims = None
|
||||
self.input_size = None
|
||||
|
||||
def prepare_data(self):
|
||||
"""Download data if needed."""
|
||||
MNIST(self.data_dir, train=True, download=True)
|
||||
@@ -81,9 +73,6 @@ class MNISTDataModule(pl.LightningDataModule):
|
||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
||||
self.data_test = MNIST(self.data_dir, train=False, transform=transforms.ToTensor())
|
||||
|
||||
self.input_dims = self.data_train[0][0].shape
|
||||
self.input_size = np.prod(self.input_dims)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory)
|
||||
@@ -112,9 +101,6 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
||||
self.data_val = None
|
||||
self.data_test = None
|
||||
|
||||
self.input_dims = None
|
||||
self.input_size = None
|
||||
|
||||
def prepare_data(self):
|
||||
"""Download data if needed."""
|
||||
CIFAR10(self.data_dir, train=True, download=True)
|
||||
@@ -130,9 +116,6 @@ class CIFAR10DataModule(pl.LightningDataModule):
|
||||
self.data_train, self.data_val = random_split(trainset, train_val_split)
|
||||
self.data_test = CIFAR10(self.data_dir, train=False, transform=transforms.ToTensor())
|
||||
|
||||
self.input_dims = self.data_train[0][0].shape
|
||||
self.input_size = np.prod(self.input_dims)
|
||||
|
||||
def train_dataloader(self):
|
||||
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
||||
pin_memory=self.pin_memory)
|
||||
|
||||
@@ -1,35 +1,31 @@
|
||||
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
|
||||
import inspect
|
||||
import os
|
||||
|
||||
|
||||
def get_wandb_logger(train_config, model_config, lit_model, datamodule):
|
||||
def get_wandb_logger(config, lit_model, datamodule):
|
||||
wandb_logger = WandbLogger(
|
||||
project=train_config["loggers"]["wandb"]["project"],
|
||||
job_type=train_config["loggers"]["wandb"]["job_type"],
|
||||
tags=train_config["loggers"]["wandb"]["tags"],
|
||||
entity=train_config["loggers"]["wandb"]["team"],
|
||||
id=model_config["resume_training"]["wandb"]["wandb_run_id"]
|
||||
if model_config["resume_training"]["wandb"]["resume_wandb_run"] else None,
|
||||
log_model=train_config["loggers"]["wandb"]["log_model"],
|
||||
offline=train_config["loggers"]["wandb"]["offline"],
|
||||
project=config["loggers"]["wandb"]["project"],
|
||||
job_type=config["loggers"]["wandb"]["job_type"],
|
||||
tags=config["loggers"]["wandb"]["tags"],
|
||||
entity=config["loggers"]["wandb"]["team"],
|
||||
id=config["resume_training"]["wandb"]["wandb_run_id"]
|
||||
if config["resume_training"]["wandb"]["resume_wandb_run"] else None,
|
||||
log_model=config["loggers"]["wandb"]["log_model"],
|
||||
offline=config["loggers"]["wandb"]["offline"],
|
||||
save_dir="logs/",
|
||||
save_code=False
|
||||
)
|
||||
if not os.path.exists("logs/"):
|
||||
os.mkdir("logs/")
|
||||
wandb_logger.watch(lit_model.model, log=None)
|
||||
wandb_logger.log_hyperparams({
|
||||
"model_name": lit_model.model.__class__.__name__,
|
||||
"parent_folder": os.path.basename(os.path.dirname((inspect.getfile(lit_model.__class__)))),
|
||||
"datamodule_name": datamodule.__class__.__name__,
|
||||
"optimizer": lit_model.configure_optimizers().__class__.__name__,
|
||||
"train_size": len(datamodule.data_train) if datamodule.data_train is not None else 0,
|
||||
"val_size": len(datamodule.data_val) if datamodule.data_train is not None else 0,
|
||||
"test_size": len(datamodule.data_test) if datamodule.data_train is not None else 0,
|
||||
"input_dims": datamodule.input_dims,
|
||||
"input_size": datamodule.input_size,
|
||||
})
|
||||
# download model from a specific wandb run
|
||||
# wandb.restore('model-best.h5', run_path="kino/some_project/a1b2c3d")
|
||||
return wandb_logger
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user