this is slowly becoming actually useful
This commit is contained in:
1 parent
d518ddb63d
commit
8628600ea3
15 files changed
+190
-176
No files matched your search
+40
-39
@@ -1,10 +1,12 @@
|
|||||||
num_of_gpus: -1
|
num_of_gpus: -1
|
||||||
|
|
||||||
|
|
||||||
model_configs:
|
model_configs:
|
||||||
simple_mnist_classifier_v1:
|
|
||||||
|
simple_mnist_classifier_v1: # everything inside will be saved to to wandb and in model checkpoint
|
||||||
|
model_folder_name: "simple_mnist_classifier"
|
||||||
max_epochs: 3
|
max_epochs: 3
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
|
batch_size: 64
|
||||||
weight_decay: 0.000001
|
weight_decay: 0.000001
|
||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
accumulate_grad_batches: 1
|
accumulate_grad_batches: 1
|
||||||
@@ -13,49 +15,51 @@ model_configs:
|
|||||||
lin1_size: 256
|
lin1_size: 256
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
|
dataset:
|
||||||
|
class_name: "MNISTDataModule"
|
||||||
|
train_transforms: "minst_train_preprocess"
|
||||||
|
test_transforms: "minst_test_preprocess"
|
||||||
|
train_val_split_ratio: 0.8
|
||||||
|
num_workers: 1
|
||||||
|
pin_memory: False
|
||||||
|
|
||||||
simple_mnist_classifier_v2:
|
transfer_learning_cifar10_classifier_v1:
|
||||||
max_epochs: 10
|
model_folder_name: "transfer_learning_img_classifier"
|
||||||
lr: 0.0005
|
max_epochs: 3
|
||||||
weight_decay: 0.0001
|
|
||||||
gradient_clip_val: 0.5
|
|
||||||
accumulate_grad_batches: 1
|
|
||||||
input_size: 784
|
|
||||||
output_size: 10
|
|
||||||
lin1_size: 256
|
|
||||||
lin2_size: 256
|
|
||||||
lin3_size: 128
|
|
||||||
|
|
||||||
transfer_learning_img_classifier_v1:
|
|
||||||
max_epochs: 5
|
|
||||||
lr: 0.001
|
lr: 0.001
|
||||||
|
batch_size: 128
|
||||||
weight_decay: 0.000001
|
weight_decay: 0.000001
|
||||||
gradient_clip_val: 0.5
|
gradient_clip_val: 0.5
|
||||||
accumulate_grad_batches: 1
|
accumulate_grad_batches: 1
|
||||||
output_size: 10
|
output_size: 10
|
||||||
lin1_size: 512
|
lin1_size: 512
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
|
dataset:
|
||||||
|
class_name: "CIFAR10DataModule"
|
||||||
|
train_transforms: "cifar10_train_preprocess"
|
||||||
|
test_transforms: "cifar10_test_preprocess"
|
||||||
|
train_val_split_ratio: 0.9
|
||||||
|
num_workers: 1
|
||||||
|
pin_memory: False
|
||||||
|
|
||||||
|
transfer_learning_cifar10_classifier_v2:
|
||||||
dataset_configs:
|
model_folder_name: "transfer_learning_img_classifier"
|
||||||
mnist_digits_v1:
|
max_epochs: 3
|
||||||
batch_size: 64
|
lr: 0.001
|
||||||
train_val_split_ratio: 0.8
|
batch_size: 128
|
||||||
num_workers: 1
|
weight_decay: 0.000001
|
||||||
pin_memory: False
|
gradient_clip_val: 0.5
|
||||||
|
accumulate_grad_batches: 1
|
||||||
mnist_digits_v2:
|
output_size: 10
|
||||||
batch_size: 256
|
lin1_size: 512
|
||||||
train_val_split_ratio: 0.9
|
lin2_size: 256
|
||||||
num_workers: 4
|
dataset:
|
||||||
pin_memory: True
|
class_name: "CIFAR10DataModule"
|
||||||
|
train_transforms: "cifar10_train_preprocess"
|
||||||
cifar10_v1:
|
test_transforms: "cifar10_test_preprocess"
|
||||||
batch_size: 64
|
train_val_split_ratio: 0.9
|
||||||
train_val_split_ratio: 0.9
|
num_workers: 1
|
||||||
num_workers: 1
|
pin_memory: False
|
||||||
pin_memory: False
|
|
||||||
|
|
||||||
|
|
||||||
resume_training:
|
resume_training:
|
||||||
lightning_ckpt:
|
lightning_ckpt:
|
||||||
@@ -65,7 +69,6 @@ resume_training:
|
|||||||
resume_wandb_run: False
|
resume_wandb_run: False
|
||||||
wandb_run_id: "8uuomodb"
|
wandb_run_id: "8uuomodb"
|
||||||
|
|
||||||
|
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
project: "hackathon_template_test"
|
project: "hackathon_template_test"
|
||||||
@@ -76,7 +79,6 @@ loggers:
|
|||||||
log_model: True
|
log_model: True
|
||||||
offline: False
|
offline: False
|
||||||
|
|
||||||
|
|
||||||
callbacks:
|
callbacks:
|
||||||
checkpoint:
|
checkpoint:
|
||||||
monitor: "val_acc"
|
monitor: "val_acc"
|
||||||
@@ -88,7 +90,6 @@ callbacks:
|
|||||||
patience: 100
|
patience: 100
|
||||||
mode: "max"
|
mode: "max"
|
||||||
|
|
||||||
|
|
||||||
printing:
|
printing:
|
||||||
progress_bar_refresh_rate: 5
|
progress_bar_refresh_rate: 5
|
||||||
weights_summary: "top" # "full"
|
weights_summary: "top" # "full"
|
||||||
|
|||||||
Binary file not shown.
@@ -47,26 +47,27 @@ def download_artifact():
|
|||||||
print("Files are being downloaded now...")
|
print("Files are being downloaded now...")
|
||||||
|
|
||||||
|
|
||||||
def download_model_from_wandb_run():
|
# TODO
|
||||||
"""
|
# def download_model_from_wandb_run():
|
||||||
WARNING: This will overwrite your training_modules/models.py and training_modules/lightning_module.py files!
|
# """
|
||||||
"""
|
# WARNING: This will overwrite your lightning_modules/models.py and lightning_modules/lightning_module.py files!
|
||||||
RUN_ID = "kino/hackathon_template_test/lx9voyom"
|
# """
|
||||||
MODEL_PATH = "last.ckpt"
|
# RUN_ID = "kino/hackathon_template_test/lx9voyom"
|
||||||
CODE_PATHS = [
|
# MODEL_PATH = "last.ckpt"
|
||||||
"code/training_modules/lightning_module.py",
|
# CODE_PATHS = [
|
||||||
"code/training_modules/models.py"
|
# "code/lightning_modules/lightning_module.py",
|
||||||
]
|
# "code/lightning_modules/models.py"
|
||||||
|
# ]
|
||||||
api = wandb.Api()
|
#
|
||||||
run = api.run(path=RUN_ID)
|
# api = wandb.Api()
|
||||||
|
# run = api.run(path=RUN_ID)
|
||||||
# download model
|
#
|
||||||
run.file(MODEL_PATH).download(replace=True)
|
# # download model
|
||||||
|
# run.file(MODEL_PATH).download(replace=True)
|
||||||
# download and replace your code
|
#
|
||||||
for path in CODE_PATHS:
|
# # download and replace your code
|
||||||
run.file(path).download(root="../training_modules/", replace=True)
|
# for path in CODE_PATHS:
|
||||||
|
# run.file(path).download(root="../lightning_modules/", replace=True)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
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
|
from shutil import copy
|
||||||
|
import inspect
|
||||||
import torch
|
import torch
|
||||||
import wandb
|
import wandb
|
||||||
import os
|
import os
|
||||||
@@ -130,17 +131,18 @@ class SaveCodeToWandbCallback(pl.Callback):
|
|||||||
"""
|
"""
|
||||||
Upload specified code 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, model):
|
def __init__(self, wandb_save_dir, lit_model):
|
||||||
self.wandb_save_dir = wandb_save_dir
|
self.wandb_save_dir = wandb_save_dir
|
||||||
self.additional_files_to_be_saved = [
|
self.additional_files_to_be_saved = [
|
||||||
"training_modules/callbacks.py",
|
"lightning_modules/data_modules/datamodules.py",
|
||||||
"training_modules/datamodules.py",
|
"lightning_modules/data_modules/datasets.py",
|
||||||
"training_modules/datasets.py",
|
"lightning_modules/data_modules/transforms.py",
|
||||||
"training_modules/loggers.py",
|
"lightning_modules/callbacks.py",
|
||||||
|
"lightning_modules/init_utils.py",
|
||||||
"train.py",
|
"train.py",
|
||||||
"config.yaml"
|
"config.yaml"
|
||||||
]
|
]
|
||||||
self.model_path = os.path.dirname(model.__file__)
|
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
|
||||||
|
|
||||||
def on_sanity_check_end(self, trainer, pl_module):
|
def on_sanity_check_end(self, trainer, pl_module):
|
||||||
"""Upload files when all validation sanity checks end."""
|
"""Upload files when all validation sanity checks end."""
|
||||||
@@ -156,7 +158,8 @@ class SaveCodeToWandbCallback(pl.Callback):
|
|||||||
|
|
||||||
for filename in os.listdir(self.model_path):
|
for filename in os.listdir(self.model_path):
|
||||||
if filename.endswith('.py'):
|
if filename.endswith('.py'):
|
||||||
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path), filename)
|
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path),
|
||||||
|
filename)
|
||||||
|
|
||||||
path, filename = os.path.split(dst_path)
|
path, filename = os.path.split(dst_path)
|
||||||
if not os.path.exists(path):
|
if not os.path.exists(path):
|
||||||
+4
-5
@@ -2,14 +2,13 @@ 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
|
||||||
|
|
||||||
# custom datasets
|
# custom data_modules
|
||||||
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, transforms, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
|
def __init__(self, transforms, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
|
||||||
pin_memory=False):
|
pin_memory=False, **args):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.transforms = transforms
|
self.transforms = transforms
|
||||||
@@ -46,7 +45,7 @@ class ExampleDataModule(pl.LightningDataModule):
|
|||||||
|
|
||||||
class MNISTDataModule(pl.LightningDataModule):
|
class MNISTDataModule(pl.LightningDataModule):
|
||||||
def __init__(self, transforms, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
def __init__(self, transforms, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||||
pin_memory=False):
|
pin_memory=False, **args):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.transforms = transforms
|
self.transforms = transforms
|
||||||
@@ -90,7 +89,7 @@ class MNISTDataModule(pl.LightningDataModule):
|
|||||||
|
|
||||||
class CIFAR10DataModule(pl.LightningDataModule):
|
class CIFAR10DataModule(pl.LightningDataModule):
|
||||||
def __init__(self, transforms, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
def __init__(self, transforms, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
|
||||||
pin_memory=False):
|
pin_memory=False, **args):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.transforms = transforms
|
self.transforms = transforms
|
||||||
File renamed without changes.
+14
-4
@@ -1,6 +1,14 @@
|
|||||||
from torchvision import transforms
|
from torchvision import transforms
|
||||||
|
|
||||||
|
|
||||||
|
minst_train_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor(),
|
||||||
|
])
|
||||||
|
|
||||||
|
mnist_test_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor()
|
||||||
|
])
|
||||||
|
|
||||||
img_augmentation_transformations = [
|
img_augmentation_transformations = [
|
||||||
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
||||||
transforms.RandomHorizontalFlip(p=0.65),
|
transforms.RandomHorizontalFlip(p=0.65),
|
||||||
@@ -8,7 +16,7 @@ img_augmentation_transformations = [
|
|||||||
transforms.ColorJitter(hue=.05, saturation=.05),
|
transforms.ColorJitter(hue=.05, saturation=.05),
|
||||||
]
|
]
|
||||||
|
|
||||||
train_preprocess = transforms.Compose([
|
imagenet_train_preprocess = transforms.Compose([
|
||||||
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
|
transforms.Resize((256, 256)), # the correct size for eff net b1 is 224x224 but we random crop it later
|
||||||
transforms.RandomCrop(224),
|
transforms.RandomCrop(224),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
@@ -16,15 +24,17 @@ train_preprocess = transforms.Compose([
|
|||||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
||||||
])
|
])
|
||||||
|
|
||||||
test_preprocess = transforms.Compose([
|
imagenet_test_preprocess = transforms.Compose([
|
||||||
transforms.Resize((224, 224)),
|
transforms.Resize((224, 224)),
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
||||||
])
|
])
|
||||||
|
|
||||||
|
|
||||||
cifar10_train_preprocess = transforms.Compose([
|
cifar10_train_preprocess = transforms.Compose([
|
||||||
transforms.ToTensor(),
|
transforms.ToTensor(),
|
||||||
transforms.RandomHorizontalFlip(p=0.5),
|
transforms.RandomHorizontalFlip(p=0.5),
|
||||||
# transforms.RandomRotation((-15, 15)),
|
])
|
||||||
|
|
||||||
|
cifar10_test_preprocess = transforms.Compose([
|
||||||
|
transforms.ToTensor(),
|
||||||
])
|
])
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
|
||||||
|
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
||||||
|
from lightning_modules.data_modules import datamodules, transforms
|
||||||
|
import importlib
|
||||||
|
|
||||||
|
|
||||||
|
def init_lit_model(model_config):
|
||||||
|
module_path = "models." + model_config["model_folder_name"] + ".lightning_module"
|
||||||
|
return importlib.import_module(module_path).LitModel(hparams=model_config)
|
||||||
|
|
||||||
|
|
||||||
|
def init_datamodule(model_config):
|
||||||
|
datamodule_class = getattr(datamodules, model_config["dataset"]["class_name"])
|
||||||
|
train_transforms = getattr(transforms, model_config["dataset"]["train_transforms"])
|
||||||
|
datamodule = datamodule_class(
|
||||||
|
transforms=train_transforms,
|
||||||
|
batch_size=model_config["batch_size"],
|
||||||
|
**model_config["dataset"]
|
||||||
|
)
|
||||||
|
datamodule.prepare_data()
|
||||||
|
datamodule.setup()
|
||||||
|
return datamodule
|
||||||
|
|
||||||
|
|
||||||
|
def init_main_callbacks(config):
|
||||||
|
callbacks = [
|
||||||
|
EarlyStopping(
|
||||||
|
monitor=config["callbacks"]["early_stop"]["monitor"],
|
||||||
|
patience=config["callbacks"]["early_stop"]["patience"],
|
||||||
|
mode=config["callbacks"]["early_stop"]["mode"],
|
||||||
|
),
|
||||||
|
ModelCheckpoint(
|
||||||
|
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"],
|
||||||
|
)
|
||||||
|
]
|
||||||
|
return callbacks
|
||||||
|
|
||||||
|
|
||||||
|
def init_wandb_logger(config, lit_model, datamodule):
|
||||||
|
wandb_logger = WandbLogger(
|
||||||
|
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
|
||||||
|
)
|
||||||
|
wandb_logger.watch(lit_model.model, log=None)
|
||||||
|
wandb_logger.log_hyperparams({
|
||||||
|
"model_name": lit_model.model.__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,
|
||||||
|
})
|
||||||
|
return wandb_logger
|
||||||
|
|
||||||
|
|
||||||
|
def init_tensorboard_loggger():
|
||||||
|
"""TODO"""
|
||||||
|
return None
|
||||||
@@ -1,2 +1 @@
|
|||||||
from .lightning_module import LitModel
|
from .lightning_module import LitModel
|
||||||
from .transforms import *
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from models.simple_mnist_classifier.lightning_module import LitModel
|
from models.simple_mnist_classifier.lightning_module import LitModel
|
||||||
from models.simple_mnist_classifier import transforms
|
from lightning_modules.data_modules import transforms
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ def predict():
|
|||||||
img = Image.open("../../example_img.png").convert("L")
|
img = Image.open("../../example_img.png").convert("L")
|
||||||
|
|
||||||
# preprocess
|
# preprocess
|
||||||
img = transforms.test_preprocess(img)
|
img = transforms.mnist_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
|
||||||
|
|||||||
@@ -1,15 +0,0 @@
|
|||||||
from torchvision import transforms
|
|
||||||
|
|
||||||
|
|
||||||
img_augmentation_transformations = [
|
|
||||||
transforms.RandomRotation((-10, 10)),
|
|
||||||
]
|
|
||||||
|
|
||||||
train_preprocess = transforms.Compose([
|
|
||||||
transforms.ToTensor(),
|
|
||||||
transforms.RandomApply(img_augmentation_transformations, 0.5)
|
|
||||||
])
|
|
||||||
|
|
||||||
test_preprocess = transforms.Compose([
|
|
||||||
transforms.ToTensor()
|
|
||||||
])
|
|
||||||
@@ -1,2 +1 @@
|
|||||||
from .lightning_module import LitModel
|
from .lightning_module import LitModel
|
||||||
from .transforms import *
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from models.transfer_learning_img_classifier.lightning_module import LitModel
|
from models.transfer_learning_img_classifier.lightning_module import LitModel
|
||||||
from models.transfer_learning_img_classifier import transforms
|
from lightning_modules.data_modules import transforms
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
|
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ def predict():
|
|||||||
img = Image.open("../../example_img.png").convert("RGB")
|
img = Image.open("../../example_img.png").convert("RGB")
|
||||||
|
|
||||||
# preprocess
|
# preprocess
|
||||||
img = transforms.test_preprocess(img)
|
img = transforms.imagenet_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
|
||||||
|
|||||||
+29
-45
@@ -1,56 +1,31 @@
|
|||||||
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
|
||||||
from pytorch_lightning.profiler import SimpleProfiler
|
from pytorch_lightning.profiler import SimpleProfiler
|
||||||
import yaml
|
import yaml
|
||||||
|
|
||||||
# training modules
|
# lightning modules
|
||||||
from training_modules.datamodules import *
|
from lightning_modules.init_utils import *
|
||||||
from training_modules.callbacks import *
|
from lightning_modules.callbacks import *
|
||||||
from training_modules.loggers import *
|
|
||||||
|
|
||||||
# custom models
|
|
||||||
from models import simple_mnist_classifier
|
|
||||||
from models import transfer_learning_img_classifier
|
|
||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train(config, model_config):
|
||||||
|
|
||||||
# --------------------------------- CHOOSE MODEL, DATASET AND CONFIGS HERE!! --------------------------------- #
|
# Init lightning model
|
||||||
MODEL = simple_mnist_classifier
|
lit_model = init_lit_model(model_config)
|
||||||
DATASET = MNISTDataModule
|
|
||||||
MODEL_CONFIG = config["model_configs"]["simple_mnist_classifier_v1"]
|
|
||||||
DATASET_CONFIG = config["dataset_configs"]["mnist_digits_v1"]
|
|
||||||
# ------------------------------------------------------------------------------------------------------------ #
|
|
||||||
|
|
||||||
# Init model
|
# Init lightning datamodule
|
||||||
lit_model = MODEL.LitModel(hparams=MODEL_CONFIG)
|
datamodule = init_datamodule(model_config)
|
||||||
|
|
||||||
# Init data
|
|
||||||
datamodule = DATASET(**DATASET_CONFIG, transforms=MODEL.train_preprocess)
|
|
||||||
datamodule.prepare_data()
|
|
||||||
datamodule.setup()
|
|
||||||
|
|
||||||
# Init logger
|
# Init logger
|
||||||
logger = get_wandb_logger(config, lit_model, datamodule)
|
logger = init_wandb_logger(config, lit_model, datamodule)
|
||||||
|
|
||||||
# Init callbacks
|
# Init callbacks
|
||||||
callbacks = [
|
callbacks = init_main_callbacks(config)
|
||||||
EarlyStopping(
|
callbacks.extend([
|
||||||
monitor=config["callbacks"]["early_stop"]["monitor"],
|
|
||||||
patience=config["callbacks"]["early_stop"]["patience"],
|
|
||||||
mode=config["callbacks"]["early_stop"]["mode"],
|
|
||||||
),
|
|
||||||
ModelCheckpoint(
|
|
||||||
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(),
|
# MetricsHeatmapLoggerCallback(),
|
||||||
# UnfreezeModelCallback(wait_epochs=5),
|
# UnfreezeModelCallback(wait_epochs=5),
|
||||||
# ImagePredictionLoggerCallback(datamodule=datamodule),
|
# ImagePredictionLoggerCallback(datamodule=datamodule),
|
||||||
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, model=MODEL),
|
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model),
|
||||||
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
|
# SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
|
||||||
]
|
])
|
||||||
|
|
||||||
# Init trainer
|
# Init trainer
|
||||||
trainer = pl.Trainer(
|
trainer = pl.Trainer(
|
||||||
@@ -62,16 +37,16 @@ def train(config):
|
|||||||
if config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
|
if config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None,
|
||||||
|
|
||||||
# model related:
|
# model related:
|
||||||
max_epochs=MODEL_CONFIG["max_epochs"],
|
max_epochs=model_config["max_epochs"],
|
||||||
accumulate_grad_batches=MODEL_CONFIG["accumulate_grad_batches"],
|
accumulate_grad_batches=model_config["accumulate_grad_batches"],
|
||||||
gradient_clip_val=MODEL_CONFIG["gradient_clip_val"],
|
gradient_clip_val=model_config["gradient_clip_val"],
|
||||||
|
|
||||||
# print related:
|
# print related:
|
||||||
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
|
progress_bar_refresh_rate=config["printing"]["progress_bar_refresh_rate"],
|
||||||
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
profiler=SimpleProfiler() if config["printing"]["profiler"] else None,
|
||||||
weights_summary=config["printing"]["weights_summary"],
|
weights_summary=config["printing"]["weights_summary"],
|
||||||
|
|
||||||
# these are mostly for debugging:
|
# these are mostly for debugging (read TIPS.md for explanation):
|
||||||
fast_dev_run=False,
|
fast_dev_run=False,
|
||||||
num_sanity_val_steps=3,
|
num_sanity_val_steps=3,
|
||||||
limit_train_batches=1.0,
|
limit_train_batches=1.0,
|
||||||
@@ -83,9 +58,9 @@ def train(config):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Test before training
|
# Test before training
|
||||||
# trainer.test(model=model, datamodule=datamodule)
|
# trainer.test(model=lit_model, datamodule=datamodule)
|
||||||
|
|
||||||
# Save randomly initialized model
|
# Save checkpoint
|
||||||
# trainer.save_checkpoint("random.ckpt")
|
# trainer.save_checkpoint("random.ckpt")
|
||||||
|
|
||||||
# Train the model ⚡
|
# Train the model ⚡
|
||||||
@@ -102,4 +77,13 @@ def load_config():
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
train(config=load_config())
|
conf = load_config()
|
||||||
|
|
||||||
|
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↓↓↓ --------------------------------------- #
|
||||||
|
|
||||||
|
model_conf = conf["model_configs"]["simple_mnist_classifier_v1"]
|
||||||
|
# model_conf = conf["model_configs"]["transfer_learning_cifar10_classifier_v1"]
|
||||||
|
|
||||||
|
# --------------------------------------- CHOOSE YOUR MODEL HEREEE ↑↑↑ --------------------------------------- #
|
||||||
|
|
||||||
|
train(config=conf, model_config=model_conf)
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger
|
|
||||||
import inspect
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
def get_wandb_logger(config, lit_model, datamodule):
|
|
||||||
wandb_logger = WandbLogger(
|
|
||||||
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
|
|
||||||
)
|
|
||||||
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__,
|
|
||||||
"batch_size": datamodule.batch_size,
|
|
||||||
"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,
|
|
||||||
})
|
|
||||||
return wandb_logger
|
|
||||||
|
|
||||||
|
|
||||||
def get_tensorboard_loggger():
|
|
||||||
"""TODO"""
|
|
||||||
return None
|
|
||||||
Reference in new issue
Block a user