11 files changed
+102
-36
No files matched your search
@@ -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:<br>
|
||||
`Ctrl + Shift + A -> type "Edit Configurations..." -> select "Emulate terminal in output console"`
|
||||
- run training:<br>
|
||||
`right click on train.py file -> "Run 'train'"`
|
||||
|
||||
|
||||
|
||||
|
||||
+32
-6
@@ -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()
|
||||
+15
-15
@@ -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()
|
||||
+3
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
File renamed without changes.
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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__,
|
||||
|
||||
@@ -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),
|
||||
|
||||
+2
-2
@@ -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
|
||||
Reference in new issue
Block a user