make paths relative
This commit is contained in:
1 parent
10fbd62ca7
commit
249992ee0a
9 files changed
+81
-128
No files matched your search
@@ -1,61 +0,0 @@
|
||||
## Setup
|
||||
1. Install anaconda if you don't already have it
|
||||
|
||||
https://docs.conda.io/projects/conda/en/latest/user-guide/install/download.html
|
||||
|
||||
2. Clone repo
|
||||
```
|
||||
git clone https://github.com/kinoai/hackathon-template
|
||||
cd hackathon-template
|
||||
```
|
||||
3. Create conda environment (change 'hack_env' to any name you want)
|
||||
```
|
||||
conda update conda
|
||||
conda env create -f conda_env.yaml -n hack_env
|
||||
conda activate hack_env
|
||||
```
|
||||
4. Make sure proper python PATH is loaded<br>
|
||||
- Unix
|
||||
```
|
||||
which python
|
||||
```
|
||||
- Windows
|
||||
```
|
||||
for %i in (python.exe) do @echo. %~$PATH:i
|
||||
```
|
||||
Expected result: `PATH_TO_CONDA/envs/ENV_NAME/bin/python`
|
||||
5. Install requirements
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
6. Log to your Weights&Biases account
|
||||
```
|
||||
wandb login
|
||||
```
|
||||
7. Run training
|
||||
```
|
||||
cd project
|
||||
python train.py
|
||||
```
|
||||
<br>
|
||||
|
||||
|
||||
#### Important notes!
|
||||
- If you're using CUDA compatible GPU make sure your drivers are updated!
|
||||
- If you are not using GPU (CUDA incompatible GPU) you may need to specify the number of GPUs manually instead of leaving the default `-1` in `project_config.yaml`:
|
||||
```
|
||||
num_of_gpus: 0
|
||||
```
|
||||
<br>
|
||||
|
||||
|
||||
## PyCharm setup
|
||||
- open this repository as PyCharm project
|
||||
- set "hack_env" as project interpreter:<br>
|
||||
`Ctrl + Shift + A -> type "Project Interpreter"`
|
||||
- mark folder "project" as sources root:<br>
|
||||
`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'"`
|
||||
+1
-2
@@ -1,4 +1,4 @@
|
||||
#name: hack_env
|
||||
#name: conda_env_name
|
||||
channels:
|
||||
- pytorch
|
||||
- conda-forge
|
||||
@@ -10,4 +10,3 @@ dependencies:
|
||||
- pytorch
|
||||
- torchvision
|
||||
- torchaudio
|
||||
- jupyter
|
||||
@@ -6,7 +6,7 @@ import os
|
||||
class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder.
|
||||
'Dataset' classes can be used by 'DataModule' classes.
|
||||
'Dataset' classes can be used by 'DataModule' class.
|
||||
"""
|
||||
|
||||
def __init__(self, img_dir, transform):
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
MNIST_CLASSIFIER_V1:
|
||||
trainer:
|
||||
min_epochs: 1
|
||||
max_epochs: 5
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 1
|
||||
limit_train_batches: 1.0
|
||||
model:
|
||||
model_folder: "simple_mnist_classifier"
|
||||
lr: 0.001
|
||||
@@ -28,7 +25,11 @@ MNIST_CLASSIFIER_V2:
|
||||
max_epochs: 10
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 2
|
||||
fast_dev_run: False
|
||||
limit_train_batches: 1.0
|
||||
limit_val_batches: 1.0
|
||||
limit_test_batches: 1.0
|
||||
val_check_interval: 1.0
|
||||
model:
|
||||
model_folder: "simple_mnist_classifier"
|
||||
lr: 0.002
|
||||
|
||||
+25
-21
@@ -2,7 +2,9 @@ from pytorch_lightning.profiler import SimpleProfiler
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
from argparse import ArgumentParser
|
||||
import pytorch_lightning as pl
|
||||
from typing import List
|
||||
import yaml
|
||||
import os
|
||||
|
||||
# utils
|
||||
from utils.init_utils import init_lit_model, init_data_module, init_main_callbacks, init_wandb_logger
|
||||
@@ -17,11 +19,16 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
datamodule: pl.LightningDataModule = init_data_module(hparams=run_config["dataset"])
|
||||
|
||||
# Init Weights&Biases logger
|
||||
logger: pl.loggers.WandbLogger = init_wandb_logger(project_config, run_config, lit_model, datamodule) \
|
||||
if use_wandb else None
|
||||
logger: pl.loggers.WandbLogger = init_wandb_logger(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
lit_model=lit_model,
|
||||
datamodule=datamodule,
|
||||
log_path=os.path.join(os.path.dirname(__file__), "logs/")
|
||||
) if use_wandb else None
|
||||
|
||||
# Init ModelCheckpoint and EarlyStopping callbacks
|
||||
callbacks: list = init_main_callbacks(project_config)
|
||||
callbacks: List[pl.Callback] = init_main_callbacks(project_config=project_config)
|
||||
|
||||
# Add custom callbacks from utils/callbacks.py
|
||||
callbacks.extend([
|
||||
@@ -30,10 +37,14 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
])
|
||||
if use_wandb:
|
||||
callbacks.append(
|
||||
SaveCodeToWandbCallback(wandb_save_dir=logger.save_dir, lit_model=lit_model, datamodule=datamodule),
|
||||
SaveCodeToWandbCallback(
|
||||
base_dir=os.path.dirname(__file__),
|
||||
wandb_save_dir=logger.save_dir,
|
||||
run_config=run_config
|
||||
),
|
||||
)
|
||||
|
||||
# Get path to checkpoint you want to resume with if it was set in run config
|
||||
# Get path to checkpoint you want to resume with if it was set in the run config
|
||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("checkpoint_path", None)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
@@ -59,22 +70,14 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
profiler=SimpleProfiler() if project_config["printing"]["profiler"] else None,
|
||||
weights_summary=project_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
|
||||
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),
|
||||
# number of validation sanity checks
|
||||
num_sanity_val_steps=3,
|
||||
|
||||
# default log dir if no logger is found
|
||||
default_root_dir="logs/lightning_logs",
|
||||
|
||||
# insert all other trainer parameters specified in run config
|
||||
**run_config["trainer"]
|
||||
)
|
||||
|
||||
# Evaluate model on test set before training
|
||||
@@ -87,7 +90,8 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
trainer.test()
|
||||
|
||||
|
||||
def load_config(path):
|
||||
def load_config(filename):
|
||||
path = os.path.join(os.path.dirname(__file__), filename)
|
||||
with open(path, "r") as ymlfile:
|
||||
config = yaml.load(ymlfile, Loader=yaml.FullLoader)
|
||||
return config
|
||||
@@ -104,8 +108,8 @@ def main(run_config_name: str, use_wandb: bool):
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("-r", "--run_conf_name", type=str, default="MNIST_CLASSIFIER_V1")
|
||||
parser.add_argument("-r", "--run_config", type=str, default="MNIST_CLASSIFIER_V1")
|
||||
parser.add_argument("-u", "--use_wandb", type=bool, default=True)
|
||||
args = parser.parse_args()
|
||||
|
||||
main(run_config_name=args.run_conf_name, use_wandb=args.use_wandb)
|
||||
main(run_config_name=args.run_config, use_wandb=args.use_wandb)
|
||||
+24
-19
@@ -26,11 +26,11 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
|
||||
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):
|
||||
def __init__(self, datamodule, wandb_save_dir):
|
||||
first_batch = next(iter(datamodule.train_dataloader()))
|
||||
x, y = first_batch
|
||||
self.dummy_input = x
|
||||
self.save_dir = save_dir
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
|
||||
def on_sanity_check_end(self, trainer, pl_module):
|
||||
self.save_onnx_model(pl_module)
|
||||
@@ -39,9 +39,9 @@ class SaveOnnxModelToWandbCallback(pl.Callback):
|
||||
self.save_onnx_model(pl_module)
|
||||
|
||||
def save_onnx_model(self, pl_module):
|
||||
file_path = os.path.join(self.save_dir, "model.onnx")
|
||||
file_path = os.path.join(self.wandb_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, base_path=self.save_dir)
|
||||
wandb.save(file_path, base_path=self.wandb_save_dir)
|
||||
|
||||
|
||||
class ImagePredictionLoggerCallback(pl.Callback):
|
||||
@@ -131,52 +131,57 @@ class SaveCodeToWandbCallback(pl.Callback):
|
||||
"""
|
||||
Upload specified code files to wandb at the beginning of the run.
|
||||
"""
|
||||
def __init__(self, wandb_save_dir, lit_model, datamodule):
|
||||
def __init__(self, base_dir, wandb_save_dir, run_config):
|
||||
self.base_dir = base_dir
|
||||
self.wandb_save_dir = wandb_save_dir
|
||||
self.additional_files_to_be_saved = [
|
||||
self.model_folder = run_config["model"]["model_folder"]
|
||||
self.datamodule_folder = run_config["dataset"]["datamodule_folder"]
|
||||
self.additional_files_to_be_saved = [ # paths should be relative to base_dir
|
||||
"utils/callbacks.py",
|
||||
"utils/init_utils.py",
|
||||
"train.py",
|
||||
"project_config.yaml",
|
||||
"run_configs.yaml",
|
||||
]
|
||||
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):
|
||||
"""Upload files when all validation sanity checks end."""
|
||||
# upload additional files
|
||||
for file in self.additional_files_to_be_saved:
|
||||
src_path = os.path.join(self.base_dir, file)
|
||||
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)
|
||||
copy(src_path, dst_path)
|
||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
||||
|
||||
for filename in os.listdir(self.model_path):
|
||||
# upload model files
|
||||
for filename in os.listdir(os.path.join(self.base_dir, "models", self.model_folder)):
|
||||
|
||||
if filename.endswith('.py'):
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "models", os.path.basename(self.model_path),
|
||||
filename)
|
||||
src_path = os.path.join(self.base_dir, "models", self.model_folder, filename)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "models", self.model_folder, filename)
|
||||
|
||||
path, filename = os.path.split(dst_path)
|
||||
if not os.path.exists(path):
|
||||
os.makedirs(path)
|
||||
|
||||
file_path = os.path.join(self.model_path, filename)
|
||||
copy(file_path, dst_path)
|
||||
copy(src_path, dst_path)
|
||||
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):
|
||||
# upload datamodule files
|
||||
for filename in os.listdir(os.path.join(self.base_dir, "data_modules", self.datamodule_folder)):
|
||||
|
||||
if filename.endswith('.py'):
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", os.path.basename(
|
||||
self.datamodule_path), filename)
|
||||
src_path = os.path.join(self.base_dir, "data_modules", self.datamodule_folder, filename)
|
||||
dst_path = os.path.join(self.wandb_save_dir, "code", "data_modules", self.datamodule_folder, 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)
|
||||
copy(src_path, dst_path)
|
||||
wandb.save(dst_path, base_path=self.wandb_save_dir) # this line is only to make upload immediate
|
||||
@@ -8,8 +8,8 @@ import train
|
||||
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]
|
||||
project_config = train.load_config("project_config.yaml")
|
||||
run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
|
||||
|
||||
# Initialize wandb
|
||||
wandb.init()
|
||||
@@ -27,4 +27,4 @@ for key, value in sweep_hparams.items():
|
||||
run_config["dataset"][key] = value
|
||||
|
||||
# Execute run
|
||||
train.train(project_config=project_config, run_config=run_config)
|
||||
train.train(project_config=project_config, run_config=run_config, use_wandb=True)
|
||||
+20
-16
@@ -1,6 +1,7 @@
|
||||
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
|
||||
from pytorch_lightning.loggers import WandbLogger
|
||||
import pytorch_lightning as pl
|
||||
from typing import List
|
||||
import importlib
|
||||
import os
|
||||
|
||||
@@ -21,36 +22,39 @@ def init_data_module(hparams: dict) -> pl.LightningDataModule:
|
||||
return datamodule
|
||||
|
||||
|
||||
def init_main_callbacks(project_config: dict) -> list:
|
||||
"""Initialize EarlyStopping callback and ModelCheckpoint callback."""
|
||||
def init_main_callbacks(project_config: dict) -> List[pl.Callback]:
|
||||
"""Initialize ModelCheckpoint and EarlyStopping callbacks."""
|
||||
callbacks = [
|
||||
EarlyStopping(
|
||||
monitor=project_config["callbacks"]["early_stop"]["monitor"],
|
||||
patience=project_config["callbacks"]["early_stop"]["patience"],
|
||||
mode=project_config["callbacks"]["early_stop"]["mode"],
|
||||
),
|
||||
ModelCheckpoint(
|
||||
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"],
|
||||
),
|
||||
EarlyStopping(
|
||||
monitor=project_config["callbacks"]["early_stop"]["monitor"],
|
||||
patience=project_config["callbacks"]["early_stop"]["patience"],
|
||||
mode=project_config["callbacks"]["early_stop"]["mode"],
|
||||
)
|
||||
]
|
||||
return callbacks
|
||||
|
||||
|
||||
def init_wandb_logger(
|
||||
config: dict, run_config: dict,
|
||||
lit_model: pl.LightningModule, datamodule: pl.LightningDataModule
|
||||
project_config: dict,
|
||||
run_config: dict,
|
||||
lit_model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
log_path: str = "logs/"
|
||||
) -> pl.loggers.WandbLogger:
|
||||
"""Initialize Weights&Biases logger."""
|
||||
resume_from_checkpoint = run_config.get("resume_training", {}).get("resume_from_checkpoint", None)
|
||||
wandb_run_id = run_config.get("resume_training", {}).get("wandb_run_id", None)
|
||||
wandb_logger = WandbLogger(
|
||||
project=config["loggers"]["wandb"]["project"],
|
||||
entity=config["loggers"]["wandb"]["entity"],
|
||||
log_model=config["loggers"]["wandb"]["log_model"],
|
||||
offline=config["loggers"]["wandb"]["offline"],
|
||||
project=project_config["loggers"]["wandb"]["project"],
|
||||
entity=project_config["loggers"]["wandb"]["entity"],
|
||||
log_model=project_config["loggers"]["wandb"]["log_model"],
|
||||
offline=project_config["loggers"]["wandb"]["offline"],
|
||||
|
||||
group=run_config.get("wandb", {}).get("group", None),
|
||||
job_type=run_config.get("wandb", {}).get("job_type", "train"),
|
||||
@@ -63,11 +67,11 @@ def init_wandb_logger(
|
||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
||||
else None,
|
||||
|
||||
save_dir="logs/",
|
||||
save_dir=log_path,
|
||||
save_code=False
|
||||
)
|
||||
if not os.path.exists("logs/"):
|
||||
os.mkdir("logs/")
|
||||
if not os.path.exists(log_path):
|
||||
os.makedirs(log_path)
|
||||
if hasattr(lit_model, 'model'):
|
||||
wandb_logger.watch(lit_model.model, log=None)
|
||||
else:
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
torch>=1.7.0
|
||||
torchvision>=0.8.1
|
||||
torchaudio>=0.7.0
|
||||
pytorch-lightning>=1.0.8
|
||||
pytorch-lightning-bolts>=0.2.5
|
||||
wandb>=0.10.11
|
||||
wandb>=0.10.12
|
||||
PyYAML>=5.3.1
|
||||
scikit-learn>=0.23.2
|
||||
Reference in new issue
Block a user