diff --git a/.gitignore b/.gitignore index 476adec..114bd81 100644 --- a/.gitignore +++ b/.gitignore @@ -230,4 +230,4 @@ project/lightning_logs/ project/wandb/ project/logs/ -project/config.yaml +project/project_config.yaml diff --git a/README.md b/README.md index 7423dd1..61f2972 100644 --- a/README.md +++ b/README.md @@ -12,43 +12,38 @@ Read [SETUP.md](SETUP.md) The directory structure of new project looks like this: ``` ├── project -│ ├── data <- Data from third party sources +│ ├── data <- Data from third party sources │ │ -│ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning +│ ├── data_modules <- Data related modules +│ │ ├── datamodules.py <- "LightningDataModule" modules +│ │ ├── datasets.py <- "Dataset" modules +│ │ └── transforms.py <- Data transformations │ │ -│ ├── docs <- Useful pdf files +│ ├── logs <- Logs generated by Weights&Biases and PyTorch Lightning │ │ -│ ├── hack_utils <- Any extra scripts not belonging to training pipeline +│ ├── utils <- Any extra scripts not belonging to training pipeline │ │ -│ ├── notebooks <- Jupyter notebooks +│ ├── notebooks <- Jupyter notebooks │ │ -│ ├── lightning_modules <- PyTorch Lightning related modules -│ │ ├── data_modules <- Data related modules -│ │ │ ├── datamodules.py <- "LightningDataModule" modules -│ │ │ ├── datasets.py <- "Dataset" modules -│ │ │ └── transforms.py <- Data transformations (data preprocessing) -│ │ │ +│ ├── lightning_modules <- PyTorch Lightning related modules │ │ ├── callbacks.py <- Training callbacks │ │ └── init_utils.py <- Some useful initializers │ │ -│ ├── models +│ ├── models <- All your models should be located here │ │ ├── simple_mnist_classifier <- Example model -│ │ │ ├── lightning_module.py <- Contains train/val/test step methods -│ │ │ ├── models.py <- Neural networks declarations -│ │ │ ├── predict.py <- Predicting from trained model -│ │ │ └── __init__.py +│ │ │ ├── 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 -│ │ │ ├── models.py -│ │ │ ├── predict.py -│ │ │ └── __init__.py +│ │ │ ├── lightning_module.py <- Contains train/val/test step methods +│ │ │ └── models.py <- Model declarations used in lightning_module.py │ │ │ │ │ └── ... │ │ -│ ├── config.yaml <- Training configuration -│ ├── execute_sweep.py <- Special file for executing wandb sweeps (hyperparameter search) -│ └── train.py <- Train model +│ ├── project_config.yaml <- Project configuration +│ ├── run_configs.yaml <- Run configurations +│ ├── execute_sweep.py <- Special file for executing wandb sweeps (hyperparameter search) +│ └── train.py <- Train model │ ├── .gitignore ├── LICENSE @@ -58,39 +53,11 @@ The directory structure of new project looks like this: └── requirements.txt ``` -## Config parameters -#### [config.yaml](project/config.yaml): +## Project config parameters +#### [project_config.yaml](project/project_config.yaml) ```yaml num_of_gpus: -1 -model_configs: - simple_mnist_classifier_v1: - model_folder_name: "simple_mnist_classifier" - max_epochs: 3 - lr: 0.001 - batch_size: 64 - weight_decay: 0.000001 - gradient_clip_val: 0.5 - accumulate_grad_batches: 1 - input_size: 784 - output_size: 10 - lin1_size: 256 - lin2_size: 256 - 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 - - transfer_learning_cifar10_classifier_v1: - ... - - transfer_learning_cifar10_classifier_v2: - ... - resume_training: lightning_ckpt: resume_from_ckpt: False @@ -122,9 +89,47 @@ callbacks: printing: progress_bar_refresh_rate: 5 - weights_summary: "top" + weights_summary: "top" # "full" profiler: False ``` +## Run config parameters +#### [run_configs.yaml](project/run_configs.yaml) +You can store many run configurations in this file.
+Example run configuration: +```yaml +CIFAR10_CLASSIFIER_V2: + trainer: + max_epochs: 10 + gradient_clip_val: 0.5 + accumulate_grad_batches: 1 + limit_train_batches: 1.0 + model: + name: "simple_cifar10_classifier" + lr: 0.002 + weight_decay: 0.00001 + output_size: 10 + lin1_size: 512 + lin2_size: 256 + dataset: + name: "CIFAR10DataModule" + batch_size: 256 + train_val_split_ratio: 0.9 + num_workers: 1 + pin_memory: False +``` + +The run configuration that you want to train with needs to be chose in [train.py](project/train.py): +```python +if __name__ == "__main__": + RUN_CONFIG = "MNIST_CLASSIFIER_V1" # choose your run config here + + 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 -Read [TIPS.md](TIPS.md) +For training tips read [TIPS.md](TIPS.md) diff --git a/project/config.yaml b/project/config.yaml deleted file mode 100644 index 7db33a4..0000000 --- a/project/config.yaml +++ /dev/null @@ -1,95 +0,0 @@ -num_of_gpus: -1 - -model_configs: - 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 - lr: 0.001 - batch_size: 64 - 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 - 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 - - transfer_learning_cifar10_classifier_v1: - model_folder_name: "transfer_learning_img_classifier" - max_epochs: 3 - lr: 0.001 - batch_size: 128 - weight_decay: 0.000001 - gradient_clip_val: 0.5 - accumulate_grad_batches: 1 - output_size: 10 - lin1_size: 512 - 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: - model_folder_name: "transfer_learning_img_classifier" - max_epochs: 3 - lr: 0.001 - batch_size: 128 - weight_decay: 0.000001 - gradient_clip_val: 0.5 - accumulate_grad_batches: 1 - output_size: 10 - lin1_size: 512 - 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 - -resume_training: - lightning_ckpt: - resume_from_ckpt: False - ckpt_path: "logs/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 diff --git a/project/lightning_modules/data_modules/datamodules.py b/project/data_modules/datamodules.py similarity index 88% rename from project/lightning_modules/data_modules/datamodules.py rename to project/data_modules/datamodules.py index dce9014..a318933 100644 --- a/project/lightning_modules/data_modules/datamodules.py +++ b/project/data_modules/datamodules.py @@ -1,23 +1,23 @@ from torch.utils.data import DataLoader, random_split from torchvision.datasets import MNIST, CIFAR10 +from torchvision.transforms import transforms import pytorch_lightning as pl -# custom data_modules - class ExampleDataModule(pl.LightningDataModule): """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, - pin_memory=False, **args): + 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.transforms = transforms 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 @@ -44,17 +44,18 @@ class ExampleDataModule(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, - pin_memory=False, **args): + 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.transforms = transforms 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 @@ -88,17 +89,18 @@ class MNISTDataModule(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, - pin_memory=False, **args): + 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.transforms = transforms 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 diff --git a/project/lightning_modules/data_modules/datasets.py b/project/data_modules/datasets.py similarity index 89% rename from project/lightning_modules/data_modules/datasets.py rename to project/data_modules/datasets.py index 1ad345c..4598016 100644 --- a/project/lightning_modules/data_modules/datasets.py +++ b/project/data_modules/datasets.py @@ -4,6 +4,7 @@ import os class TestDatasetForImgs(Dataset): + """Example dataset class for loading images from folder.""" def __init__(self, img_dir, transform): self.transform = transform diff --git a/project/lightning_modules/data_modules/transforms.py b/project/data_modules/transforms.py similarity index 67% rename from project/lightning_modules/data_modules/transforms.py rename to project/data_modules/transforms.py index 6f95349..4e20156 100644 --- a/project/lightning_modules/data_modules/transforms.py +++ b/project/data_modules/transforms.py @@ -1,40 +1,40 @@ from torchvision import transforms -minst_train_preprocess = transforms.Compose([ +mnist_train_transforms = transforms.Compose([ transforms.ToTensor(), ]) -mnist_test_preprocess = transforms.Compose([ +mnist_test_transforms = transforms.Compose([ transforms.ToTensor() ]) -img_augmentation_transformations = [ +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_preprocess = 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.RandomCrop(224), transforms.ToTensor(), - transforms.RandomApply(img_augmentation_transformations, 0.8), + 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_preprocess = transforms.Compose([ +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]), ]) -cifar10_train_preprocess = transforms.Compose([ +cifar10_train_transforms = transforms.Compose([ transforms.ToTensor(), transforms.RandomHorizontalFlip(p=0.5), ]) -cifar10_test_preprocess = transforms.Compose([ +cifar10_test_transforms = transforms.Compose([ transforms.ToTensor(), ]) diff --git a/project/docs/conda-cheatsheet.pdf b/project/docs/conda-cheatsheet.pdf deleted file mode 100644 index 5e1dff5..0000000 Binary files a/project/docs/conda-cheatsheet.pdf and /dev/null differ diff --git a/project/docs/pandas-cheatsheet.pdf b/project/docs/pandas-cheatsheet.pdf deleted file mode 100644 index 925b424..0000000 Binary files a/project/docs/pandas-cheatsheet.pdf and /dev/null differ diff --git a/project/docs/pycharm-cheatsheet.pdf b/project/docs/pycharm-cheatsheet.pdf deleted file mode 100644 index 17bfa52..0000000 Binary files a/project/docs/pycharm-cheatsheet.pdf and /dev/null differ diff --git a/project/execute_sweep.py b/project/execute_sweep.py index 4dcbea4..ec42e10 100644 --- a/project/execute_sweep.py +++ b/project/execute_sweep.py @@ -1,14 +1,14 @@ +# THIS FILE SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT! import wandb import train -# THIS FILE SHOULDN't BE EXECUTED DIRECTLY, IT SHOULD BE RUN BY WANDB SWEEP AGENT! +# Choose which run config to optimize +RUN_CONFIG = "MNIST_CLASSIFIER_V1" # Load project config -conf = train.load_config() - -# Choose model for hyperparameter search -model_conf = conf["model_configs"]["simple_mnist_classifier_v1"] +project_conf = train.load_config("project_config.yaml") +run_conf = train.load_config("run_configs.yaml")[RUN_CONFIG] # Initialize wandb wandb.init() @@ -16,8 +16,14 @@ 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" and not key.startswith("dataset/"): - model_conf[key] = value + 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(config=conf, model_config=model_conf) +train.train(project_config=project_conf, run_config=run_conf) diff --git a/project/lightning_modules/callbacks.py b/project/lightning_modules/callbacks.py index 3471708..11f3838 100644 --- a/project/lightning_modules/callbacks.py +++ b/project/lightning_modules/callbacks.py @@ -134,13 +134,14 @@ class SaveCodeToWandbCallback(pl.Callback): def __init__(self, wandb_save_dir, lit_model): self.wandb_save_dir = wandb_save_dir self.additional_files_to_be_saved = [ - "lightning_modules/data_modules/datamodules.py", - "lightning_modules/data_modules/datasets.py", - "lightning_modules/data_modules/transforms.py", + "data_modules/datamodules.py", + "data_modules/datasets.py", + "data_modules/transforms.py", "lightning_modules/callbacks.py", "lightning_modules/init_utils.py", "train.py", - "config.yaml" + "project_config.yaml", + "run_configs.yaml", ] self.model_path = os.path.dirname(inspect.getfile(lit_model.__class__)) diff --git a/project/lightning_modules/init_utils.py b/project/lightning_modules/init_utils.py index a01b44b..aced490 100644 --- a/project/lightning_modules/init_utils.py +++ b/project/lightning_modules/init_utils.py @@ -1,46 +1,49 @@ -from pytorch_lightning.loggers import WandbLogger, TensorBoardLogger, CometLogger, MLFlowLogger, NeptuneLogger +from pytorch_lightning.loggers import WandbLogger from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping -from lightning_modules.data_modules import datamodules, transforms +from data_modules import datamodules import importlib import os def init_lit_model(model_config): - module_path = "models." + model_config["model_folder_name"] + ".lightning_module" + """Load LitModel from folder specified in run config.""" + module_path = "models." + model_config["name"] + ".lightning_module" + model_config["model_folder_name"] = model_config.pop("name") 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"] - ) +def init_datamodule(dataset_config): + """Load datamodule from class specified in run config.""" + datamodule_class = getattr(datamodules, dataset_config["name"]) + dataset_config["datamodule_name"] = dataset_config.pop("name") + dataset_config = dataset_config.copy() + dataset_config.pop("datamodule_name") + datamodule = datamodule_class(**dataset_config) datamodule.prepare_data() datamodule.setup() return datamodule -def init_main_callbacks(config): +def init_main_callbacks(project_config): + """Initialize EarlyStopping callback and ModelCheckpoint callback.""" callbacks = [ EarlyStopping( - monitor=config["callbacks"]["early_stop"]["monitor"], - patience=config["callbacks"]["early_stop"]["patience"], - mode=config["callbacks"]["early_stop"]["mode"], + monitor=project_config["callbacks"]["early_stop"]["monitor"], + patience=project_config["callbacks"]["early_stop"]["patience"], + mode=project_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"], + monitor=project_config["callbacks"]["checkpoint"]["monitor"], + save_top_k=project_config["callbacks"]["checkpoint"]["save_top_k"], + mode=project_config["callbacks"]["checkpoint"]["mode"], + save_last=project_config["callbacks"]["checkpoint"]["save_last"], ) ] return callbacks -def init_wandb_logger(config, lit_model, datamodule): +def init_wandb_logger(config, run_config, lit_model, datamodule): + """Initialize Weights&Biases logger.""" wandb_logger = WandbLogger( project=config["loggers"]["wandb"]["project"], job_type=config["loggers"]["wandb"]["job_type"], @@ -55,7 +58,9 @@ def init_wandb_logger(config, lit_model, datamodule): ) if not os.path.exists("logs/"): os.mkdir("logs/") - wandb_logger.watch(lit_model.model, log=None) + if hasattr(lit_model, 'model'): + wandb_logger.watch(lit_model.model, log=None) + wandb_logger.watch(lit_model, log=None) wandb_logger.log_hyperparams({ "model_name": lit_model.model.__class__.__name__, "optimizer": lit_model.configure_optimizers().__class__.__name__, @@ -63,6 +68,9 @@ def init_wandb_logger(config, lit_model, datamodule): "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, }) + wandb_logger.log_hyperparams(run_config["trainer"]) + wandb_logger.log_hyperparams(run_config["model"]) + wandb_logger.log_hyperparams(run_config["dataset"]) return wandb_logger diff --git a/project/models/simple_mnist_classifier/__init__.py b/project/models/simple_mnist_classifier/__init__.py deleted file mode 100644 index ab9fb22..0000000 --- a/project/models/simple_mnist_classifier/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .lightning_module import LitModel diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index def73f4..4ee54ad 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -67,4 +67,4 @@ class LitModel(pl.LightningModule): return loss def configure_optimizers(self): - return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"]) + return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay) diff --git a/project/models/simple_mnist_classifier/predict.py b/project/models/simple_mnist_classifier/predict.py deleted file mode 100644 index 2ccf980..0000000 --- a/project/models/simple_mnist_classifier/predict.py +++ /dev/null @@ -1,35 +0,0 @@ -from models.simple_mnist_classifier.lightning_module import LitModel -from lightning_modules.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 - pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH) - - # switch to evaluation mode - pretrained_model.eval() - pretrained_model.freeze() - - # load data - img = Image.open("../../example_img.png").convert("L") - - # preprocess - img = transforms.mnist_test_preprocess(img) - img = img.reshape((1, *img.size())) # reshape to form batch of size 1 - - # inference - output = pretrained_model(img) - print(output) - - -if __name__ == "__main__": - predict() diff --git a/project/models/transfer_learning_img_classifier/__init__.py b/project/models/transfer_learning_img_classifier/__init__.py deleted file mode 100644 index ab9fb22..0000000 --- a/project/models/transfer_learning_img_classifier/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .lightning_module import LitModel diff --git a/project/models/transfer_learning_img_classifier/lightning_module.py b/project/models/transfer_learning_img_classifier/lightning_module.py index c76a122..c03932f 100644 --- a/project/models/transfer_learning_img_classifier/lightning_module.py +++ b/project/models/transfer_learning_img_classifier/lightning_module.py @@ -67,4 +67,4 @@ class LitModel(pl.LightningModule): return loss def configure_optimizers(self): - return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams["weight_decay"]) + return torch.optim.Adam(self.parameters(), lr=self.hparams.lr, weight_decay=self.hparams.weight_decay) diff --git a/project/models/transfer_learning_img_classifier/models.py b/project/models/transfer_learning_img_classifier/models.py index ed4e362..ea1bb23 100644 --- a/project/models/transfer_learning_img_classifier/models.py +++ b/project/models/transfer_learning_img_classifier/models.py @@ -1,4 +1,3 @@ -from pl_bolts.models.self_supervised import CPCV2 from efficientnet_pytorch import EfficientNet from torchvision import models from torch import nn @@ -9,7 +8,7 @@ class EfficientNetPretrained(nn.Module): def __init__(self, config): super().__init__() - self.model = EfficientNet.from_pretrained('efficientnet-b1') + self.model = EfficientNet.from_pretrained('efficientnet-b0') for param in self.model.parameters(): param.requires_grad = False @@ -81,35 +80,3 @@ class ResnextPretrained(nn.Module): def forward(self, x): return self.model(x) - - -# this model doesn't work yet, we wait for lightning-bolts patch -# class ResnetPretrainedUnsupervised(nn.Module): -# """ -# Trained without labels on Imagenet. -# Perhaps the features when trained without labels are much better for classification or other tasks. -# """ -# def __init__(self, config): -# super().__init__() -# -# self.model = CPCV2(encoder='resnet18', pretrained='imagenet128').encoder -# # self.model = CPCV2(encoder='resnet18', pretrained='stl10').encoder -# -# 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) diff --git a/project/notebooks/.gitkeep b/project/notebooks/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/project/notebooks/notebook_tricks.ipynb b/project/notebooks/notebook_tricks.ipynb deleted file mode 100644 index a7d2590..0000000 --- a/project/notebooks/notebook_tricks.ipynb +++ /dev/null @@ -1,372 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Import modules from parent directory" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false - } - }, - "outputs": [], - "source": [ - "# add directory above current directory to path\n", - "import sys\n", - "sys.path.insert(0, '..')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false - } - }, - "outputs": [], - "source": [ - "# now we can import modules from parent directory\n", - "import train\n", - "import pipeline_modules" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Define function to print object length with commas" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "showlen = lambda data: print(f\"{len(data):,}\")\n", - "showlen([0 for i in range(2395940)])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Create quick progress bars with tqdm" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - }, - "scrolled": true - }, - "outputs": [], - "source": [ - "from tqdm import tqdm\n", - "import time\n", - "\n", - "for i in tqdm(range(10)):\n", - " time.sleep(1)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "source": [ - "### Prettier ipywidgets version of the progress bar specifically for the notebook environment" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "from tqdm.auto import tqdm\n", - "\n", - "for i in tqdm(range(10)):\n", - " time.sleep(1)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "source": [ - "### Beyond basic for loops, you can also use it in list comprehensions" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "some_list = [x**2 for x in tqdm(10*[0])]" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "source": [ - "### You can even use it with multiprocessing\n", - "https://stackoverflow.com/questions/41920124/multiprocessing-use-tqdm-to-display-a-progress-bar" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### If you’re iterating over a generator, tqdm won’t know the length and the progress bar will be more limited but if you know or can calculate the total length you can supply that as an argument" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# generator expressions are surrounded by parenthesis ()\n", - "generator = (x**2 for x in [1, 2, 3, 4])\n", - "# print(next(generator))\n", - "\n", - "some_list = [x for x in tqdm(generator, total=4)]" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Jupyter Notebook Shortcuts" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "- Esc will take you into command mode where you can navigate around your notebook with arrow keys.\n", - "- While in command mode:\n", - " - A to insert a new cell above the current cell, B to insert a new cell below.\n", - " - M to change the current cell to Markdown, Y to change it back to code\n", - " - D + D (press the key twice) to delete the current cell\n", - " - Enter will take you from command mode back into edit mode for the given cell.\n", - "- Shift + Tab will show you the Docstring (documentation) for the the object you have just typed in a code cell – you can keep pressing this short cut to cycle through a few modes of documentation.\n", - "- Ctrl + Shift + - will split the current cell into two from where your cursor is.\n", - "- Esc + O Toggle cell output.\n", - "- Select Multiple Cells:\n", - " - Shift + J or Shift + Down selects the next sell in a downwards direction. You can also select sells in an upwards direction by using Shift + K or Shift + Up.\n", - " - Once cells are selected, you can then delete / copy / cut / paste / run them as a batch. This is helpful when you need to move parts of a notebook.\n", - " - You can also use Shift + M to merge multiple cells." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "from IPython.display import IFrame, HTML, YouTubeVideo\n", - "# YouTubeVideo(\"ZbrRrXiWBKc\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "from ipywidgets import FloatSlider, interactive, IntSlider" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "def simple_ex(amplitude=2.0, phase=0.0):\n", - " x = np.linspace(-2*np.pi, 2*np.pi, 1000)\n", - " y = amplitude * np.sin(x + phase)\n", - " plt.rcParams['figure.figsize'] = 8,6\n", - " plt.figure()\n", - " plt.plot(x, y)\n", - " plt.xlim(-3, 3)\n", - " plt.ylim(-2*np.pi, 2*np.pi)\n", - "\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "amplitude_slider = FloatSlider(value=2.0, min=-10, max=10.0, step=.05)\n", - "phase_slider = FloatSlider(value=0.0, min=-np.pi, max=np.pi, step=.05)\n", - "\n", - "w = interactive(simple_ex,\n", - " amplitude=amplitude_slider,\n", - " phase=phase_slider\n", - " )" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "import pandas as pd\n", - "data = pd.read_csv('loan_train.csv')\n", - "\n", - "import pandas_profiling\n", - "report = pandas_profiling.ProfileReport(data)\n", - "\n", - "report" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "# print many outputs in the same cell!\n", - "from IPython.core.interactiveshell import InteractiveShell\n", - "InteractiveShell.ast_node_interactivity = \"all\"\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "%history -t" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "pycharm": { - "is_executing": false, - "name": "#%% md\n" - } - }, - "source": [ - "https://towardsdatascience.com/bringing-the-best-out-of-jupyter-notebooks-for-data-science-f0871519ca29" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "pycharm": { - "name": "#%%\n" - } - }, - "outputs": [], - "source": [ - "\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.7.4" - }, - "pycharm": { - "stem_cell": { - "cell_type": "raw", - "metadata": { - "collapsed": false - }, - "source": [] - } - } - }, - "nbformat": 4, - "nbformat_minor": 1 -} diff --git a/project/project_config.yaml b/project/project_config.yaml new file mode 100644 index 0000000..8e87346 --- /dev/null +++ b/project/project_config.yaml @@ -0,0 +1,35 @@ +num_of_gpus: -1 + +resume_training: + lightning_ckpt: + resume_from_ckpt: False + ckpt_path: "logs/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 diff --git a/project/run_configs.yaml b/project/run_configs.yaml new file mode 100644 index 0000000..fbfc079 --- /dev/null +++ b/project/run_configs.yaml @@ -0,0 +1,55 @@ +MNIST_CLASSIFIER_V1: + trainer: + max_epochs: 5 + model: + name: "simple_mnist_classifier" + lr: 0.001 + weight_decay: 0.000001 + input_size: 784 # img size is 28*28*1 + output_size: 10 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + dataset: + name: "MNISTDataModule" + 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 + train_val_split_ratio: 0.9 + num_workers: 1 + pin_memory: False + +CIFAR10_CLASSIFIER_V2: + trainer: + max_epochs: 10 + gradient_clip_val: 0.5 + accumulate_grad_batches: 2 + limit_train_batches: 1.0 + model: + name: "transfer_learning_img_classifier" + lr: 0.002 + weight_decay: 0.00001 + output_size: 10 + lin1_size: 512 + lin2_size: 256 + dataset: + name: "CIFAR10DataModule" + batch_size: 256 + train_val_split_ratio: 0.9 + num_workers: 4 + pin_memory: True diff --git a/project/train.py b/project/train.py index fd04d2a..d1e4a03 100644 --- a/project/train.py +++ b/project/train.py @@ -6,84 +6,92 @@ from lightning_modules.init_utils import * from lightning_modules.callbacks import * -def train(config, model_config): +def train(project_config, run_config): - # Init lightning model - lit_model = init_lit_model(model_config) + # Init PyTorch Lightning model ⚡ + lit_model = init_lit_model(model_config=run_config["model"]) - # Init lightning datamodule - datamodule = init_datamodule(model_config) + # Init PyTorch Lightning datamodule ⚡ + datamodule = init_datamodule(dataset_config=run_config["dataset"]) - # Init logger - logger = init_wandb_logger(config, lit_model, datamodule) + # Init Weights&Biases logger + logger = init_wandb_logger(project_config, run_config, lit_model, datamodule) - # Init callbacks - callbacks = init_main_callbacks(config) + # Init checkpoint and early stoping callbacks + callbacks = init_main_callbacks(project_config) + + # Add your custom callbacks callbacks.extend([ # MetricsHeatmapLoggerCallback(), # UnfreezeModelCallback(wait_epochs=5), - # ImagePredictionLoggerCallback(datamodule=datamodule), SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model), - # SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir) ]) - # Init trainer + # Init PyTorch Lightning trainer ⚡ trainer = pl.Trainer( + # whether to use gpu and how many + gpus=project_config["num_of_gpus"], + + # experiment logging logger=logger, + + # useful callbacks callbacks=callbacks, - 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, + # resuming training from checkpoint + resume_from_checkpoint=project_config["resume_training"]["lightning_ckpt"]["ckpt_path"] + if project_config["resume_training"]["lightning_ckpt"]["resume_from_ckpt"] else None, - # model related: - max_epochs=model_config["max_epochs"], - accumulate_grad_batches=model_config["accumulate_grad_batches"], - gradient_clip_val=model_config["gradient_clip_val"], + # print related + progress_bar_refresh_rate=project_config["printing"]["progress_bar_refresh_rate"], + profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None, + weights_summary=project_config["printing"]["weights_summary"], - # print 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"], + # run related + max_epochs=run_config["trainer"]["max_epochs"], + min_epochs=run_config["trainer"].get("min_epochs", 1), + accumulate_grad_batches=run_config["trainer"].get("accumulate_grad_batches", 1), + gradient_clip_val=run_config["trainer"].get("gradient_clip_val", 0.5), - # these are mostly for debugging (read TIPS.md for explanation): - 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, + # these are mostly for debugging (read TIPS.md for explanation) + fast_dev_run=run_config["trainer"].get("fast_dev_run", False), + limit_train_batches=run_config["trainer"].get("limit_train_batches", 1.0), + limit_val_batches=run_config["trainer"].get("limit_val_batches", 1.0), + limit_test_batches=run_config["trainer"].get("limit_test_batches", 1.0), + val_check_interval=run_config["trainer"].get("val_check_interval", 1.0), + num_sanity_val_steps=run_config["trainer"].get("fast_dev_run", 3), + # default log dir if no logger is found default_root_dir="logs/lightning_logs", ) - # Test before training + # Evaluate model on test set before training # trainer.test(model=lit_model, datamodule=datamodule) - # Save checkpoint - # trainer.save_checkpoint("random.ckpt") - - # Train the model ⚡ + # Train the model trainer.fit(model=lit_model, datamodule=datamodule) - # Evaluate model on test set + # Evaluate model on test set after training trainer.test() -def load_config(): - with open("config.yaml", "r") as ymlfile: +def load_config(path): + with open(path, "r") as ymlfile: config = yaml.load(ymlfile, Loader=yaml.FullLoader) return config if __name__ == "__main__": - conf = load_config() - # --------------------------------------- CHOOSE YOUR MODEL HEREEE ↓↓↓ --------------------------------------- # + # --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- # + # --------------------------------------------------- ↓↓↓ ---------------------------------------------------- # + RUN_CONFIG = "MNIST_CLASSIFIER_V1" + # RUN_CONFIG = "CIFAR10_CLASSIFIER_V1" + # RUN_CONFIG = "CIFAR10_CLASSIFIER_V2" + # --------------------------------------------------- ↑↑↑ ---------------------------------------------------- # + # --------------------------------------- CHOOSE YOUR RUN CONFIG HEREE --------------------------------------- # - model_conf = conf["model_configs"]["simple_mnist_classifier_v1"] - # model_conf = conf["model_configs"]["transfer_learning_cifar10_classifier_v1"] + project_conf = load_config("project_config.yaml") + run_conf = load_config("run_configs.yaml")[RUN_CONFIG] - # --------------------------------------- CHOOSE YOUR MODEL HEREEE ↑↑↑ --------------------------------------- # - - train(config=conf, model_config=model_conf) + train(project_config=project_conf, run_config=run_conf) diff --git a/project/models/transfer_learning_img_classifier/predict.py b/project/utils/predict.py similarity index 70% rename from project/models/transfer_learning_img_classifier/predict.py rename to project/utils/predict.py index 75a49fd..6fa11a0 100644 --- a/project/models/transfer_learning_img_classifier/predict.py +++ b/project/utils/predict.py @@ -1,5 +1,5 @@ from models.transfer_learning_img_classifier.lightning_module import LitModel -from lightning_modules.data_modules import transforms +from data_modules import transforms from PIL import Image @@ -13,21 +13,21 @@ def predict(): CKPT_PATH = "epoch=0.ckpt" # load model from checkpoint - pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH) + trained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH) # switch to evaluation mode - pretrained_model.eval() - pretrained_model.freeze() + trained_model.eval() + trained_model.freeze() # load data img = Image.open("../../example_img.png").convert("RGB") # preprocess - img = transforms.imagenet_test_preprocess(img) + img = transforms.imagenet_test_transforms(img) img = img.reshape((1, *img.size())) # reshape to form batch of size 1 # inference - output = pretrained_model(img) + output = trained_model(img) print(output) diff --git a/project/hack_utils/wandb_artifacts_tools.py b/project/utils/wandb_artifacts_tools.py similarity index 100% rename from project/hack_utils/wandb_artifacts_tools.py rename to project/utils/wandb_artifacts_tools.py