diff --git a/README.md b/README.md
index 14dc4bc..cdfeb59 100644
--- a/README.md
+++ b/README.md
@@ -14,10 +14,10 @@ The directory structure of new project looks like this:
│ │
│ ├── notebooks <- Jupyter notebooks
│ │
-│ ├── training_modules <- All modules necessary for training deep learning models
+│ ├── training_modules <- All modules useful for training deep learning models
│ │ ├── callbacks.py <- Useful training callbacks
-│ │ ├── data_modules.py <- "LightningDataModule" modules (wrappers for PyTorch "Dataset")
│ │ ├── datasets.py <- PyTorch "Dataset" modules
+│ │ ├── datamodules.py <- "LightningDataModule" modules (wrappers for PyTorch "Dataset")
│ │ ├── lightning_wrapper.py <- Contains train/val/test step methods executed during training
│ │ ├── loggers.py <- Initializers for different loggers (wandb, tensorboard, etc.)
│ │ ├── models.py <- Neural networks declarations
@@ -86,6 +86,8 @@ Installation command generator: https://pytorch.org/get-started/locally/
`right click on directory -> "Mark Directory as" -> "Sources Root"`
- set terminal emulation:
`Ctrl + Shift + A -> type "Edit Configurations..." -> select "Emulate terminal in output console"`
+- run training:
+`right click on train.py file -> "Run 'train'"`
diff --git a/project/hack_utils/artifacts_tools.py b/project/hack_utils/wandb_artifacts_tools.py
similarity index 57%
rename from project/hack_utils/artifacts_tools.py
rename to project/hack_utils/wandb_artifacts_tools.py
index 062056b..2cd6f63 100644
--- a/project/hack_utils/artifacts_tools.py
+++ b/project/hack_utils/wandb_artifacts_tools.py
@@ -3,12 +3,14 @@ import os
def upload_artifact():
- WANDB_PROJECT = "hackathon_template_test"
- WANDB_TEAM = "kino"
- FILES_TO_UPLOAD_PATH = "../data/skyhacks"
+ 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(
@@ -24,7 +26,8 @@ def upload_artifact():
name=ARTIFACT_NAME,
type=TYPE
)
- artifact.add_dir(FILES_TO_UPLOAD_PATH)
+ artifact.add_dir(FOLDER_TO_UPLOAD_PATH)
+ # artifact.add_file(MODEL_PATH)
# Upload artifact
run.log_artifact(artifact, aliases=["latest"])
@@ -44,6 +47,29 @@ def download_artifact():
print("Files are being downloaded now...")
+def download_model_from_wandb_run():
+ """
+ WARNING: This will overwrite your training_modules/models.py and training_modules/lightning_wrapper.py files!
+ """
+ RUN_ID = "kino/hackathon_template_test/lx9voyom"
+ MODEL_PATH = "last.ckpt"
+ CODE_PATHS = [
+ "code/training_modules/lightning_wrapper.py",
+ "code/training_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="../training_modules/", replace=True)
+
+
if __name__ == "__main__":
- # upload_artifact()
- download_artifact()
+ upload_artifact()
+ # download_artifact()
+ # download_model_from_wandb_run()
diff --git a/project/predict.py b/project/predict.py
index 54ad377..4274be7 100644
--- a/project/predict.py
+++ b/project/predict.py
@@ -1,20 +1,28 @@
from training_modules.lightning_wrapper import LitModel
+from training_modules.datamodules import *
+from training_modules.datasets import *
from training_modules import transforms
-import pytorch_lightning as pl
-from train import load_config
-import torch
+from PIL import Image
def predict():
- # load config
- config = load_config()
+ """
+ Loads model from checkpoint.
+ Model used in training_modules/lightning_wrapper.py and declaration of that model in training_modules/models.py
+ should be the same as during training.
+ """
+
+ CKPT_PATH = "epoch=0.ckpt"
# load model from checkpoint
- pretrained_model = LitModel.load_from_checkpoint("example.ckpt", hparams=config["hparams"])
+ pretrained_model = LitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
+
+ # switch to evaluation mode
pretrained_model.eval()
+ pretrained_model.freeze()
# load data
- img = None
+ img = Image.open("example_img.png").convert("RGB")
# preprocess
img = transforms.efficient_net_test_preprocess(img)
@@ -25,13 +33,5 @@ def predict():
print(output)
-def download_from_wandb():
- """
- WARNING: This will overwrite your models.py, lightning_wrapper.py and config.yaml files!
- """
- MODEL_PATH = ""
- CODE_PATH = ""
-
-
if __name__ == "__main__":
predict()
diff --git a/project/train.py b/project/train.py
index 9636e1c..2976d0a 100644
--- a/project/train.py
+++ b/project/train.py
@@ -5,7 +5,7 @@ import yaml
# custom
from training_modules.lightning_wrapper import LitModel
from training_modules.loggers import *
-from training_modules.data_modules import *
+from training_modules.datamodules import *
from training_modules.callbacks import *
@@ -40,7 +40,8 @@ def train(config):
# MetricsHeatmapLoggerCallback(),
# UnfreezeModelCallback(wait_epochs=5),
# ImagePredictionLoggerCallback(datamodule=datamodule),
- # SaveModelOnnxCallback(datamodule=datamodule, save_dir=wandb_logger.save_dir)
+ SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir),
+ # SaveOnnxModelToWandbCallback(datamodule=datamodule, save_dir=logger.save_dir)
]
# Init trainer
diff --git a/project/training_modules/callbacks.py b/project/training_modules/callbacks.py
index eae4053..59b8424 100644
--- a/project/training_modules/callbacks.py
+++ b/project/training_modules/callbacks.py
@@ -1,5 +1,6 @@
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import pytorch_lightning as pl
+from shutil import copy, copyfile
import seaborn
import torch
import wandb
@@ -20,9 +21,9 @@ class ExampleCallback(pl.Callback):
print('Do something when training ends.')
-class SaveModelOnnxCallback(pl.Callback):
+class SaveOnnxModelToWandbCallback(pl.Callback):
"""
- Save model in .onnx format.
+ Save model in .onnx format and upload to wandb.
Might crash since not all models are compatible with onnx.
"""
def __init__(self, datamodule, save_dir):
@@ -40,7 +41,7 @@ class SaveModelOnnxCallback(pl.Callback):
def save_onnx_model(self, pl_module):
file_path = os.path.join(self.save_dir, "model.onnx")
pl_module.to_onnx(file_path=file_path, input_sample=self.dummy_input.to(pl_module.device))
- wandb.save(file_path)
+ wandb.save(file_path, base_path=self.save_dir)
class ImagePredictionLoggerCallback(pl.Callback):
@@ -123,3 +124,34 @@ class MetricsHeatmapLoggerCallback(pl.Callback):
self.preds = []
self.targets = []
+
+
+class SaveCodeToWandbCallback(pl.Callback):
+ """
+ Upload specified files to wandb at the beginning of the run.
+ """
+ def __init__(self, wandb_save_dir):
+ self.wandb_save_dir = wandb_save_dir
+ self.files_to_be_saved = [
+ "training_modules/callbacks.py",
+ "training_modules/datamodules.py",
+ "training_modules/datasets.py",
+ "training_modules/lightning_wrapper.py",
+ "training_modules/loggers.py",
+ "training_modules/models.py",
+ "training_modules/transforms.py",
+ "train.py",
+ "config.yaml"
+ ]
+
+ def on_sanity_check_end(self, trainer, pl_module):
+ """Upload files when all validation sanity checks end."""
+ for file in self.files_to_be_saved:
+ dst_path = os.path.join(self.wandb_save_dir, "code", file)
+
+ path, filename = os.path.split(dst_path)
+ if not os.path.exists(path):
+ os.makedirs(path)
+
+ copy(file, dst_path)
+ wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
diff --git a/project/training_modules/data_modules.py b/project/training_modules/datamodules.py
similarity index 100%
rename from project/training_modules/data_modules.py
rename to project/training_modules/datamodules.py
diff --git a/project/training_modules/datasets.py b/project/training_modules/datasets.py
index e495b85..1ad345c 100644
--- a/project/training_modules/datasets.py
+++ b/project/training_modules/datasets.py
@@ -3,7 +3,7 @@ from PIL import Image
import os
-class TestDataset(Dataset):
+class TestDatasetForImgs(Dataset):
def __init__(self, img_dir, transform):
self.transform = transform
diff --git a/project/training_modules/lightning_wrapper.py b/project/training_modules/lightning_wrapper.py
index 1990ad2..e44aaf3 100644
--- a/project/training_modules/lightning_wrapper.py
+++ b/project/training_modules/lightning_wrapper.py
@@ -10,10 +10,12 @@ from training_modules.models import *
class LitModel(pl.LightningModule):
- def __init__(self, hparams):
+ def __init__(self, hparams=None):
super().__init__()
- self.save_hyperparameters(hparams)
+ if hparams:
+ self.save_hyperparameters(hparams)
+
self.model = SimpleLinearMNIST(config=self.hparams)
def forward(self, x):
diff --git a/project/training_modules/loggers.py b/project/training_modules/loggers.py
index 0dca73e..5f71b3d 100644
--- a/project/training_modules/loggers.py
+++ b/project/training_modules/loggers.py
@@ -11,9 +11,11 @@ def get_wandb_logger(config, lit_model, datamodule):
id=config["resume"]["wandb_run_id"] if config["resume"]["resume_from_ckpt"] else None,
log_model=config["loggers"]["wandb"]["log_model"],
offline=config["loggers"]["wandb"]["offline"],
- save_dir="logs/"
+ save_dir="logs/",
+ save_code=False
)
- os.mkdir("logs/") if not os.path.exists("logs/") else None
+ if not os.path.exists("logs/"):
+ os.mkdir("logs/")
wandb_logger.watch(lit_model.model, log=None)
wandb_logger.log_hyperparams({
"model_name": lit_model.model.__class__.__name__,
diff --git a/project/training_modules/models.py b/project/training_modules/models.py
index 7d879ac..083a3a8 100644
--- a/project/training_modules/models.py
+++ b/project/training_modules/models.py
@@ -13,7 +13,8 @@ class SimpleLinearMNIST(nn.Module):
# mnist images are (1, 28, 28) (channels, width, height)
self.model = nn.Sequential(
- nn.Linear(28 * 28, config["lin1_size"]),
+ nn.Linear(28*28, config["lin1_size"]),
+ # nn.Linear(3*32*32, config["lin1_size"]), # for CIFAR10
nn.BatchNorm1d(config["lin1_size"]),
nn.ReLU(),
nn.Dropout(p=0.3),
diff --git a/requirements.txt b/requirements.txt
index 1d6bc7f..652f8bf 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,9 +1,9 @@
torchvision>=0.8.1
pytorch-lightning>=1.0.7
pytorch-lightning-bolts>=0.2.5
-wandb>=0.10.10
+wandb>=0.10.11
PyYAML>=5.3.1
scikit-learn>=0.23.2
efficientnet-pytorch>=0.7.0
pandas>=1.1.4
-seaborn>=0.11.0
+opencv-python>=4.4.0.46