making progress with hydra
This commit is contained in:
1 parent
610117f161
commit
d24568e686
21 files changed
+142
-104
No files matched your search
@@ -5,19 +5,20 @@ defaults:
|
|||||||
- model: simple_mnist_classifier.yaml
|
- model: simple_mnist_classifier.yaml
|
||||||
- datamodule: mnist_datamodule.yaml
|
- datamodule: mnist_datamodule.yaml
|
||||||
- optimizer: adam.yaml
|
- optimizer: adam.yaml
|
||||||
- callbacks: default_callbacks.yaml
|
- seeds: default_seeds.yaml # set this to null if you don't want to use seeds
|
||||||
- loggers: null
|
- callbacks: default_callbacks.yaml # set this to null if you don't want to use callbacks
|
||||||
|
- logger: null # set logger here or use command line (e.g. `python train.py logger=wandb`)
|
||||||
|
|
||||||
seeds:
|
# path to working directory (the directory that `train.py` was executed from in command line)
|
||||||
pytorch_seed: 12345
|
work_dir: ${hydra:runtime.cwd}
|
||||||
|
|
||||||
paths:
|
# path to folder with data
|
||||||
data_dir: "data" # path to data folder (either absolute or relative to placement of 'train.py' file)
|
data_dir: ${work_dir}/data/
|
||||||
logs_dir: "logs" # path to logs folder (either absolute or relative to placement of 'train.py' file)
|
|
||||||
|
|
||||||
|
# hydra output paths
|
||||||
hydra:
|
hydra:
|
||||||
run:
|
run:
|
||||||
dir: ${paths.logs_dir}/hydra_logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
|
dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
|
||||||
sweep:
|
sweep:
|
||||||
dir: ${paths.logs_dir}/hydra_logs/sweeps/${now:%Y-%m-%d_%H-%M-%S}
|
dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S}
|
||||||
subdir: ${hydra.job.num}
|
subdir: ${hydra.job.num}
|
||||||
@@ -37,7 +37,7 @@ model:
|
|||||||
datamodule:
|
datamodule:
|
||||||
args: # you can add here any params you want and then access them in lightning datamodule
|
args: # you can add here any params you want and then access them in lightning datamodule
|
||||||
batch_size: 64
|
batch_size: 64
|
||||||
train_val_test_split: (55_000, 5_000, 10_000)
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
num_workers: 1 # num of processes used for loading data in parallel
|
num_workers: 1 # num of processes used for loading data in parallel
|
||||||
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
|
pin_memory: False # dataloaders will copy tensors into CUDA pinned memory before returning them
|
||||||
|
|
||||||
@@ -48,7 +48,7 @@ optimizer:
|
|||||||
|
|
||||||
loggers:
|
loggers:
|
||||||
wandb:
|
wandb:
|
||||||
args: # you can add here additional loggers arguments specific for this experiment
|
args: # you can add here additional logger arguments specific for this experiment
|
||||||
tags: ["uwu", "best_model"]
|
tags: ["uwu", "best_model"]
|
||||||
notes: ""
|
notes: ""
|
||||||
group: ""
|
group: ""
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ model:
|
|||||||
datamodule:
|
datamodule:
|
||||||
args:
|
args:
|
||||||
batch_size: 32
|
batch_size: 32
|
||||||
train_val_test_split: (55_000, 5_000, 10_000)
|
train_val_test_split: [55_000, 5_000, 10_000]
|
||||||
|
|
||||||
optimizer:
|
optimizer:
|
||||||
args:
|
args:
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
# Train with all logger at once
|
||||||
|
defaults:
|
||||||
|
- comet.yaml
|
||||||
|
- csv_logger.yaml
|
||||||
|
- tensorboard.yaml
|
||||||
|
- wandb.yaml
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
# Comet logger config
|
# Comet logger config
|
||||||
comet:
|
comet:
|
||||||
class: pytorch_lightning.loggers.CometLogger
|
class: pytorch_lightning.logger.CometLogger
|
||||||
args:
|
args:
|
||||||
api_key: ???
|
api_key: ???
|
||||||
project_name: "project_template_test"
|
project_name: "project_template_test"
|
||||||
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
# Csv logger config
|
# Csv logger config
|
||||||
csv_logger:
|
csv_logger:
|
||||||
class: pytorch_lightning.loggers.CSVLogger
|
class: pytorch_lightning.logger.CSVLogger
|
||||||
args: {}
|
args: {}
|
||||||
@@ -2,5 +2,5 @@
|
|||||||
|
|
||||||
# Tensorboard logger config
|
# Tensorboard logger config
|
||||||
tensorboard:
|
tensorboard:
|
||||||
class: pytorch_lightning.loggers.TensorboardLogger
|
class: pytorch_lightning.logger.TensorboardLogger
|
||||||
args: {}
|
args: {}
|
||||||
@@ -2,13 +2,13 @@
|
|||||||
|
|
||||||
# Weights&Biases logger config
|
# Weights&Biases logger config
|
||||||
wandb:
|
wandb:
|
||||||
class: pytorch_lightning.loggers.WandbLogger
|
class: pytorch_lightning.logger.WandbLogger
|
||||||
args:
|
args:
|
||||||
project: "project_template_test"
|
project: "project_template_test"
|
||||||
entity: "" # change to your username or name of your team on wandb
|
# entity: "your_team_name" # set to name of your team on wandb
|
||||||
offline: False # set True to store all logs only locally
|
offline: False # set True to store all logs only locally
|
||||||
job_type: "train"
|
job_type: "train"
|
||||||
save_dir: ${paths.logs_dir}
|
save_dir: "./"
|
||||||
|
|
||||||
# some extra things which will be logged by the environment
|
# some extra things which will be logged by the environment
|
||||||
extra_logs:
|
extra_logs:
|
||||||
@@ -17,10 +17,10 @@ wandb:
|
|||||||
|
|
||||||
log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset
|
log_train_val_test_sizes: True # log sizes of train dataset, val dataset and test dataset
|
||||||
|
|
||||||
log_model_args: True # log
|
log_model_args: True
|
||||||
log_datamodule_args: True # log
|
log_datamodule_args: True
|
||||||
log_optimizer_args: True # log
|
log_optimizer_args: True
|
||||||
log_trainer_args: False # log
|
log_trainer_args: False
|
||||||
|
|
||||||
log_model_class_name: True
|
log_model_class_name: True
|
||||||
log_datamodule_class_name: True
|
log_datamodule_class_name: True
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
# @package _group_
|
|
||||||
|
|
||||||
# Train with all loggers at once
|
|
||||||
defaults:
|
|
||||||
- comet
|
|
||||||
- csv_logger
|
|
||||||
- tensorboard
|
|
||||||
- wandb
|
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
# @package _group_
|
||||||
|
|
||||||
|
pytorch_seed: 12345
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
# trainer args for debugging model
|
# trainer args for debugging model
|
||||||
args:
|
args:
|
||||||
gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
gpus: -1 # set -1 to train on all GPUs abailable, set 0 to train on CPU only
|
||||||
auto_select_gpus: True
|
auto_select_gpus: True
|
||||||
|
|
||||||
fast_dev_run: True
|
fast_dev_run: True
|
||||||
@@ -13,5 +13,5 @@ args:
|
|||||||
profiler: "simple" # use profiler to print execution time profiling after training ends
|
profiler: "simple" # use profiler to print execution time profiling after training ends
|
||||||
|
|
||||||
progress_bar_refresh_rate: 10
|
progress_bar_refresh_rate: 10
|
||||||
weights_summary: "top"
|
weights_summary: "full"
|
||||||
default_root_dir: ${paths.logs_dir}/lightning_logs
|
default_root_dir: "lightning_logs/"
|
||||||
@@ -1,12 +1,11 @@
|
|||||||
# @package _group_
|
# @package _group_
|
||||||
|
|
||||||
# args passed to Lightning Trainer on every experiment
|
# default args passed to Lightning Trainer on every experiment
|
||||||
# they will be combined with trainer args specified in experiment config
|
# they can be combined or overwritten with args set in experiment config
|
||||||
# (if the argument repeats in experiment config, then it will override the one set here)
|
|
||||||
args:
|
args:
|
||||||
gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
gpus: -1 # set -1 to train on all GPUs available, set 0 to train on CPU only
|
||||||
auto_select_gpus: True
|
auto_select_gpus: True
|
||||||
num_sanity_val_steps: 3
|
num_sanity_val_steps: 3
|
||||||
weights_summary: "top"
|
|
||||||
progress_bar_refresh_rate: 10
|
progress_bar_refresh_rate: 10
|
||||||
default_root_dir: ${paths.logs_dir}/lightning_logs
|
weights_summary: null # null in yaml represents python None value
|
||||||
|
default_root_dir: "lightning_logs/"
|
||||||
@@ -18,7 +18,7 @@ class MNISTDataModule(LightningDataModule):
|
|||||||
def __init__(self, data_dir, **args):
|
def __init__(self, data_dir, **args):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
self.data_dir = data_dir + "/MNIST" # data_dir is specified in config.yaml
|
self.data_dir = data_dir # data_dir is specified in config.yaml
|
||||||
|
|
||||||
self.batch_size = args.get("batch_size") or 64
|
self.batch_size = args.get("batch_size") or 64
|
||||||
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
self.train_val_test_split = args.get("train_val_test_split") or [55_000, 5_000, 10_000]
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ def main(project_config_path, run_configs_path):
|
|||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = ArgumentParser()
|
parser = ArgumentParser()
|
||||||
parser.add_argument("-p", "--project_config_path", type=str,
|
parser.add_argument("-p", "--project_config_path", type=str,
|
||||||
default=os.path.join(train.BASE_DIR, "project_config.yaml"))
|
default=os.path.join(train.BASE_DIR, "config.yaml"))
|
||||||
parser.add_argument("-r", "--run_configs_path", type=str,
|
parser.add_argument("-r", "--run_configs_path", type=str,
|
||||||
default=os.path.join(train.BASE_DIR, "run_configs.yaml"))
|
default=os.path.join(train.BASE_DIR, "run_configs.yaml"))
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import train
|
|||||||
RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
|
RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
|
||||||
|
|
||||||
# Load configs
|
# Load configs
|
||||||
project_config = train.load_config("project_config.yaml")
|
project_config = train.load_config("config.yaml")
|
||||||
run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
|
run_config = train.load_config("run_configs.yaml")[RUN_CONFIG_NAME]
|
||||||
|
|
||||||
# Initialize wandb
|
# Initialize wandb
|
||||||
|
|||||||
Whitespace-only changes.
@@ -1,39 +1,24 @@
|
|||||||
# pytorch lightning imports
|
# pytorch lightning imports
|
||||||
import pytorch_lightning as pl
|
import pytorch_lightning as pl
|
||||||
|
|
||||||
# normal imports
|
|
||||||
from typing import List, Tuple
|
|
||||||
import importlib.util
|
|
||||||
import os
|
|
||||||
|
|
||||||
# template utils imports
|
|
||||||
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
||||||
import torch
|
import torch
|
||||||
|
|
||||||
|
# normal imports
|
||||||
def format_path(path: str, base_dir: str):
|
from typing import List, Tuple
|
||||||
"""Convert path to absolute relatively to base_dir and normalize it."""
|
import importlib
|
||||||
if not os.path.isabs(path):
|
import os
|
||||||
path = os.path.join(base_dir, path)
|
|
||||||
return os.path.normpath(path)
|
|
||||||
|
|
||||||
|
|
||||||
def format_config_paths(config: dict, base_dir: str) -> dict:
|
def load_class(class_path) -> type:
|
||||||
config["paths"]["data_dir"] = format_path(config["paths"]["data_dir"], base_dir)
|
class_path, obj_name = class_path.rsplit('.', 1)
|
||||||
config["paths"]["logs_dir"] = format_path(config["paths"]["logs_dir"], base_dir)
|
module = importlib.import_module(class_path)
|
||||||
return config
|
|
||||||
|
|
||||||
|
|
||||||
def load_object(obj_path):
|
|
||||||
obj_path, obj_name = obj_path.rsplit('.', 1)
|
|
||||||
module = importlib.import_module(obj_path)
|
|
||||||
assert hasattr(module, obj_name), \
|
assert hasattr(module, obj_name), \
|
||||||
f'Object `{obj_name}` cannot be loaded from `{obj_path}`.'
|
f'Object `{obj_name}` cannot be loaded from `{class_path}`.'
|
||||||
return getattr(module, obj_name)
|
return getattr(module, obj_name)
|
||||||
|
|
||||||
|
|
||||||
def init_object(obj_path, args):
|
def init_object(class_path, args) -> object:
|
||||||
return load_object(obj_path)(**args)
|
return load_class(class_path)(**args)
|
||||||
|
|
||||||
|
|
||||||
def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule:
|
def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule:
|
||||||
@@ -42,7 +27,7 @@ def init_model(model_config: dict, optimizer_config: dict) -> pl.LightningModule
|
|||||||
"""
|
"""
|
||||||
model_class = model_config["class"]
|
model_class = model_config["class"]
|
||||||
model_args = model_config["args"]
|
model_args = model_config["args"]
|
||||||
LitModel = load_object(model_class)
|
LitModel = load_class(model_class)
|
||||||
assert issubclass(LitModel, pl.LightningModule), \
|
assert issubclass(LitModel, pl.LightningModule), \
|
||||||
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
f"Specified model class `{model_class}` is not a subclass of `LightningModule`."
|
||||||
return LitModel(optimizer_config, **model_args)
|
return LitModel(optimizer_config, **model_args)
|
||||||
@@ -54,7 +39,7 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM
|
|||||||
"""
|
"""
|
||||||
datamodule_class = datamodule_config["class"]
|
datamodule_class = datamodule_config["class"]
|
||||||
datamodule_args = datamodule_config["args"]
|
datamodule_args = datamodule_config["args"]
|
||||||
DataModule = load_object(datamodule_class)
|
DataModule = load_class(datamodule_class)
|
||||||
assert issubclass(DataModule, pl.LightningDataModule), \
|
assert issubclass(DataModule, pl.LightningDataModule), \
|
||||||
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
f"Specified datamodule class `{datamodule_class}` is not a subclass of `LightningDataModule`"
|
||||||
datamodule = DataModule(data_dir=data_dir, **datamodule_args)
|
datamodule = DataModule(data_dir=data_dir, **datamodule_args)
|
||||||
@@ -66,9 +51,9 @@ def init_datamodule(datamodule_config: dict, data_dir: str) -> pl.LightningDataM
|
|||||||
def init_optimizer(optimizer_config, model):
|
def init_optimizer(optimizer_config, model):
|
||||||
optimizer_class = optimizer_config["class"]
|
optimizer_class = optimizer_config["class"]
|
||||||
optimizer_args = optimizer_config["args"]
|
optimizer_args = optimizer_config["args"]
|
||||||
Optim = load_object(optimizer_class)
|
Optim = load_class(optimizer_class)
|
||||||
assert issubclass(Optim, torch.optim.Optimizer), \
|
assert issubclass(Optim, torch.optim.Optimizer), \
|
||||||
f"Specified optimizer class `{optimizer_class}` is not a subclass of `torch.optim.Optimizer`."
|
f"Specified optimizer class `{optimizer_class}` is not subclass of `torch.optim.Optimizer`."
|
||||||
return Optim(model.parameters(), **optimizer_args)
|
return Optim(model.parameters(), **optimizer_args)
|
||||||
|
|
||||||
|
|
||||||
@@ -97,9 +82,11 @@ def init_callbacks(config: dict) -> List[pl.Callback]:
|
|||||||
return callbacks
|
return callbacks
|
||||||
|
|
||||||
for callback_name, callback_conf in callbacks_config.items():
|
for callback_name, callback_conf in callbacks_config.items():
|
||||||
callback_class = callback_conf.get("class", None)
|
class_path = callback_conf.get("class", None)
|
||||||
if callback_class:
|
if class_path:
|
||||||
callback_obj = init_object(callback_class, callback_conf.get("args", {}))
|
callback_obj = init_object(class_path=class_path, args=callback_conf.get("args", {}))
|
||||||
|
assert issubclass(callback_obj.__class__, pl.Callback), \
|
||||||
|
f"Specified callback class `{class_path}` is not a subclass of `pl.Callback`."
|
||||||
callbacks.append(callback_obj)
|
callbacks.append(callback_obj)
|
||||||
|
|
||||||
return callbacks
|
return callbacks
|
||||||
@@ -109,21 +96,23 @@ def init_loggers(config: dict,
|
|||||||
model: pl.LightningModule,
|
model: pl.LightningModule,
|
||||||
datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]:
|
datamodule: pl.LightningDataModule) -> List[pl.loggers.LightningLoggerBase]:
|
||||||
"""
|
"""
|
||||||
Initialize loggers specified in config.
|
Initialize logger specified in config.
|
||||||
"""
|
"""
|
||||||
loggers_config = config.get("loggers", None)
|
loggers_config = config.get("logger", None)
|
||||||
loggers = []
|
loggers = []
|
||||||
|
|
||||||
if not loggers_config:
|
if not loggers_config:
|
||||||
return loggers
|
return loggers
|
||||||
|
|
||||||
for logger_name, logger_conf in loggers_config.items():
|
for logger_name, logger_conf in loggers_config.items():
|
||||||
logger_class = loggers_config.get("class", None)
|
class_path = logger_conf.get("class", None)
|
||||||
if logger_class:
|
if class_path:
|
||||||
if logger_class == "pytorch_lightning.loggers.WandbLogger":
|
if class_path == "pytorch_lightning.logger.WandbLogger":
|
||||||
logger_obj = init_wandb(config, model, datamodule)
|
logger_obj = init_wandb(config, model, datamodule)
|
||||||
else:
|
else:
|
||||||
logger_obj = init_object(logger_class, logger_conf.get("args", {}))
|
logger_obj = init_object(class_path=class_path, args=logger_conf.get("args", {}))
|
||||||
|
assert issubclass(logger_obj.__class__, pl.loggers.LightningLoggerBase), \
|
||||||
|
f"Specified logger class `{class_path}` is not a subclass of `pl.loggers.LightningLoggerBase`."
|
||||||
loggers.append(logger_obj)
|
loggers.append(logger_obj)
|
||||||
|
|
||||||
return loggers
|
return loggers
|
||||||
@@ -139,7 +128,7 @@ def init_wandb(config: dict,
|
|||||||
# instead of auto-creating a new run
|
# instead of auto-creating a new run
|
||||||
os.environ["WANDB_RESUME"] = "must"
|
os.environ["WANDB_RESUME"] = "must"
|
||||||
|
|
||||||
wandb_config = config["loggers"]["wandb"]
|
wandb_config = config["logger"]["wandb"]
|
||||||
wandb_logger = WandbLogger(**wandb_config["args"])
|
wandb_logger = WandbLogger(**wandb_config["args"])
|
||||||
|
|
||||||
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
# make save dir path if it doesn't exists to prevent throwing errors by wandb
|
||||||
@@ -147,18 +136,18 @@ def init_wandb(config: dict,
|
|||||||
os.makedirs(wandb_config["args"]["save_dir"])
|
os.makedirs(wandb_config["args"]["save_dir"])
|
||||||
|
|
||||||
if hasattr(model, 'model'):
|
if hasattr(model, 'model'):
|
||||||
if wandb_config["extra_options"]["log_gradients"]:
|
if wandb_config["extra_logs"]["log_gradients"]:
|
||||||
wandb_logger.watch(model.model, log='gradients')
|
wandb_logger.watch(model.model, log='gradients')
|
||||||
else:
|
else:
|
||||||
wandb_logger.watch(model.model, log=None)
|
wandb_logger.watch(model.model, log=None)
|
||||||
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
wandb_logger.log_hyperparams({"architecture": model.model.__class__.__name__})
|
||||||
else:
|
else:
|
||||||
if wandb_config["extra_options"]["log_gradients"]:
|
if wandb_config["extra_logs"]["log_gradients"]:
|
||||||
wandb_logger.watch(model, log='gradients')
|
wandb_logger.watch(model, log='gradients')
|
||||||
else:
|
else:
|
||||||
wandb_logger.watch(model, log=None)
|
wandb_logger.watch(model, log=None)
|
||||||
|
|
||||||
if wandb_config["extra_options"]["log_train_val_test_sizes"]:
|
if wandb_config["extra_logs"]["log_train_val_test_sizes"]:
|
||||||
wandb_logger.log_hyperparams({
|
wandb_logger.log_hyperparams({
|
||||||
"train_size": len(datamodule.data_train)
|
"train_size": len(datamodule.data_train)
|
||||||
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
if hasattr(datamodule, 'data_train') and datamodule.data_train is not None else 0,
|
||||||
@@ -168,20 +157,30 @@ def init_wandb(config: dict,
|
|||||||
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
if hasattr(datamodule, 'data_test') and datamodule.data_test is not None else 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
if wandb_config["extra_options"]["log_model_args"]:
|
if wandb_config["extra_logs"]["log_model_args"]:
|
||||||
wandb_logger.log_hyperparams(config["model"]["args"])
|
wandb_logger.log_hyperparams(config["model"]["args"])
|
||||||
if wandb_config["extra_options"]["log_datamodule_args"]:
|
if wandb_config["extra_logs"]["log_datamodule_args"]:
|
||||||
wandb_logger.log_hyperparams(config["datamodule"]["args"])
|
wandb_logger.log_hyperparams(config["datamodule"]["args"])
|
||||||
if wandb_config["extra_options"]["log_optimizer_args"]:
|
if wandb_config["extra_logs"]["log_optimizer_args"]:
|
||||||
wandb_logger.log_hyperparams(config["optimizer"]["args"])
|
wandb_logger.log_hyperparams(config["optimizer"]["args"])
|
||||||
if wandb_config["extra_options"]["log_trainer_args"]:
|
if wandb_config["extra_logs"]["log_trainer_args"]:
|
||||||
wandb_logger.log_hyperparams(config["trainer"]["args"])
|
wandb_logger.log_hyperparams(config["trainer"]["args"])
|
||||||
|
|
||||||
if wandb_config["extra_options"]["log_model_class_name"]:
|
if wandb_config["extra_logs"]["log_model_class_name"]:
|
||||||
wandb_logger.log_hyperparams({"model_class": config["model"]["class"]})
|
wandb_logger.log_hyperparams({"model_class": config["model"]["class"]})
|
||||||
if wandb_config["extra_options"]["log_datamodule_class_name"]:
|
if wandb_config["extra_logs"]["log_datamodule_class_name"]:
|
||||||
wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]})
|
wandb_logger.log_hyperparams({"datamodule_class": config["datamodule"]["class"]})
|
||||||
if wandb_config["extra_options"]["log_optimizer_class_name"]:
|
if wandb_config["extra_logs"]["log_optimizer_class_name"]:
|
||||||
wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]})
|
wandb_logger.log_hyperparams({"optimizer_class": config["optimizer"]["class"]})
|
||||||
|
|
||||||
return wandb_logger
|
return wandb_logger
|
||||||
|
|
||||||
|
|
||||||
|
def validate_config(config: dict):
|
||||||
|
# TODO
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def validate_obj_config(obj_config: dict):
|
||||||
|
# TODO
|
||||||
|
pass
|
||||||
+21
-2
@@ -1,14 +1,33 @@
|
|||||||
|
import torch
|
||||||
|
import yaml
|
||||||
from omegaconf import DictConfig, OmegaConf
|
from omegaconf import DictConfig, OmegaConf
|
||||||
import hydra.conf.hydra.output
|
import hydra.conf.hydra.output
|
||||||
from hydra.experimental import initialize, compose
|
from hydra.experimental import initialize, compose
|
||||||
import comet_ml
|
import comet_ml
|
||||||
|
from pytorch_lightning.loggers import CSVLogger, WandbLogger, CometLogger, TestTubeLogger, TensorBoardLogger
|
||||||
|
import logging
|
||||||
|
|
||||||
|
|
||||||
@hydra.main(config_path="configs/", config_name="project_config.yaml")
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
def my_app(cfg: DictConfig) -> None:
|
def my_app(cfg: DictConfig) -> None:
|
||||||
|
# pass
|
||||||
# print(cfg)
|
# print(cfg)
|
||||||
print(OmegaConf.to_yaml(cfg))
|
log.info(OmegaConf.to_yaml(cfg, resolve=True))
|
||||||
|
|
||||||
|
|
||||||
|
def test_logger():
|
||||||
|
logger = WandbLogger()
|
||||||
|
print(logger)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
my_app()
|
my_app()
|
||||||
|
|
||||||
|
# with open("epoch=0.ckpt", "rb") as file:
|
||||||
|
# data = torch.load(file)
|
||||||
|
# print(data)
|
||||||
|
|
||||||
|
# test_logger()
|
||||||
+26
-10
@@ -6,15 +6,15 @@ import torch
|
|||||||
# hydra imports
|
# hydra imports
|
||||||
from omegaconf import DictConfig, OmegaConf
|
from omegaconf import DictConfig, OmegaConf
|
||||||
import hydra.conf.hydra.output
|
import hydra.conf.hydra.output
|
||||||
|
import hydra
|
||||||
|
|
||||||
# normal imports
|
# normal imports
|
||||||
from typing import List
|
from typing import List
|
||||||
import logging
|
import logging
|
||||||
import os
|
|
||||||
|
|
||||||
# template utils imports
|
# template utils imports
|
||||||
from template_utils.initializers import (
|
from template_utils.initializers import (
|
||||||
format_config_paths,
|
validate_config,
|
||||||
init_model,
|
init_model,
|
||||||
init_datamodule,
|
init_datamodule,
|
||||||
init_callbacks,
|
init_callbacks,
|
||||||
@@ -22,19 +22,16 @@ from template_utils.initializers import (
|
|||||||
init_trainer
|
init_trainer
|
||||||
)
|
)
|
||||||
|
|
||||||
BASE_DIR: str = os.path.dirname(__file__)
|
log = logging.getLogger(__name__)
|
||||||
LOG = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def train(config):
|
def train(config):
|
||||||
|
validate_config(config)
|
||||||
|
|
||||||
# Set global PyTorch seed
|
# Set global PyTorch seed
|
||||||
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||||
torch.manual_seed(config["seeds"]["pytorch_seed"])
|
torch.manual_seed(config["seeds"]["pytorch_seed"])
|
||||||
|
|
||||||
# Covert paths to absolute and normalize them
|
|
||||||
config = format_config_paths(config=config, base_dir=BASE_DIR)
|
|
||||||
|
|
||||||
# Init PyTorch Lightning model ⚡
|
# Init PyTorch Lightning model ⚡
|
||||||
model: pl.LightningModule = init_model(
|
model: pl.LightningModule = init_model(
|
||||||
model_config=config["model"],
|
model_config=config["model"],
|
||||||
@@ -44,19 +41,38 @@ def train(config):
|
|||||||
# Init PyTorch Lightning datamodule ⚡
|
# Init PyTorch Lightning datamodule ⚡
|
||||||
datamodule: pl.LightningDataModule = init_datamodule(
|
datamodule: pl.LightningDataModule = init_datamodule(
|
||||||
datamodule_config=config["datamodule"],
|
datamodule_config=config["datamodule"],
|
||||||
data_dir=config["paths"]["data_dir"]
|
data_dir=config["data_dir"]
|
||||||
)
|
)
|
||||||
|
|
||||||
# Init PyTorch Lightning callbacks ⚡
|
# Init PyTorch Lightning callbacks ⚡
|
||||||
callbacks: List[pl.Callback] = init_callbacks(config=config)
|
callbacks: List[pl.Callback] = init_callbacks(config=config)
|
||||||
|
|
||||||
# Init PyTorch Lightning loggers ⚡
|
# Init PyTorch Lightning logger ⚡
|
||||||
loggers: List[pl.loggers.LightningLoggerBase] = init_loggers(
|
loggers: List[pl.loggers.LightningLoggerBase] = init_loggers(
|
||||||
config=config,
|
config=config,
|
||||||
model=model,
|
model=model,
|
||||||
datamodule=datamodule
|
datamodule=datamodule
|
||||||
)
|
)
|
||||||
|
|
||||||
|
message = "Model initialised:" + "\n" + model.__module__ + "." + model.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Datamodule initialised:" + "\n" + datamodule.__module__ + "." + datamodule.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Callbacks initialised:" + "\n"
|
||||||
|
for cb in callbacks:
|
||||||
|
message += cb.__module__ + "." + cb.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
message = "Loggers initialised:" + "\n"
|
||||||
|
for logger in loggers:
|
||||||
|
message += logger.__module__ + "." + logger.__class__.__name__ + "\n"
|
||||||
|
log.info(message)
|
||||||
|
|
||||||
|
if "seeds" in config and "pytorch_seed" in config["seeds"]:
|
||||||
|
log.info(f"Using pytorch seed: {config['seeds']['pytorch_seed']}\n")
|
||||||
|
|
||||||
# Init PyTorch Lightning trainer ⚡
|
# Init PyTorch Lightning trainer ⚡
|
||||||
trainer: pl.Trainer = init_trainer(
|
trainer: pl.Trainer = init_trainer(
|
||||||
trainer_config=config["trainer"],
|
trainer_config=config["trainer"],
|
||||||
@@ -76,7 +92,7 @@ def train(config):
|
|||||||
|
|
||||||
@hydra.main(config_path="configs/", config_name="config.yaml")
|
@hydra.main(config_path="configs/", config_name="config.yaml")
|
||||||
def main(config: DictConfig) -> None:
|
def main(config: DictConfig) -> None:
|
||||||
LOG.info(OmegaConf.to_yaml(config, resolve=True)) # print content of config
|
log.info(f"\n{OmegaConf.to_yaml(config, resolve=True)}") # print content of config
|
||||||
train(config)
|
train(config)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,3 +6,4 @@ hydra-core
|
|||||||
wandb>=0.10.12
|
wandb>=0.10.12
|
||||||
scikit-learn>=0.23.2
|
scikit-learn>=0.23.2
|
||||||
pandas>=1.1.5
|
pandas>=1.1.5
|
||||||
|
hydra_colorlog
|
||||||
@@ -8,7 +8,7 @@ setup(
|
|||||||
description='Describe Your Cool Project',
|
description='Describe Your Cool Project',
|
||||||
author='',
|
author='',
|
||||||
author_email='',
|
author_email='',
|
||||||
url='https://github.com/kinoai/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
|
url='https://github.com/hobogalaxy/deep-learning-project-template', # REPLACE WITH YOUR OWN GITHUB PROJECT LINK
|
||||||
install_requires=['pytorch-lightning'],
|
install_requires=['pytorch-lightning', 'hydra-core'],
|
||||||
packages=find_packages(),
|
packages=find_packages(),
|
||||||
)
|
)
|
||||||
Reference in new issue
Block a user