Merge pull request #33 from kinoai/new-project-structure

BIG clean up and refactoring
This commit is contained in:
hobogalaxy authored and GitHub committed 2020-11-27 20:25:15 +01:00
commit 6cc87c281b
24 files changed
+373 -601

No files matched your search

+41 -51
View File
@@ -14,47 +14,43 @@ The directory structure of new project looks like this:
├── project ├── project
│ ├── data <- Data from third party sources │ ├── data <- Data from third party sources
│ │ │ │
│ ├── data_modules <- Data related modules │ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning
│ │ ├── datamodules.py <- "LightningDataModule" modules
│ │ ├── datasets.py <- "Dataset" modules
│ │ └── transforms.py <- Data transformations
│ │ │ │
│ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning │ ├── notebooks <- Jupyter notebooks
│ │ │ │
│ ├── utils <- Any extra scripts not belonging to training pipeline │ ├── utils <- Different utilities
│ │ ├── callbacks.py <- Useful training callbacks
│ │ ├── execute_sweep.py <- Special file for executing Weights&Biases sweeps
│ │ ├── init_utils.py <- Useful initializers
│ │ └── predict_example.py <- Example of inference with trained model
│ │ │ │
│ ├── notebooks <- Jupyter notebooks │ ├── data_modules <- All your data modules should be located here
│ │ │ │ ├── example_datamodule <- Each datamodule should be located in separate folder!
│ ├── lightning_modules <- PyTorch Lightning related modules │ │ │ ├── datamodule.py <- Contains 'DataModule' class
│ │ ├── callbacks.py <- Training callbacks │ │ │ ├── datasets.py <- Contains pytorch 'Dataset' classes
│ │ └── init_utils.py <- Some useful initializers │ │ │ └── transforms.py <- Contains data transformations
│ │ │ │ ├── ...
│ ├── models <- All your models should be located here
│ │ ├── simple_mnist_classifier <- Example model
│ │ │ ├── lightning_module.py <- Contains train/val/test step methods
│ │ │ └── models.py <- Model declarations used in lightning_module.py
│ │ │
│ │ ├── simple_cifar10_classifier <- Example model
│ │ │ ├── lightning_module.py <- Contains train/val/test step methods
│ │ │ └── models.py <- Model declarations used in lightning_module.py
│ │ │
│ │ └── ... │ │ └── ...
│ │ │ │
│ ├── project_config.yaml <- Project configuration │ ├── models <- All your models should be located here
│ ├── run_configs.yaml <- Run configurations │ │ ├── example_model <- Each model should be located in separate folder!
│ ├── execute_sweep.py <- Special file for executing wandb sweeps (hyperparameter search) │ │ │ ├── lightning_module.py <- Contains 'LitModel' class with train/val/test step methods
│ └── train.py <- Train model │ │ │ └── models.py <- Model architectures used by lightning_module.py
│ │ ├── ...
│ │ └── ...
│ │
│ ├── project_config.yaml <- Project configuration
│ ├── run_configs.yaml <- Configurations of different runs/experiments
│ └── train.py <- Train model with chosen run configuration
│ │
├── .gitignore ├── .gitignore
├── LICENSE ├── LICENSE
├── README.md ├── README.md
├── SETUP.md ├── SETUP.md
├── TIPS.md
└── requirements.txt └── requirements.txt
``` ```
## Project config parameters ## Project config parameters ([project_config.yaml](project/project_config.yaml))
#### [project_config.yaml](project/project_config.yaml)
```yaml ```yaml
num_of_gpus: -1 num_of_gpus: -1
@@ -93,43 +89,37 @@ printing:
profiler: False profiler: False
``` ```
## Run config parameters ## Run config parameters ([run_configs.yaml](project/run_configs.yaml))
#### [run_configs.yaml](project/run_configs.yaml)
You can store many run configurations in this file.<br> You can store many run configurations in this file.<br>
Example run configuration: Example run configuration:
```yaml ```yaml
CIFAR10_CLASSIFIER_V2: MNIST_CLASSIFIER_V1:
trainer: trainer:
max_epochs: 10 min_epochs: 1
max_epochs: 5
gradient_clip_val: 0.5 gradient_clip_val: 0.5
accumulate_grad_batches: 1 accumulate_grad_batches: 1
limit_train_batches: 1.0 limit_train_batches: 1.0
model: model:
name: "simple_cifar10_classifier" model_folder: "simple_mnist_classifier"
lr: 0.002 lr: 0.001
weight_decay: 0.00001 weight_decay: 0.000001
output_size: 10 input_size: 784 # img size is 1*28*28
lin1_size: 512 output_size: 10 # there are 10 digit classes
lin1_size: 256
lin2_size: 256 lin2_size: 256
lin3_size: 128
dataset: dataset:
name: "CIFAR10DataModule" datamodule_folder: "mnist_digits_datamodule"
batch_size: 256 batch_size: 256
train_val_split_ratio: 0.9 train_val_split_ratio: 0.9
num_workers: 1 num_workers: 4
pin_memory: False pin_memory: True
``` ```
The run configuration that you want to train with needs to be chosen in [train.py](project/train.py):
The run configuration that you want to train with needs to be chose in [train.py](project/train.py):
```python ```python
if __name__ == "__main__": if __name__ == "__main__":
RUN_CONFIG = "MNIST_CLASSIFIER_V1" # choose your run config here RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1"
main(run_config_name=RUN_CONFIG_NAME)
project_conf = load_config("project_config.yaml")
run_conf = load_config("run_configs.yaml")[RUN_CONFIG]
train(project_config=project_conf, run_config=run_conf) # train with chosen run config
``` ```
## Tips
For training tips read [TIPS.md](TIPS.md)
-26
View File
@@ -1,26 +0,0 @@
## Tips
- PyTorch Lightning Bolts is official collection of prebuilt models across many research domains:
- https://pytorch-lightning.readthedocs.io/en/latest/bolts.html
- https://github.com/PyTorchLightning/pytorch-lightning-bolts
- Pre-trained pytorch model repository designed for research exploration:
- https://pytorch.org/hub/
- List of all tools in PyTorch ecosystem:
- https://pytorch.org/ecosystem/
- Additional pl.Trainer() parameters which can be useful:
- <b>accumulate_grad_batches=5</b> - perform optimisation after accumulating gradient from 5 batches
- <b>accumulate_grad_batches={5: 3, 10: 20}</b> - no accumulation for epochs 1-4. accumulate 3 for epochs 5-10. accumulate 20 after that
- <b>auto_scale_batch_size='power'</b> - automatically find the largest batch size that fits into memory and is power of 2 (requires calling trainer.tune(model, datamodule))
- <b>check_val_every_n_epoch=10</b> - run validation loop every 10 training epochs
- <b>val_check_interval=0.25</b> - check validation set 4 times during a training epoch
- <b>fast_dev_run=True</b> - runs 1 train, val, test batch and program ends (great for debugging)
- <b>min_epochs=1</b> - force training for at least these many epochs
- <b>overfit_batches=0.01</b> - use only 1% of the train set (and use the train set for val and test)
- <b>overfit_batches=10</b> - use only 10 batches of the train set (and use the train set for val and test)
- <b>limit_train_batches=0.25</b> - run through only 25% of the training set each epoch
- <b>limit_val_batches=0.25</b>
- <b>limit_test_batches=0.25</b>
- <b>precision=16</b> - set tensor precision (default is 32 bits)
- <b>amp_backend='apex'</b> - apex backend for mixed precision training https://github.com/NVIDIA/apex
-133
View File
@@ -1,133 +0,0 @@
from torch.utils.data import DataLoader, random_split
from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import transforms
import pytorch_lightning as pl
class ExampleDataModule(pl.LightningDataModule):
"""All datamodules should look like this!"""
def __init__(self, data_dir="data/example_data", batch_size=64, data_split_ratio=0.90, num_workers=1,
pin_memory=False):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.data_split_ratio = data_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
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)
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)
class MNISTDataModule(pl.LightningDataModule):
def __init__(self, data_dir='data/mnist', batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.transforms = transforms.ToTensor()
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
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_test = MNIST(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
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)
class CIFAR10DataModule(pl.LightningDataModule):
def __init__(self, data_dir="data/cifar10", batch_size=64, train_val_split_ratio=0.90, num_workers=1,
pin_memory=False):
super().__init__()
self.data_dir = data_dir
self.batch_size = batch_size
self.train_val_split_ratio = train_val_split_ratio
self.num_workers = num_workers
self.pin_memory = pin_memory
self.transforms = transforms.ToTensor()
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
CIFAR10(self.data_dir, train=True, download=True)
CIFAR10(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = CIFAR10(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
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_test = CIFAR10(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
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)
@@ -0,0 +1,48 @@
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)
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)
@@ -3,8 +3,11 @@ from PIL import Image
import os import os
class TestDatasetForImgs(Dataset): class TestDataset(Dataset):
"""Example dataset class for loading images from folder.""" """
Example dataset class for loading images from folder.
'Dataset' classes can be used by 'DataModule' classes.
"""
def __init__(self, img_dir, transform): def __init__(self, img_dir, transform):
self.transform = transform self.transform = transform
@@ -1,14 +1,6 @@
from torchvision import transforms from torchvision import transforms
mnist_train_transforms = transforms.Compose([
transforms.ToTensor(),
])
mnist_test_transforms = transforms.Compose([
transforms.ToTensor()
])
img_augmentation_transforms = [ img_augmentation_transforms = [
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),
@@ -17,7 +9,7 @@ img_augmentation_transforms = [
] ]
imagenet_train_transforms = transforms.Compose([ imagenet_train_transforms = 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)),
transforms.RandomCrop(224), transforms.RandomCrop(224),
transforms.ToTensor(), transforms.ToTensor(),
transforms.RandomApply(img_augmentation_transforms, 0.8), transforms.RandomApply(img_augmentation_transforms, 0.8),
@@ -29,12 +21,3 @@ imagenet_test_transforms = transforms.Compose([
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_transforms = transforms.Compose([
transforms.ToTensor(),
transforms.RandomHorizontalFlip(p=0.5),
])
cifar10_test_transforms = transforms.Compose([
transforms.ToTensor(),
])
@@ -0,0 +1,49 @@
from torch.utils.data import DataLoader, random_split
from torchvision.transforms import transforms
from torchvision.datasets import MNIST
import pytorch_lightning as pl
class DataModule(pl.LightningDataModule):
"""The proper datamodule for mnist digits dataset."""
def __init__(self, hparams):
super().__init__()
self.data_dir = hparams.get("data_dir") or "data/mnist"
self.batch_size = hparams.get("batch_size") or 64
self.train_val_split_ratio = hparams.get("train_val_split_ratio") or 0.9
self.num_workers = hparams.get("num_workers") or 1
self.pin_memory = hparams.get("pin_memory") or False
self.transforms = transforms.ToTensor()
self.data_train = None
self.data_val = None
self.data_test = None
def prepare_data(self):
"""Download data if needed."""
MNIST(self.data_dir, train=True, download=True)
MNIST(self.data_dir, train=False, download=True)
def setup(self, stage=None):
"""Load data. Set variables: self.data_train, self.data_val, self.data_test."""
trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
train_dataset_length = int(len(trainset) * self.train_val_split_ratio)
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_test = MNIST(self.data_dir, train=False, transform=self.transforms)
def train_dataloader(self):
return DataLoader(self.data_train, batch_size=self.batch_size, num_workers=self.num_workers,
pin_memory=self.pin_memory)
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)
@@ -0,0 +1,10 @@
from torchvision import transforms
mnist_train_transforms = transforms.Compose([
transforms.ToTensor(),
])
mnist_test_transforms = transforms.Compose([
transforms.ToTensor()
])
-29
View File
@@ -1,29 +0,0 @@
# THIS FILE SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
import wandb
import train
# Choose which run config to optimize
RUN_CONFIG = "MNIST_CLASSIFIER_V1"
# Load project config
project_conf = train.load_config("project_config.yaml")
run_conf = train.load_config("run_configs.yaml")[RUN_CONFIG]
# Initialize wandb
wandb.init()
# Replace project config hyperparameters with the ones loaded from wandb sweep server
sweep_hparams = wandb.Config._as_dict(wandb.config)
for key, value in sweep_hparams.items():
if key == "_wandb":
continue
elif key in run_conf["trainer"].keys():
run_conf["trainer"][key] = value
elif key in run_conf["model"].keys():
run_conf["model"][key] = value
elif key in run_conf["dataset"].keys():
run_conf["dataset"][key] = value
# Execute run
train.train(project_config=project_conf, run_config=run_conf)
@@ -0,0 +1,58 @@
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.
The folder name of LitModel used during trainig 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 validatin_step() or test_step() if you don't want to use them during trainig and model
should still train correctly.
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)
+21
View File
@@ -0,0 +1,21 @@
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)
@@ -15,7 +15,7 @@ class LitModel(pl.LightningModule):
if hparams: if hparams:
self.save_hyperparameters(hparams) self.save_hyperparameters(hparams)
self.model = SimpleMNISTClassifier(config=self.hparams) self.model = SimpleMNISTClassifier(hparams=self.hparams)
def forward(self, x): def forward(self, x):
return self.model(x) return self.model(x)
@@ -3,24 +3,24 @@ from torch import nn
class SimpleMNISTClassifier(nn.Module): class SimpleMNISTClassifier(nn.Module):
def __init__(self, config): def __init__(self, hparams):
super().__init__() super().__init__()
# mnist images are (1, 28, 28) (channels, width, height) # mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential( self.model = nn.Sequential(
nn.Linear(config["input_size"], config["lin1_size"]), nn.Linear(hparams["input_size"], hparams["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]), nn.BatchNorm1d(hparams["lin1_size"]),
nn.ReLU(), nn.ReLU(),
nn.Dropout(p=0.3), nn.Dropout(p=0.3),
nn.Linear(config["lin1_size"], config["lin2_size"]), nn.Linear(hparams["lin1_size"], hparams["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]), nn.BatchNorm1d(hparams["lin2_size"]),
nn.ReLU(), nn.ReLU(),
nn.Dropout(p=0.25), nn.Dropout(p=0.25),
nn.Linear(config["lin2_size"], config["lin3_size"]), nn.Linear(hparams["lin2_size"], hparams["lin3_size"]),
nn.BatchNorm1d(config["lin3_size"]), nn.BatchNorm1d(hparams["lin3_size"]),
nn.ReLU(), nn.ReLU(),
nn.Dropout(p=0.2), nn.Dropout(p=0.2),
nn.Linear(config["lin3_size"], config["output_size"]), nn.Linear(hparams["lin3_size"], hparams["output_size"]),
nn.LogSoftmax(dim=1) nn.LogSoftmax(dim=1)
) )
@@ -1,70 +0,0 @@
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_img_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)
@@ -1,82 +0,0 @@
from efficientnet_pytorch import EfficientNet
from torchvision import models
from torch import nn
class EfficientNetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = EfficientNet.from_pretrained('efficientnet-b0')
for param in self.model.parameters():
param.requires_grad = False
self.model._fc = nn.Sequential(
nn.Linear(self.model._fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnetPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnet18(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
class ResnextPretrained(nn.Module):
def __init__(self, config):
super().__init__()
self.model = models.resnext101_32x8d(pretrained=True)
for param in self.model.parameters():
param.requires_grad = False
self.model.fc = nn.Sequential(
nn.Linear(self.model.fc.in_features, config["lin1_size"]),
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.25),
nn.Linear(config["lin1_size"], config["lin2_size"]),
nn.BatchNorm1d(config["lin2_size"]),
nn.ReLU(),
nn.Dropout(p=0.2),
nn.Linear(config["lin2_size"], config["output_size"]),
nn.LogSoftmax(dim=1)
)
def forward(self, x):
return self.model(x)
+17 -27
View File
@@ -1,55 +1,45 @@
MNIST_CLASSIFIER_V1: MNIST_CLASSIFIER_V1:
trainer: trainer:
min_epochs: 1
max_epochs: 5 max_epochs: 5
gradient_clip_val: 0.5
accumulate_grad_batches: 1
limit_train_batches: 1.0
model: model:
name: "simple_mnist_classifier" model_folder: "simple_mnist_classifier"
lr: 0.001 lr: 0.001
weight_decay: 0.000001 weight_decay: 0.000001
input_size: 784 # img size is 28*28*1 input_size: 784 # img size is 1*28*28
output_size: 10 output_size: 10 # there are 10 digit classes
lin1_size: 256 lin1_size: 256
lin2_size: 256 lin2_size: 256
lin3_size: 128 lin3_size: 128
dataset: dataset:
name: "MNISTDataModule" datamodule_folder: "mnist_digits_datamodule"
batch_size: 64
train_val_split_ratio: 0.9
CIFAR10_CLASSIFIER_V1:
trainer:
max_epochs: 5
gradient_clip_val: 0.5
accumulate_grad_batches: 1
model:
name: "transfer_learning_img_classifier"
lr: 0.001
weight_decay: 0.000001
output_size: 10
lin1_size: 256
lin2_size: 128
dataset:
name: "CIFAR10DataModule"
batch_size: 64 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
CIFAR10_CLASSIFIER_V2: MNIST_CLASSIFIER_V2:
trainer: trainer:
min_epochs: 1
max_epochs: 10 max_epochs: 10
gradient_clip_val: 0.5 gradient_clip_val: 0.5
accumulate_grad_batches: 2 accumulate_grad_batches: 2
limit_train_batches: 1.0 limit_train_batches: 1.0
model: model:
name: "transfer_learning_img_classifier" model_folder: "simple_mnist_classifier"
lr: 0.002 lr: 0.002
weight_decay: 0.00001 weight_decay: 0.00001
output_size: 10 input_size: 784 # img size is 1*28*28
output_size: 10 # there are 10 digit classes
lin1_size: 512 lin1_size: 512
lin2_size: 256 lin2_size: 256
lin3_size: 128
dataset: dataset:
name: "CIFAR10DataModule" datamodule_folder: "mnist_digits_datamodule"
batch_size: 256 batch_size: 256
train_val_split_ratio: 0.9 train_val_split_ratio: 0.9
num_workers: 4 num_workers: 1
pin_memory: True pin_memory: False
+19 -21
View File
@@ -1,30 +1,30 @@
from pytorch_lightning.profiler import SimpleProfiler from pytorch_lightning.profiler import SimpleProfiler
import yaml import yaml
# lightning modules # utils
from lightning_modules.init_utils import * from utils.init_utils import init_lit_model, init_data_module, init_main_callbacks, init_wandb_logger
from lightning_modules.callbacks import * from utils.callbacks import *
def train(project_config, run_config): def train(project_config, run_config):
# Init PyTorch Lightning model ⚡ # Init PyTorch Lightning model ⚡
lit_model = init_lit_model(model_config=run_config["model"]) lit_model = init_lit_model(hparams=run_config["model"])
# Init PyTorch Lightning datamodule ⚡ # Init PyTorch Lightning datamodule ⚡
datamodule = init_datamodule(dataset_config=run_config["dataset"]) datamodule = init_data_module(hparams=run_config["dataset"])
# Init Weights&Biases logger # Init Weights&Biases logger
logger = init_wandb_logger(project_config, run_config, lit_model, datamodule) logger = init_wandb_logger(project_config, run_config, lit_model, datamodule)
# Init checkpoint and early stoping callbacks # Init ModelCheckpoint and EarlyStopping callbacks
callbacks = init_main_callbacks(project_config) callbacks = init_main_callbacks(project_config)
# Add your custom callbacks # 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), SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model, datamodule=datamodule),
]) ])
# Init PyTorch Lightning trainer ⚡ # Init PyTorch Lightning trainer ⚡
@@ -81,17 +81,15 @@ def load_config(path):
return config return config
def main(run_config_name):
# Load configs
project_config = load_config("project_config.yaml")
run_config = load_config("run_configs.yaml")[run_config_name]
# Train model
train(project_config=project_config, run_config=run_config)
if __name__ == "__main__": if __name__ == "__main__":
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V2"
# --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- # main(run_config_name=RUN_CONFIG_NAME)
# --------------------------------------------------- ↓↓↓ ---------------------------------------------------- #
RUN_CONFIG = "MNIST_CLASSIFIER_V1"
# RUN_CONFIG = "CIFAR10_CLASSIFIER_V1"
# RUN_CONFIG = "CIFAR10_CLASSIFIER_V2"
# --------------------------------------------------- ↑↑↑ ---------------------------------------------------- #
# --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- #
project_conf = load_config("project_config.yaml")
run_conf = load_config("run_configs.yaml")[RUN_CONFIG]
train(project_config=project_conf, run_config=run_conf)
@@ -131,19 +131,17 @@ 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, lit_model): def __init__(self, wandb_save_dir, lit_model, datamodule):
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 = [
"data_modules/datamodules.py", "utils/callbacks.py",
"data_modules/datasets.py", "utils/init_utils.py",
"data_modules/transforms.py",
"lightning_modules/callbacks.py",
"lightning_modules/init_utils.py",
"train.py", "train.py",
"project_config.yaml", "project_config.yaml",
"run_configs.yaml", "run_configs.yaml",
] ]
self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__)) self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__))
self.datamodule_path = os.path.dirname(inspect.getfile(datamodule.__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."""
@@ -169,3 +167,16 @@ class SaveCodeToWandbCallback(pl.Callback):
file_path = os.path.join(self.model_path, filename) file_path = os.path.join(self.model_path, filename)
copy(file_path, dst_path) copy(file_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
for filename in os.listdir(self.datamodule_path):
if filename.endswith('.py'):
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", os.path.basename(
self.datamodule_path), filename)
path, filename = os.path.split(dst_path)
if not os.path.exists(path):
os.makedirs(path)
file_path = os.path.join(self.datamodule_path, filename)
copy(file_path, dst_path)
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
+30
View File
@@ -0,0 +1,30 @@
# THIS FILE IS FOR HYPERPARAMETER SEARCH WITH Weights&Biases
# IT SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT!
import wandb
import train
# Choose which run config to optimize
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1"
# Load configs
project_config = train.load_config("../project_config.yaml")
run_config = train.load_config("../run_configs.yaml")[RUN_CONFIG_NAME]
# Initialize wandb
wandb.init()
# Replace run config hyperparameters with the ones loaded from wandb sweep server
sweep_hparams = wandb.Config._as_dict(wandb.config)
for key, value in sweep_hparams.items():
if key == "_wandb":
continue
elif key in run_config["trainer"].keys():
run_config["trainer"][key] = value
elif key in run_config["model"].keys():
run_config["model"][key] = value
elif key in run_config["dataset"].keys():
run_config["dataset"][key] = value
# Execute run
train.train(project_config=project_config, run_config=run_config)
@@ -1,24 +1,20 @@
from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
from data_modules import datamodules
import importlib import importlib
import os import os
def init_lit_model(model_config): def init_lit_model(hparams):
"""Load LitModel from folder specified in run config.""" """Load LitModel from folder specified in run config."""
module_path = "models." + model_config["name"] + ".lightning_module" module_path = "models." + hparams["model_folder"] + ".lightning_module"
model_config["model_folder_name"] = model_config.pop("name") lit_model = importlib.import_module(module_path).LitModel(hparams=hparams)
return importlib.import_module(module_path).LitModel(hparams=model_config) return lit_model
def init_datamodule(dataset_config): def init_data_module(hparams):
"""Load datamodule from class specified in run config.""" """Load DataModule from folder specified in run config."""
datamodule_class = getattr(datamodules, dataset_config["name"]) module_path = "data_modules." + hparams["datamodule_folder"] + ".datamodule"
dataset_config["datamodule_name"] = dataset_config.pop("name") datamodule = importlib.import_module(module_path).DataModule(hparams=hparams)
dataset_config = dataset_config.copy()
dataset_config.pop("datamodule_name")
datamodule = datamodule_class(**dataset_config)
datamodule.prepare_data() datamodule.prepare_data()
datamodule.setup() datamodule.setup()
return datamodule return datamodule
@@ -60,7 +56,8 @@ def init_wandb_logger(config, run_config, lit_model, datamodule):
os.mkdir("logs/") os.mkdir("logs/")
if hasattr(lit_model, 'model'): if hasattr(lit_model, 'model'):
wandb_logger.watch(lit_model.model, log=None) wandb_logger.watch(lit_model.model, log=None)
wandb_logger.watch(lit_model, log=None) else:
wandb_logger.watch(lit_model, log=None)
wandb_logger.log_hyperparams({ wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__, "model_name": lit_model.model.__class__.__name__,
"optimizer": lit_model.configure_optimizers().__class__.__name__, "optimizer": lit_model.configure_optimizers().__class__.__name__,
-35
View File
@@ -1,35 +0,0 @@
from models.transfer_learning_img_classifier.lightning_module import LitModel
from data_modules 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
trained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# switch to evaluation mode
trained_model.eval()
trained_model.freeze()
# load data
img = Image.open("../../example_img.png").convert("RGB")
# preprocess
img = transforms.imagenet_test_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = trained_model(img)
print(output)
if __name__ == "__main__":
predict()
+37
View File
@@ -0,0 +1,37 @@
from models.simple_mnist_classifier.lightning_module import LitModel
from data_modules.mnist_digits_datamodule import transforms
from PIL import Image
def predict():
"""
This method is example of inference with a trained model.
It Loads trained image classification model from checkpoint.
Then it loads example image and predicts its label.
Model used in lightning_module.py should be the same as during training!!!
"""
CKPT_PATH = "epoch=0.ckpt"
# load model from checkpoint
trained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# switch to evaluation mode
trained_model.eval()
trained_model.freeze()
# load data
img = Image.open("data/example_img.png").convert("L") # for monochromatic conversion
# img = Image.open("data/example_img.png").convert("RGB") # for RGB conversion
# preprocess
img = transforms.mnist_test_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = trained_model(img)
print(output)
if __name__ == "__main__":
predict()
-76
View File
@@ -1,76 +0,0 @@
import wandb
import os
def upload_artifact():
FOLDER_TO_UPLOAD_PATH = "../data/skyhacks"
ARTIFACT_NAME = "skyhacks-dataset"
TYPE = "dataset" # type can be anything but we recommend sticking to "dataset" / "model" / "result"
WANDB_PROJECT = "hackathon_template_test"
WANDB_TEAM = "kino"
# Set project which will own the artifact
os.mkdir("../logs") if not os.path.exists("../logs") else None
run = wandb.init(
project=WANDB_PROJECT,
entity=WANDB_TEAM,
dir="../logs",
name="artifact_upload",
job_type="artifact"
)
# Recursively add all files from a directory
artifact = wandb.Artifact(
name=ARTIFACT_NAME,
type=TYPE
)
artifact.add_dir(FOLDER_TO_UPLOAD_PATH)
# artifact.add_file(MODEL_PATH)
# Upload artifact
run.log_artifact(artifact, aliases=["latest"])
print("Files are being uploaded now...")
def download_artifact():
SAVE_DIR = "../data/skyhacks"
ARTIFACT = "kino/hackathon_template_test/skyhacks-dataset:v0"
# Choose what artifact you want to download
api = wandb.Api()
artifact = api.artifact(ARTIFACT)
# Download artifact
artifact.download(root=SAVE_DIR)
print("Files are being downloaded now...")
# TODO
# def download_model_from_wandb_run():
# """
# 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"
# CODE_PATHS = [
# "code/lightning_modules/lightning_module.py",
# "code/lightning_modules/models.py"
# ]
#
# api = wandb.Api()
# run = api.run(path=RUN_ID)
#
# # download model
# run.file(MODEL_PATH).download(replace=True)
#
# # download and replace your code
# for path in CODE_PATHS:
# run.file(path).download(root="../lightning_modules/", replace=True)
if __name__ == "__main__":
upload_artifact()
# download_artifact()
# download_model_from_wandb_run()
+1 -3
View File
@@ -1,9 +1,7 @@
torchvision>=0.8.1 torchvision>=0.8.1
pytorch-lightning>=1.0.7 pytorch-lightning>=1.0.8
pytorch-lightning-bolts>=0.2.5 pytorch-lightning-bolts>=0.2.5
wandb>=0.10.11 wandb>=0.10.11
PyYAML>=5.3.1 PyYAML>=5.3.1
scikit-learn>=0.23.2 scikit-learn>=0.23.2
efficientnet-pytorch>=0.7.0 efficientnet-pytorch>=0.7.0
pandas>=1.1.4
opencv-python>=4.4.0.46