remove example model and add arg for disabling wandb
This commit is contained in:
1 parent
6de644d4f0
commit
54c7c3f53a
12 files changed
+63
-189
No files matched your search
@@ -1,48 +0,0 @@
|
|||||||
from torch.utils.data import DataLoader
|
|
||||||
import pytorch_lightning as pl
|
|
||||||
|
|
||||||
|
|
||||||
class DataModule(pl.LightningDataModule):
|
|
||||||
"""
|
|
||||||
This is example of datamodule.
|
|
||||||
The folder name of datamodule used during training should be specified in run config and all parameters from
|
|
||||||
'dataset' section will be passed in 'hparams' dictionary.
|
|
||||||
|
|
||||||
All data modules should be located in separate folders and this class should always be called 'DataModule'!
|
|
||||||
All datamodules should have a structure like this one!!
|
|
||||||
|
|
||||||
See 'mnist_digits_datamodule' for more proper example.
|
|
||||||
"""
|
|
||||||
def __init__(self, hparams):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
self.data_dir = hparams.get("data_dir") or "data/example_data"
|
|
||||||
self.batch_size = hparams.get("batch_size") or 64
|
|
||||||
self.num_workers = hparams.get("num_workers") or 1
|
|
||||||
self.pin_memory = hparams.get("pin_memory") or False
|
|
||||||
|
|
||||||
self.transforms = None
|
|
||||||
|
|
||||||
self.data_train = None
|
|
||||||
self.data_val = None
|
|
||||||
self.data_test = None
|
|
||||||
|
|
||||||
def prepare_data(self):
|
|
||||||
"""Download data if needed."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def setup(self, stage=None):
|
|
||||||
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
|
|
||||||
pass
|
|
||||||
|
|
||||||
def train_dataloader(self):
|
|
||||||
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory, shuffle=True)
|
|
||||||
|
|
||||||
def val_dataloader(self):
|
|
||||||
return DataLoader(self.data_val, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory)
|
|
||||||
|
|
||||||
def test_dataloader(self):
|
|
||||||
return DataLoader(self.data_test, batch_size=self.batch_size, num_workers=self.num_workers,
|
|
||||||
pin_memory=self.pin_memory)
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
from torch.utils.data import Dataset
|
|
||||||
from PIL import Image
|
|
||||||
import os
|
|
||||||
|
|
||||||
|
|
||||||
class TestDataset(Dataset):
|
|
||||||
"""
|
|
||||||
Example dataset class for loading images from folder.
|
|
||||||
'Dataset' classes can be used by 'DataModule' classes.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, img_dir, transform):
|
|
||||||
self.transform = transform
|
|
||||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
|
||||||
|
|
||||||
def __getitem__(self, idx):
|
|
||||||
image = Image.open(self.images[idx]).convert("RGB")
|
|
||||||
|
|
||||||
if self.transform is not None:
|
|
||||||
image = self.transform(image)
|
|
||||||
|
|
||||||
return image
|
|
||||||
|
|
||||||
def __len__(self):
|
|
||||||
return len(self.images)
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
from torchvision import transforms
|
|
||||||
|
|
||||||
|
|
||||||
img_augmentation_transforms = [
|
|
||||||
transforms.RandomAffine((-15, 15), translate=(0.2, 0.2)),
|
|
||||||
transforms.RandomHorizontalFlip(p=0.65),
|
|
||||||
transforms.RandomRotation((-15, 15)),
|
|
||||||
transforms.ColorJitter(hue=.05, saturation=.05),
|
|
||||||
]
|
|
||||||
|
|
||||||
imagenet_train_transforms = transforms.Compose([
|
|
||||||
transforms.Resize((256, 256)),
|
|
||||||
transforms.RandomCrop(224),
|
|
||||||
transforms.ToTensor(),
|
|
||||||
transforms.RandomApply(img_augmentation_transforms, 0.8),
|
|
||||||
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
|
||||||
])
|
|
||||||
|
|
||||||
imagenet_test_transforms = transforms.Compose([
|
|
||||||
transforms.Resize((224, 224)),
|
|
||||||
transforms.ToTensor(),
|
|
||||||
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
|
||||||
])
|
|
||||||
@@ -5,7 +5,16 @@ import pytorch_lightning as pl
|
|||||||
|
|
||||||
|
|
||||||
class DataModule(pl.LightningDataModule):
|
class DataModule(pl.LightningDataModule):
|
||||||
"""The proper datamodule for mnist digits dataset."""
|
"""
|
||||||
|
This is example of datamodule for MNIST digits dataset.
|
||||||
|
All data modules should be located in separate folders with file named 'datamodule.py' containing class which
|
||||||
|
is always called 'DataModule'!
|
||||||
|
|
||||||
|
The folder name of datamodule used during training should be specified in run config and all parameters from
|
||||||
|
'dataset' section will be passed in 'hparams' dictionary.
|
||||||
|
|
||||||
|
All datamodules should have a structure like this one!
|
||||||
|
"""
|
||||||
def __init__(self, hparams):
|
def __init__(self, hparams):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
from torch.utils.data import Dataset
|
||||||
|
from PIL import Image
|
||||||
|
import os
|
||||||
|
|
||||||
|
|
||||||
|
class TestDataset(Dataset):
|
||||||
|
"""
|
||||||
|
Example dataset class for loading images from folder.
|
||||||
|
'Dataset' classes can be used by 'DataModule' classes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, img_dir, transform):
|
||||||
|
self.transform = transform
|
||||||
|
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||||
|
|
||||||
|
def __getitem__(self, idx):
|
||||||
|
image = Image.open(self.images[idx]).convert("RGB")
|
||||||
|
|
||||||
|
if self.transform is not None:
|
||||||
|
image = self.transform(image)
|
||||||
|
|
||||||
|
return image
|
||||||
|
|
||||||
|
def __len__(self):
|
||||||
|
return len(self.images)
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
import pytorch_lightning as pl
|
|
||||||
import torch.nn.functional as F
|
|
||||||
import torch
|
|
||||||
|
|
||||||
# custom models
|
|
||||||
from models.example_model.models import *
|
|
||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
|
||||||
"""
|
|
||||||
This is example of lightning model.
|
|
||||||
It should always be located in file named 'lightninig_module.py' and always be named 'LitModel'!
|
|
||||||
|
|
||||||
The folder name of 'LitModel' used during training should be specified in run config and all parameters from
|
|
||||||
'model' section will be passed in 'hparams' dictionary.
|
|
||||||
|
|
||||||
It enables you to specify what happens during training, validation and test step.
|
|
||||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
|
||||||
|
|
||||||
See 'simple_mnist_classifier' for more proper example.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, hparams=None):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
if hparams:
|
|
||||||
self.save_hyperparameters(hparams)
|
|
||||||
|
|
||||||
self.model = ExampleModel(hparams=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)
|
|
||||||
|
|
||||||
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)
|
|
||||||
|
|
||||||
return loss
|
|
||||||
|
|
||||||
# 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)
|
|
||||||
|
|
||||||
return loss
|
|
||||||
|
|
||||||
def configure_optimizers(self):
|
|
||||||
return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay)
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
from torch import nn
|
|
||||||
|
|
||||||
|
|
||||||
class ExampleModel(nn.Module):
|
|
||||||
|
|
||||||
def __init__(self, hparams):
|
|
||||||
super().__init__()
|
|
||||||
|
|
||||||
self.model = nn.Sequential(
|
|
||||||
nn.Linear(hparams["input_size"], hparams["lin1_size"]),
|
|
||||||
nn.BatchNorm1d(hparams["lin1_size"]),
|
|
||||||
nn.ReLU(),
|
|
||||||
nn.Dropout(p=0.25),
|
|
||||||
nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
|
|
||||||
nn.LogSoftmax(dim=1)
|
|
||||||
)
|
|
||||||
|
|
||||||
def forward(self, x):
|
|
||||||
batch_size, channels, width, height = x.size()
|
|
||||||
x = x.view(batch_size, -1)
|
|
||||||
return self.model(x)
|
|
||||||
@@ -8,6 +8,17 @@ from models.simple_mnist_classifier.models import *
|
|||||||
|
|
||||||
|
|
||||||
class LitModel(pl.LightningModule):
|
class LitModel(pl.LightningModule):
|
||||||
|
"""
|
||||||
|
This is example of lightning model for MNIST digits classification.
|
||||||
|
All models should be located in separate folders with file named 'lightning_module.py' containing class which
|
||||||
|
is always called 'LitModel'!
|
||||||
|
|
||||||
|
The folder name of model used during training should be specified in run config and all parameters from
|
||||||
|
'model' section will be passed in 'hparams' dictionary.
|
||||||
|
|
||||||
|
This class enables you to specify what happens during training, validation and test step.
|
||||||
|
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||||
|
"""
|
||||||
|
|
||||||
def __init__(self, hparams=None):
|
def __init__(self, hparams=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ num_of_gpus: 0
|
|||||||
|
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
project: "hackathon_template_test"
|
project: "project_template_test"
|
||||||
team: "kino"
|
entity: "kino"
|
||||||
log_model: True
|
log_model: True
|
||||||
offline: False
|
offline: False
|
||||||
|
|
||||||
|
|||||||
@@ -33,8 +33,8 @@ MNIST_CLASSIFIER_V2:
|
|||||||
model_folder: "simple_mnist_classifier"
|
model_folder: "simple_mnist_classifier"
|
||||||
lr: 0.002
|
lr: 0.002
|
||||||
weight_decay: 0.00001
|
weight_decay: 0.00001
|
||||||
input_size: 784 # img size is 1*28*28
|
input_size: 784
|
||||||
output_size: 10 # there are 10 digit classes
|
output_size: 10
|
||||||
lin1_size: 512
|
lin1_size: 512
|
||||||
lin2_size: 256
|
lin2_size: 256
|
||||||
lin3_size: 128
|
lin3_size: 128
|
||||||
|
|||||||
+12
-7
@@ -9,7 +9,7 @@ from utils.init_utils import init_lit_model, init_data_module, init_main_callbac
|
|||||||
from utils.callbacks import *
|
from utils.callbacks import *
|
||||||
|
|
||||||
|
|
||||||
def train(project_config: dict, run_config: dict):
|
def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
lit_model: pl.LightningModule = init_lit_model(hparams=run_config["model"])
|
lit_model: pl.LightningModule = init_lit_model(hparams=run_config["model"])
|
||||||
|
|
||||||
@@ -17,17 +17,21 @@ def train(project_config: dict, run_config: dict):
|
|||||||
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
|
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
|
||||||
|
|
||||||
# Init Weights&Biases logger
|
# Init Weights&Biases logger
|
||||||
logger: pl.loggers.WandbLogger = init_wandb_logger(project_config, run_config, lit_model, datamodule)
|
logger: pl.loggers.WandbLogger = init_wandb_logger(project_config, run_config, lit_model, datamodule) \
|
||||||
|
if use_wandb else None
|
||||||
|
|
||||||
# Init ModelCheckpoint and EarlyStopping callbacks
|
# Init ModelCheckpoint and EarlyStopping callbacks
|
||||||
callbacks: list = init_main_callbacks(project_config)
|
callbacks: list = init_main_callbacks(project_config)
|
||||||
|
|
||||||
# Add custom callbacks from utils/callbacks.py
|
# Add custom callbacks from utils/callbacks.py
|
||||||
callbacks.extend([
|
callbacks.extend([
|
||||||
MetricsHeatmapLoggerCallback(),
|
# MetricsHeatmapLoggerCallback(),
|
||||||
# UnfreezeModelCallback(wait_epochs=5),
|
# UnfreezeModelCallback(wait_epochs=5),
|
||||||
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model, datamodule=datamodule),
|
|
||||||
])
|
])
|
||||||
|
if use_wandb:
|
||||||
|
callbacks.append(
|
||||||
|
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model, datamodule=datamodule),
|
||||||
|
)
|
||||||
|
|
||||||
# Get path to checkpoint you want to resume with if it was set in run config
|
# Get path to checkpoint you want to resume with if it was set in run config
|
||||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
|
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
|
||||||
@@ -89,18 +93,19 @@ def load_config(path):
|
|||||||
return config
|
return config
|
||||||
|
|
||||||
|
|
||||||
def main(run_config_name):
|
def main(run_config_name: str, use_wandb: bool):
|
||||||
# Load configs
|
# Load configs
|
||||||
project_config: dict = load_config("project_config.yaml")
|
project_config: dict = load_config("project_config.yaml")
|
||||||
run_config: dict = load_config("run_configs.yaml")[run_config_name]
|
run_config: dict = load_config("run_configs.yaml")[run_config_name]
|
||||||
|
|
||||||
# Train model
|
# Train model
|
||||||
train(project_config=project_config, run_config=run_config)
|
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
parser = ArgumentParser()
|
||||||
parser.add_argument("-c", "--conf_name", type=str, default="MNIST_CLASSIFIER_V1")
|
parser.add_argument("-c", "--conf_name", type=str, default="MNIST_CLASSIFIER_V1")
|
||||||
|
parser.add_argument("-u", "--use_wandb", type=bool, default=True)
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
main(run_config_name=args.conf_name)
|
main(run_config_name=args.conf_name, use_wandb=args.use_wandb)
|
||||||
@@ -48,7 +48,7 @@ def init_wandb_logger(
|
|||||||
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
||||||
wandb_logger = WandbLogger(
|
wandb_logger = WandbLogger(
|
||||||
project=config["loggers"]["wandb"]["project"],
|
project=config["loggers"]["wandb"]["project"],
|
||||||
entity=config["loggers"]["wandb"]["team"],
|
entity=config["loggers"]["wandb"]["entity"],
|
||||||
log_model=config["loggers"]["wandb"]["log_model"],
|
log_model=config["loggers"]["wandb"]["log_model"],
|
||||||
offline=config["loggers"]["wandb"]["offline"],
|
offline=config["loggers"]["wandb"]["offline"],
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user