everything except callbacks works
This commit is contained in:
1 parent
f46f380261
commit
757f0fc25a
7 files changed
+189
-148
No files matched your search
@@ -38,16 +38,16 @@ The directory structure of new project looks like this:
|
||||
│ │
|
||||
│ ├── data_modules <- All your data modules should be located here!
|
||||
│ │ ├── example_datamodule <- Each datamodule should be located in separate folder!
|
||||
│ │ │ ├── datamodule.py <- Contains 'DataModule' class
|
||||
│ │ │ ├── datasets.py <- Contains pytorch 'Dataset' classes (optional file)
|
||||
│ │ │ └── transforms.py <- Contains data transformations (optional file)
|
||||
│ │ │ ├── datamodule.py <- Contains class of type 'LightningDataModule'
|
||||
│ │ │ ├── datasets.py <- Optional file
|
||||
│ │ │ └── transforms.py <- Optional file
|
||||
│ │ ├── ...
|
||||
│ │ └── ...
|
||||
│ │
|
||||
│ ├── models <- All your models should be located here!
|
||||
│ │ ├── example_model <- Each model should be located in separate folder!
|
||||
│ │ │ ├── lightning_module.py <- Contains 'LitModel' class with train/val/test step methods
|
||||
│ │ │ └── models.py <- Model architectures used by lightning_module.py (optional file)
|
||||
│ │ │ ├── lightning_module.py <- Contains class of type 'LightningModule'
|
||||
│ │ │ └── models.py <- Model architectures used by 'LightningModule'
|
||||
│ │ ├── ...
|
||||
│ │ └── ...
|
||||
│ │
|
||||
@@ -68,23 +68,24 @@ The directory structure of new project looks like this:
|
||||
## Project config parameters ([project_config.yaml](project/project_config.yaml))
|
||||
Example project configuration:
|
||||
```yaml
|
||||
num_of_gpus: -1 <- '-1' to use all gpus available, '0' to train on cpu
|
||||
num_of_gpus: -1 <- '-1' to train on all GPUs available, '0' to train on CPU
|
||||
|
||||
loggers:
|
||||
wandb:
|
||||
project: "project_name" <- wandb project name
|
||||
entity: "some_name" <- wandb entity name
|
||||
log_model: True <- set True if you want to upload ckpts to wandb automatically
|
||||
log_gradients: False <- set True to log gradient histograms
|
||||
offline: False <- set True if you want to store all data locally
|
||||
|
||||
callbacks:
|
||||
checkpoint:
|
||||
monitor: "val_acc" <- name of the logged metric that determines when model is improving
|
||||
default_callbacks:
|
||||
ModelCheckpoint:
|
||||
monitor: "val_acc" <- name of the logged metric which determines when model is improving
|
||||
save_top_k: 1 <- save k best models (determined by above metric)
|
||||
save_last: True <- additionaly always save model from last epoch
|
||||
mode: "max" <- can be "max" or "min"
|
||||
early_stop:
|
||||
monitor: "val_acc" <- name of the logged metric that determines when model is improving
|
||||
EarlyStopping:
|
||||
monitor: "val_acc" <- name of the logged metric which determines when model is improving
|
||||
patience: 5 <- how many epochs of not improving until training stops
|
||||
mode: "max" <- can be "max" or "min"
|
||||
|
||||
@@ -100,55 +101,52 @@ printing:
|
||||
You can store many run configurations in this file.<br>
|
||||
Example run configuration:
|
||||
```yaml
|
||||
MNIST_CLASSIFIER_V1:
|
||||
trainer: # these parameters will be passed directly to PyTorch Lightning 'Trainer' object
|
||||
max_epochs: 5
|
||||
gradient_clip_val: 0.5
|
||||
accumulate_grad_batches: 1
|
||||
limit_train_batches: 1.0
|
||||
model: # these parameters will be passed to 'LightningModule' object as 'hparams' dictionary
|
||||
model_folder: "simple_mnist_classifier"
|
||||
lr: 0.001
|
||||
weight_decay: 0.000001
|
||||
input_size: 784
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
lin2_size: 256
|
||||
lin3_size: 128
|
||||
dataset: # these parameters will be passed to 'LightningDataModule' object as 'hparams' dictionary
|
||||
datamodule_folder: "mnist_datamodule"
|
||||
batch_size: 256
|
||||
train_val_split_ratio: 0.9
|
||||
num_workers: 1
|
||||
pin_memory: False
|
||||
callbacks:
|
||||
ConfusionMatrixLoggerCallback:
|
||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
wandb:
|
||||
group: ""
|
||||
tags: ["v1", "uwu"]
|
||||
resume_training:
|
||||
checkpoint_path: "path_to_checkpoint/last.ckpt"
|
||||
wandb_run_id: None
|
||||
SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
seed: 1234
|
||||
trainer:
|
||||
args:
|
||||
max_epochs: 10
|
||||
model:
|
||||
load_from:
|
||||
model_path: "models/simple_mnist_classifier/lightning_module.py"
|
||||
model_class: "LitModel"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
weight_decay: 0.00001
|
||||
input_size: 784
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
lin2_size: 256
|
||||
lin3_size: 128
|
||||
datamodule:
|
||||
load_from:
|
||||
datamodule_path: "datamodules/mnist_datamodule/datamodule.py"
|
||||
datamodule_class: "MNISTDataModule"
|
||||
hparams:
|
||||
batch_size: 64
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
```
|
||||
Each run configuration needs to contain sections `trainer`, `model` and `dataset`. Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.<br>
|
||||
To start training with this configuration run: `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST`
|
||||
|
||||
Section `model` always needs to contain `model_folder` parameter (name of the folder from which `lightning_module.py` will be loaded, which should contain `LitModel` class).<br>
|
||||
Section `dataset` always needs to contain `datamodule_folder` parameter (name of the folder from which `datamodule.py` will be loaded, which should contain `DataModule` class).<br>
|
||||
Each run configuration needs to contain sections `trainer`, `model` and `datamodule`. <br>
|
||||
Sections `callbacks`, `wandb` and `resume_training` are optional and can be removed.<br>
|
||||
|
||||
Every parameter in `model` section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).<br>
|
||||
Every parameter in `dataset` section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).<br>
|
||||
Every parameter specified in model hparams section will be passed to your model class and can be retrieved through `hparams` dictionary (see example with [simple_mnist_classifier](project/models/simple_mnist_classifier/lightning_module.py)).<br>
|
||||
Every parameter specified in datamodule hparams section will be passed to your datamodule class and can be retrieved through `hparams` dictionary (see example with [mnist_digits_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).<br>
|
||||
<br>
|
||||
|
||||
|
||||
## Workflow
|
||||
1. Add your model to `project/models` folder. You need to create folder with `lightning_module.py` file containing `LitModel` class
|
||||
2. Add your datamodule to `project/data_modules` folder. You need to create folder with `datamodule.py` file containing `DataModule` class
|
||||
3. Create new run config in [run_configs.yaml](project/run_configs.yaml) (specify there folders containing your model and datamodule)
|
||||
3. Configure [project_config.yaml](project/project_config.yaml)
|
||||
1. Create model in PyTorch Lightning
|
||||
2. Create datamodule in PyTorch Lightning
|
||||
3. Create new run config in [run_configs.yaml](project/run_configs.yaml)
|
||||
- specify path to your model class
|
||||
- specify path to your datamodule class
|
||||
- you can add there and hyperparametrs you want!
|
||||
3. Configure your project in [project_config.yaml](project/project_config.yaml)
|
||||
4. Run training with chosen run config<br>
|
||||
```bash
|
||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||
```
|
||||
<br><br>
|
||||
|
||||
@@ -192,7 +190,7 @@ Next, you can train model without logging
|
||||
# train model without Weights&Biases
|
||||
# choose run config from project/run_configs.yaml
|
||||
cd project
|
||||
python train.py --no_wandb --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --no_wandb --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||
```
|
||||
|
||||
Or you can train model with Weights&Biases logging
|
||||
@@ -207,10 +205,10 @@ loggers:
|
||||
# train model with Weights&Biases
|
||||
# choose run config from project/run_configs.yaml
|
||||
cd project
|
||||
python train.py --run_config MNIST_CLASSIFIER_V1
|
||||
python train.py --run_config SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||
```
|
||||
|
||||
Optionally you can install project as package with [setup.py](setup.py)
|
||||
Optionally you can install project as a package with [setup.py](setup.py)
|
||||
```bash
|
||||
pip install -e .
|
||||
```
|
||||
|
||||
@@ -5,8 +5,8 @@ import os
|
||||
|
||||
class TestDataset(Dataset):
|
||||
"""
|
||||
Example dataset class for loading images from folder.
|
||||
'Dataset' classes can be used by 'DataModule' class.
|
||||
Example dataset class for loading images from folder.
|
||||
'Dataset' classes can be used by 'DataModule' class.
|
||||
"""
|
||||
|
||||
def __init__(self, img_dir, transform):
|
||||
@@ -14,7 +14,8 @@ class TestDataset(Dataset):
|
||||
self.images = [os.path.join(img_dir, fname) for fname in os.listdir(img_dir)]
|
||||
|
||||
def __getitem__(self, idx):
|
||||
image = Image.open(self.images[idx]).convert("RGB")
|
||||
image = Image.open(self.images[idx]).convert("L") # convert to black and white
|
||||
# image = Image.open(self.images[idx]).convert("RGB")
|
||||
|
||||
if self.transform is not None:
|
||||
image = self.transform(image)
|
||||
|
||||
@@ -9,18 +9,16 @@ from models.simple_mnist_classifier.models import *
|
||||
|
||||
class LitModel(pl.LightningModule):
|
||||
"""
|
||||
This is example of lightning model for MNIST digits classification.
|
||||
All models should be located in separate folders with file named 'lightning_module.py' containing class which
|
||||
is always called 'LitModel'!
|
||||
This is example of lightning model for MNIST digits classification.
|
||||
|
||||
The folder name of model used during training should be specified in run config and all parameters from
|
||||
'model' section will be passed in 'hparams' dictionary.
|
||||
The path to model should be specified in your run config. (run_configs.yaml)
|
||||
The 'hparams' dict contains your hparams specified in run config! (run_configs.yaml)
|
||||
|
||||
This class enables you to specify what happens during training, validation and test step.
|
||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||
This class enables you to specify what happens during training, validation and test step.
|
||||
You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
|
||||
"""
|
||||
|
||||
def __init__(self, hparams=None):
|
||||
def __init__(self, hparams: dict = None):
|
||||
super().__init__()
|
||||
|
||||
if hparams:
|
||||
|
||||
+12
-11
@@ -4,11 +4,12 @@ num_of_gpus: 0
|
||||
|
||||
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
|
||||
loggers:
|
||||
Weights&Biases_config:
|
||||
wandb:
|
||||
project: "project_template_test"
|
||||
entity: "kino" # change to your username or name of your team on wandb
|
||||
log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
|
||||
offline: False # set True to store all logs only locally
|
||||
entity: "kino" # change to your username or name of your team on wandb
|
||||
log_model: True # set True to automatically upload model checkpoint to wandb cloud after training
|
||||
log_gradients: False # set True to log gradient histograms (avoid this for very big models)
|
||||
offline: False # set True to store all logs only locally
|
||||
|
||||
|
||||
# default callbacks initialised on every run/experiment
|
||||
@@ -18,14 +19,14 @@ loggers:
|
||||
# all of the callback parameters will be passed to it on initialization
|
||||
default_callbacks:
|
||||
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
|
||||
monitor: "val_acc",
|
||||
patience: 5,
|
||||
mode: "max",
|
||||
monitor: "val_acc"
|
||||
patience: 5
|
||||
mode: "max"
|
||||
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
|
||||
monitor: "val_acc",
|
||||
save_top_k: 1,
|
||||
save_last: True,
|
||||
mode: "max",
|
||||
monitor: "val_acc"
|
||||
save_top_k: 1
|
||||
save_last: True
|
||||
mode: "max"
|
||||
|
||||
|
||||
# configure things which are printed in terminal
|
||||
|
||||
+11
-11
@@ -1,4 +1,4 @@
|
||||
# execute this run like this:
|
||||
# to execute this run:
|
||||
# python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST
|
||||
SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
seed: 1234
|
||||
@@ -11,7 +11,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
model_class: "LitModel"
|
||||
hparams:
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
weight_decay: 0.00001
|
||||
input_size: 784
|
||||
output_size: 10
|
||||
lin1_size: 256
|
||||
@@ -26,7 +26,7 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
|
||||
train_val_test_split: [55_000, 5_000, 10_000]
|
||||
|
||||
|
||||
# execute this run like this:
|
||||
# to execute this run:
|
||||
# python train.py --run_config_name ADVANCED_CONFIG_EXAMPLE_MNIST
|
||||
ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
seed: 1234
|
||||
@@ -47,7 +47,7 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
model_class: "LitModel"
|
||||
hparams: # you can add here any parameters you want and then read them in model!
|
||||
lr: 0.001
|
||||
weight_decay: 1e-5
|
||||
weight_decay: 0.00001
|
||||
input_size: 784 # img size is 1*28*28
|
||||
output_size: 10 # there are 10 digit classes
|
||||
lin1_size: 256
|
||||
@@ -70,14 +70,14 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
|
||||
notes: "This is example run."
|
||||
callbacks: # you can add here any callback class available in PyTorch Lightning or template_utils/callbacks.py
|
||||
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
|
||||
monitor: "val_acc",
|
||||
patience: 5,
|
||||
mode: "max",
|
||||
monitor: "val_acc"
|
||||
patience: 5
|
||||
mode: "max"
|
||||
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
|
||||
monitor: "val_acc",
|
||||
save_top_k: 1,
|
||||
save_last: True,
|
||||
mode: "max",
|
||||
monitor: "val_acc"
|
||||
save_top_k: 1
|
||||
save_last: True
|
||||
mode: "max"
|
||||
ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py
|
||||
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
|
||||
resume_training:
|
||||
|
||||
@@ -4,15 +4,40 @@ from pytorch_lightning.profiler import SimpleProfiler
|
||||
import pytorch_lightning as pl
|
||||
|
||||
# normal imports
|
||||
from typing import List
|
||||
from typing import List, Tuple
|
||||
import importlib.util
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
import template_utils.callbacks
|
||||
from template_utils import callbacks as custom_callbacks
|
||||
from template_utils import wandb_callbacks
|
||||
|
||||
|
||||
def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
def normalize_config_paths(project_config: dict, run_config: dict, base_dir: str) -> Tuple[dict, dict]:
|
||||
"""
|
||||
Convert all config paths to absolute paths relatively to base_dir and normalize them.
|
||||
"""
|
||||
|
||||
if not os.path.isabs(project_config["data_dir"]):
|
||||
project_config["data_dir"] = \
|
||||
os.path.normpath(os.path.join(base_dir, project_config["data_dir"]))
|
||||
|
||||
if not os.path.isabs(project_config["logs_dir"]):
|
||||
project_config["logs_dir"] =\
|
||||
os.path.normpath(os.path.join(base_dir, project_config["logs_dir"]))
|
||||
|
||||
if not os.path.isabs(run_config["model"]["load_from"]["model_path"]):
|
||||
run_config["model"]["load_from"]["model_path"] = \
|
||||
os.path.normpath(os.path.join(base_dir, run_config["model"]["load_from"]["model_path"]))
|
||||
|
||||
if not os.path.isabs(run_config["datamodule"]["load_from"]["datamodule_path"]):
|
||||
run_config["datamodule"]["load_from"]["datamodule_path"] = \
|
||||
os.path.normpath(os.path.join(base_dir, run_config["datamodule"]["load_from"]["datamodule_path"]))
|
||||
|
||||
return project_config, run_config
|
||||
|
||||
|
||||
def init_model(model_config: dict) -> pl.LightningModule:
|
||||
"""
|
||||
Load LightningModule from path specified in run config.
|
||||
"""
|
||||
@@ -20,9 +45,6 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
model_path = model_config["load_from"]["model_path"]
|
||||
model_class = model_config["load_from"]["model_class"]
|
||||
|
||||
if not os.path.isabs(model_path):
|
||||
model_path = os.path.join(base_dir, model_path)
|
||||
|
||||
assert os.path.isfile(model_path), f"incorrect model path: {model_path}"
|
||||
|
||||
spec = importlib.util.spec_from_file_location("lightning_model", model_path)
|
||||
@@ -42,7 +64,7 @@ def init_model(model_config: dict, base_dir: str) -> pl.LightningModule:
|
||||
return model
|
||||
|
||||
|
||||
def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl.LightningDataModule:
|
||||
def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataModule:
|
||||
"""
|
||||
Load LightningDataModule from path specified in run config.
|
||||
"""
|
||||
@@ -50,13 +72,8 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl
|
||||
datamodule_path = datamodule_config["load_from"]["datamodule_path"]
|
||||
datamodule_class = datamodule_config["load_from"]["datamodule_class"]
|
||||
|
||||
if not os.path.isabs(datamodule_path):
|
||||
datamodule_path = os.path.join(base_dir, datamodule_path)
|
||||
assert os.path.isfile(datamodule_path), f"incorrect model path: {datamodule_path}"
|
||||
|
||||
if not os.path.isabs(data_dir):
|
||||
data_dir = os.path.join(base_dir, data_dir)
|
||||
|
||||
spec = importlib.util.spec_from_file_location("lightning_model", datamodule_path)
|
||||
lightning_module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(lightning_module)
|
||||
@@ -79,8 +96,7 @@ def init_datamodule(datamodule_config: dict, data_dir: str, base_dir: str) -> pl
|
||||
def init_trainer(project_config: dict,
|
||||
run_config: dict,
|
||||
callbacks: List[pl.Callback],
|
||||
loggers: List[pl.loggers.LightningLoggerBase],
|
||||
base_dir: str) -> pl.Trainer:
|
||||
loggers: List[pl.loggers.LightningLoggerBase]) -> pl.Trainer:
|
||||
"""
|
||||
Initialize PyTorch Lightning Trainer.
|
||||
"""
|
||||
@@ -125,8 +141,7 @@ def init_trainer(project_config: dict,
|
||||
|
||||
def init_callbacks(project_config: dict,
|
||||
run_config: dict,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.Callback]:
|
||||
use_wandb: bool) -> List[pl.Callback]:
|
||||
"""
|
||||
Initialize default callbacks and callbacks specified in run config.
|
||||
"""
|
||||
@@ -134,26 +149,26 @@ def init_callbacks(project_config: dict,
|
||||
default_callbacks = project_config.get("default_callbacks", {})
|
||||
run_callbacks = run_config.get("callbacks", {})
|
||||
|
||||
print(default_callbacks)
|
||||
# print(default_callbacks)
|
||||
|
||||
callbacks = []
|
||||
|
||||
for callback_config in default_callbacks:
|
||||
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
callbacks.append(callback_class(**callback_config["args"]))
|
||||
|
||||
for callback_config in run_callbacks:
|
||||
callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
callbacks.append(callback_class(**callback_config["args"]))
|
||||
|
||||
if use_wandb:
|
||||
callbacks.append(
|
||||
template_utils.callbacks.SaveCodeToWandbCallback(
|
||||
base_dir=os.path.dirname(os.path.dirname(__file__)),
|
||||
wandb_save_dir=os.path.join(os.path.dirname(os.path.dirname(__file__)), "logs"),
|
||||
run_config=run_config
|
||||
)
|
||||
)
|
||||
# for callback_config in default_callbacks:
|
||||
# callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
# callbacks.append(callback_class(**callback_config["args"]))
|
||||
#
|
||||
# for callback_config in run_callbacks:
|
||||
# callback_class = getattr(pl.callbacks, callback_config["callback_class"])
|
||||
# callbacks.append(callback_class(**callback_config["args"]))
|
||||
#
|
||||
# if use_wandb:
|
||||
# callbacks.append(
|
||||
# wandb_callbacks.SaveCodeToWandbCallback(
|
||||
# base_dir=os.path.dirname(os.path.dirname(__file__)),
|
||||
# wandb_save_dir=project_config["logs_dir"],
|
||||
# run_config=run_config
|
||||
# )
|
||||
# )
|
||||
|
||||
return callbacks
|
||||
|
||||
@@ -162,24 +177,35 @@ def init_loggers(project_config: dict,
|
||||
run_config: dict,
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
use_wandb: bool,
|
||||
base_dir: str) -> List[pl.loggers.LightningLoggerBase]:
|
||||
use_wandb: bool) -> List[pl.loggers.LightningLoggerBase]:
|
||||
"""
|
||||
Initialize loggers.
|
||||
"""
|
||||
loggers = []
|
||||
if use_wandb:
|
||||
wandb_logger = init_wandb_logger(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
model=model,
|
||||
datamodule=datamodule
|
||||
)
|
||||
if wandb_logger:
|
||||
loggers.append(wandb_logger)
|
||||
|
||||
return []
|
||||
return loggers
|
||||
|
||||
|
||||
def init_wandb_logger(project_config: dict,
|
||||
run_config: dict,
|
||||
lit_model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule,
|
||||
log_path: str = "logs/") -> pl.loggers.WandbLogger:
|
||||
model: pl.LightningModule,
|
||||
datamodule: pl.LightningDataModule) -> pl.loggers.WandbLogger:
|
||||
"""
|
||||
Initialize Weights&Biases logger.
|
||||
"""
|
||||
|
||||
if "loggers" not in project_config or "wandb" not in project_config["loggers"]:
|
||||
return None
|
||||
|
||||
# with this line wandb will throw an error if the run to be resumed does not exist yet
|
||||
# instead of auto-creating a new run
|
||||
os.environ["WANDB_RESUME"] = "must"
|
||||
@@ -204,21 +230,27 @@ def init_wandb_logger(project_config: dict,
|
||||
and resume_from_checkpoint is not False and wandb_run_id is not False
|
||||
else None,
|
||||
|
||||
save_dir=log_path,
|
||||
save_dir=project_config["logs_dir"],
|
||||
save_code=False
|
||||
)
|
||||
|
||||
if not os.path.exists(log_path):
|
||||
os.makedirs(log_path)
|
||||
if not os.path.exists(project_config["logs_dir"]):
|
||||
os.makedirs(project_config["logs_dir"])
|
||||
|
||||
if hasattr(lit_model, 'model'):
|
||||
wandb_logger.watch(lit_model.model, log=None)
|
||||
wandb_logger.log_hyperparams({"model": lit_model.model.__class__.__name__})
|
||||
if hasattr(model, 'model'):
|
||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
||||
wandb_logger.watch(model.model, log='gradients')
|
||||
else:
|
||||
wandb_logger.watch(model.model, log=None)
|
||||
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
||||
else:
|
||||
wandb_logger.watch(lit_model, log=None)
|
||||
if project_config["loggers"]["wandb"]["log_gradients"]:
|
||||
wandb_logger.watch(model, log='gradients')
|
||||
else:
|
||||
wandb_logger.watch(model, log=None)
|
||||
|
||||
wandb_logger.log_hyperparams({
|
||||
"optimizer": lit_model.configure_optimizers().__class__.__name__,
|
||||
"optimizer": model.configure_optimizers().__class__.__name__,
|
||||
"train_size": len(datamodule.data_train)
|
||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||
"val_size": len(datamodule.data_val)
|
||||
@@ -226,9 +258,12 @@ def init_wandb_logger(project_config: dict,
|
||||
"test_size": len(datamodule.data_test)
|
||||
if hasattr(datamodule, 'data_test') and datamodule.data_test 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"])
|
||||
wandb_logger.log_hyperparams(project_config["num_of_gpus"])
|
||||
wandb_logger.log_hyperparams(run_config["trainer"]["args"])
|
||||
wandb_logger.log_hyperparams(run_config["model"]["hparams"])
|
||||
wandb_logger.log_hyperparams(run_config["model"]["load_from"])
|
||||
wandb_logger.log_hyperparams(run_config["datamodule"]["hparams"])
|
||||
wandb_logger.log_hyperparams(run_config["datamodule"]["load_from"])
|
||||
|
||||
return wandb_logger
|
||||
|
||||
|
||||
+19
-11
@@ -1,16 +1,18 @@
|
||||
# pytorch lightning imports
|
||||
import torch
|
||||
from pytorch_lightning import Trainer, LightningModule, LightningDataModule, Callback
|
||||
from pytorch_lightning.loggers import LightningLoggerBase
|
||||
import torch
|
||||
|
||||
# normal imports
|
||||
from argparse import ArgumentParser
|
||||
from typing import List
|
||||
import pprint
|
||||
import yaml
|
||||
import os
|
||||
|
||||
# template utils imports
|
||||
from template_utils.initializers import (
|
||||
normalize_config_paths,
|
||||
init_model,
|
||||
init_datamodule,
|
||||
init_callbacks,
|
||||
@@ -29,25 +31,29 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
if "seed" in run_config:
|
||||
torch.manual_seed(run_config["seed"])
|
||||
|
||||
# Covert paths to absolute and normalize them
|
||||
project_config, run_config = normalize_config_paths(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
base_dir=BASE_DIR
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning model ⚡
|
||||
model: LightningModule = init_model(
|
||||
model_config=run_config["model"],
|
||||
base_dir=BASE_DIR
|
||||
model_config=run_config["model"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning datamodule ⚡
|
||||
datamodule: LightningDataModule = init_datamodule(
|
||||
datamodule_config=run_config["datamodule"],
|
||||
data_dir=project_config["data_dir"],
|
||||
base_dir=BASE_DIR
|
||||
data_dir=project_config["data_dir"]
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning callbacks ⚡
|
||||
callbacks: List[Callback] = init_callbacks(
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
use_wandb=use_wandb,
|
||||
base_dir=BASE_DIR
|
||||
use_wandb=use_wandb
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning loggers ⚡
|
||||
@@ -56,8 +62,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
run_config=run_config,
|
||||
model=model,
|
||||
datamodule=datamodule,
|
||||
use_wandb=use_wandb,
|
||||
base_dir=BASE_DIR
|
||||
use_wandb=use_wandb
|
||||
)
|
||||
|
||||
# Init PyTorch Lightning trainer ⚡
|
||||
@@ -65,8 +70,7 @@ def train(project_config: dict, run_config: dict, use_wandb: bool):
|
||||
project_config=project_config,
|
||||
run_config=run_config,
|
||||
callbacks=callbacks,
|
||||
loggers=loggers,
|
||||
base_dir=BASE_DIR
|
||||
loggers=loggers
|
||||
)
|
||||
|
||||
# Evaluate model on test set before training
|
||||
@@ -91,6 +95,10 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str,
|
||||
project_config: dict = load_config(path=project_config_path)
|
||||
run_config: dict = load_config(path=run_configs_path)[run_config_name]
|
||||
|
||||
print("EXECUTING RUN:", run_config_name)
|
||||
pprint.pprint(run_config, sort_dicts=False)
|
||||
print()
|
||||
|
||||
# Train model
|
||||
train(project_config=project_config, run_config=run_config, use_wandb=use_wandb)
|
||||
|
||||
|
||||
Reference in new issue
Block a user