* fix code formatting

* add module init logging

* general improvements
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-03-06 19:43:48 +01:00
1 parent caa566dfd8
commit b45d3b31ec
9 files changed
+197 -133

No files matched your search

+7 -7
View File
@@ -4,21 +4,21 @@ default_language_version:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
# supported hooks: https://pre-commit.com/hooks.html
hooks:
# list of supported hooks: https://pre-commit.com/hooks.html
- id: end-of-file-fixer
- id: trailing-whitespace
- id: double-quote-string-fixer
- id: debug-statements
- id: detect-private-key
- id: check-yaml
- id: check-added-large-files
# - id: check-merge-conflict
- id: check-merge-conflict
# - repo: https://github.com/psf/black
# rev: 20.8b1
# hooks:
# - id: black
- repo: https://github.com/psf/black
rev: 20.8b1
hooks:
- id: black
# args: [--force-exclude, train.py]
# - repo: https://github.com/PyCQA/isort
# rev: 5.7.0
+1 -1
View File
@@ -25,7 +25,7 @@ val_check_interval: 0.5
# val_check_interval: 100
# run for 1 train, 1 val and 1 test batch
# fast_dev_run: True
fast_dev_run: False
# use only 20% of the data
limit_train_batches: 0.2
+2 -1
View File
@@ -4,6 +4,7 @@ min_epochs: 1
max_epochs: 10
gradient_clip_val: 0.5
num_sanity_val_steps: 2
progress_bar_refresh_rate: 20
progress_bar_refresh_rate: 10
weights_summary: null
default_root_dir: "lightning_logs/"
fast_dev_run: False
+1 -1
View File
@@ -22,7 +22,7 @@ def get_wandb_logger(trainer: pl.Trainer) -> WandbLogger:
if not logger:
raise Exception(
"You're using wandb related callback, "
"You are using wandb related callback,"
"but WandbLogger was not found for some reason..."
)
+79 -40
View File
@@ -4,6 +4,7 @@ import pytorch_lightning as pl
# hydra imports
from omegaconf import DictConfig, OmegaConf
from hydra.utils import get_original_cwd, to_absolute_path
from hydra.utils import log
# logger imports
import wandb
@@ -21,6 +22,44 @@ from rich import print
# normal imports
from typing import List
import warnings
import logging
def extras(config: DictConfig):
"""A couple of optional utilities, controlled with variables in main config file.
Simply delete those if you don' want them.
Args:
config (DictConfig): [description]
"""
# [OPTIONAL] Disable python warnings if <disable_warnings=True>
if config.get("disable_warnings"):
log.info(f"Disabling python warnings! <{config.disable_warnings=}>")
warnings.filterwarnings("ignore")
# [OPTIONAL] Disable Lightning logs if <disable_lightning_logs=True>
if config.get("disable_lightning_logs"):
log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>")
logging.getLogger("lightning").setLevel(logging.ERROR)
# [OPTIONAL] Force debugger friendly configuration if <trainer.fast_dev_run=True>
if config.trainer.get("fast_dev_run"):
log.info(
f"Forcing debugger friendly configuration! "
f"<{config.trainer.fast_dev_run=}>"
)
# Debuggers don't like GPUs or multiprocessing
if config.trainer.get("gpus"):
config.trainer.gpus = 0
if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0
# [OPTIONAL] Pretty print config using Rich library if <print_config=True>
if config.get("print_config"):
log.info(f"Pretty printing config with Rich! <{config.print_config=}>")
print_config(config)
def print_config(config: DictConfig):
@@ -34,41 +73,41 @@ def print_config(config: DictConfig):
# directory = to_absolute_path("configs/config.yaml")
# print(f"Main config path: [link file://{directory}]{directory}")
style = 'dim'
style = "dim"
tree = Tree(f':gear: HYDRA CONFIG', style=style, guide_style=style)
tree = Tree(f":gear: TRAINING CONFIG", style=style, guide_style=style)
trainer = OmegaConf.to_yaml(config['trainer'], resolve=True)
trainer_branch = tree.add('Trainer', style=style, guide_style=style)
trainer_branch.add(Syntax(trainer, 'yaml'))
trainer = OmegaConf.to_yaml(config["trainer"], resolve=True)
trainer_branch = tree.add("Trainer", style=style, guide_style=style)
trainer_branch.add(Syntax(trainer, "yaml"))
model = OmegaConf.to_yaml(config['model'], resolve=True)
model_branch = tree.add('Model', style=style, guide_style=style)
model_branch.add(Syntax(model, 'yaml'))
model = OmegaConf.to_yaml(config["model"], resolve=True)
model_branch = tree.add("Model", style=style, guide_style=style)
model_branch.add(Syntax(model, "yaml"))
datamodule = OmegaConf.to_yaml(config['datamodule'], resolve=True)
datamodule_branch = tree.add('Datamodule', style=style, guide_style=style)
datamodule_branch.add(Syntax(datamodule, 'yaml'))
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=True)
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style)
datamodule_branch.add(Syntax(datamodule, "yaml"))
callbacks_branch = tree.add('Callbacks', style=style, guide_style=style)
if 'callbacks' in config:
for cb_name, cb_conf in config['callbacks'].items():
callbacks_branch = tree.add("Callbacks", style=style, guide_style=style)
if "callbacks" in config:
for cb_name, cb_conf in config["callbacks"].items():
cb = callbacks_branch.add(cb_name, style=style, guide_style=style)
cb.add(Syntax(OmegaConf.to_yaml(cb_conf, resolve=True), 'yaml'))
cb.add(Syntax(OmegaConf.to_yaml(cb_conf, resolve=True), "yaml"))
else:
callbacks_branch.add('None')
callbacks_branch.add("None")
logger_branch = tree.add('Logger', style=style, guide_style=style)
if 'logger' in config:
for lg_name, lg_conf in config['logger'].items():
logger_branch = tree.add("Logger", style=style, guide_style=style)
if "logger" in config:
for lg_name, lg_conf in config["logger"].items():
lg = logger_branch.add(lg_name, style=style, guide_style=style)
lg.add(Syntax(OmegaConf.to_yaml(lg_conf, resolve=True), 'yaml'))
lg.add(Syntax(OmegaConf.to_yaml(lg_conf, resolve=True), "yaml"))
else:
logger_branch.add('None')
logger_branch.add("None")
seed = config.get('seed', 'None')
seed_branch = tree.add(f'Seed', style=style, guide_style=style)
seed_branch.add(str(seed) + '\n')
seed = config.get("seed", "None")
seed_branch = tree.add(f"Seed", style=style, guide_style=style)
seed_branch.add(str(seed) + "\n")
print(tree)
@@ -95,32 +134,32 @@ def log_hparams_to_all_loggers(
hparams = {}
# save all params of model, datamodule and trainer
hparams.update(config['model'])
hparams.update(config['datamodule'])
hparams.update(config['trainer'])
hparams.pop('_target_')
hparams.update(config["model"])
hparams.update(config["datamodule"])
hparams.update(config["trainer"])
hparams.pop("_target_")
# save seed
hparams['seed'] = config.get('seed', 'None')
hparams["seed"] = config.get("seed", "None")
# save targets
hparams['_class_model'] = config['model']['_target_']
hparams['_class_datamodule'] = config['datamodule']['_target_']
hparams["_class_model"] = config["model"]["_target_"]
hparams["_class_datamodule"] = config["datamodule"]["_target_"]
# save sizes of each dataset
if hasattr(datamodule, 'data_train') and datamodule.data_train:
hparams['train_size'] = len(datamodule.data_train)
if hasattr(datamodule, 'data_val') and datamodule.data_val:
hparams['val_size'] = len(datamodule.data_val)
if hasattr(datamodule, 'data_test') and datamodule.data_test:
hparams['test_size'] = len(datamodule.data_test)
if hasattr(datamodule, "data_train") and datamodule.data_train:
hparams["train_size"] = len(datamodule.data_train)
if hasattr(datamodule, "data_val") and datamodule.data_val:
hparams["val_size"] = len(datamodule.data_val)
if hasattr(datamodule, "data_test") and datamodule.data_test:
hparams["test_size"] = len(datamodule.data_test)
# save number of model parameters
hparams['#params_total'] = sum(p.numel() for p in model.parameters())
hparams['#params_trainable'] = sum(
hparams["#params_total"] = sum(p.numel() for p in model.parameters())
hparams["#params_trainable"] = sum(
p.numel() for p in model.parameters() if p.requires_grad
)
hparams['#params_not_trainable'] = sum(
hparams["#params_not_trainable"] = sum(
p.numel() for p in model.parameters() if not p.requires_grad
)
+33
View File
@@ -0,0 +1,33 @@
# !/bin/bash
# Quick tests for gpu
# To execute:
# bash tests/gpu_tests.sh
# Method for printing test name
echo() {
termwidth="$(tput cols)"
padding="$(printf '%0.1s' ={1..500})"
printf '\e[33m%*.*s %s %*.*s\n\e[0m' 0 "$(((termwidth-2-${#1})/2))" "$padding" "$1" 0 "$(((termwidth-1-${#1})/2))" "$padding"
}
# Make python hide warnings
export PYTHONWARNINGS="ignore"
echo "TEST 1"
echo "Train on GPU (2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
print_config=false
echo "TEST 2"
echo "Train with 4 workers and cuda pinned memory (2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
datamodule.num_workers=4 datamodule.pin_memory=True \
print_config=false
echo "TEST 3"
echo "Train with mixed-precision (apex, 2 epochs)"
python train.py trainer.gpus=-1 trainer.max_epochs=2 \
+trainer.amp_backend='apex' +trainer.amp_level='O2' \
print_config=false
+28 -45
View File
@@ -15,83 +15,66 @@ echo() {
export PYTHONWARNINGS="ignore"
# Test fast_dev_run (runs for 1 train, 1 val and 1 test batch)
echo "TEST 1"
python train.py +trainer.fast_dev_run=True \
echo "fast_dev_run=true (run 1 train, val and test loop using 1 batch)"
python train.py trainer.fast_dev_run=True \
print_config=false
# Overfit to 10 bathes
echo "TEST 2"
echo "Overfit to 10 bathes"
python train.py +trainer.overfit_batches=10 \
trainer.min_epochs=20 trainer.max_epochs=20 \
trainer.min_epochs=10 trainer.max_epochs=10 \
print_config=false
# Test 1 epoch on CPU
echo "TEST 3"
echo "Train 1 epoch on CPU"
python train.py trainer.gpus=0 trainer.max_epochs=1 \
print_config=false
# Test 1 epoch on GPU
echo "TEST 4"
python train.py trainer.gpus=1 trainer.max_epochs=1 \
print_config=false
# Test on 25% of data
echo "TEST 5"
echo "Train on 25% of data"
python train.py trainer.max_epochs=1 \
+trainer.limit_train_batches=0.25 +trainer.limit_val_batches=0.25 +trainer.limit_test_batches=0.25 \
print_config=false
# Test on 15 train batches, 10 val batches, 5 test batches
echo "TEST 6"
echo "TEST 5"
echo "Train on 15 train batches, 10 val batches, 5 test batches"
python train.py trainer.max_epochs=1 \
+trainer.limit_train_batches=15 +trainer.limit_val_batches=10 +trainer.limit_test_batches=5 \
print_config=false
# Test all experiment configs
echo "TEST 6"
echo "Run all experiment configs for 2 epochs"
python train.py -m '+experiment=glob(*)' trainer.max_epochs=2 \
print_config=false
echo "TEST 7"
python train.py -m '+experiment=glob(*)' trainer.gpus=1 trainer.max_epochs=2 \
print_config=false
# Test default hydra sweep over hyperparameters (runs 4 different combinations with fast_dev_run)
echo "TEST 8"
echo "Run default hydra sweep (executes 4 different combinations with fast_dev_run=True)"
python train.py -m datamodule.batch_size=32,64 model.lr=0.001,0.003 \
+trainer.fast_dev_run=True \
trainer.fast_dev_run=True \
print_config=false
echo "TEST 8"
echo "Run with 16 bit precision"
python train.py trainer.max_epochs=1 +trainer.precision=16 \
print_config=false
# Test multiple workers and cuda pinned memory
echo "TEST 9"
python train.py trainer.gpus=1 trainer.max_epochs=2 \
datamodule.num_workers=4 datamodule.pin_memory=True \
echo "Run with gradient accumulation"
python train.py trainer.max_epochs=1 +trainer.accumulate_grad_batches=10 \
print_config=false
# Test 16 bit precision
echo "TEST 10"
python train.py trainer.gpus=1 trainer.max_epochs=1 precision=16 \
echo "Run validation loop twice per epoch"
python train.py trainer.max_epochs=2 +trainer.val_check_interval=0.5 \
print_config=false
# Test gradient accumulation
echo "TEST 11"
python train.py trainer.gpus=1 trainer.max_epochs=1 accumulate_grad_batches=10 \
echo "Run with CSVLogger (2 epochs)"
python train.py logger=csv trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false
# Test running validation loop twice per epoch
echo "TEST 12"
python train.py trainer.gpus=1 trainer.max_epochs=2 val_check_interval=0.5 \
print_config=false
# Test CSV logger (5 epochs)
echo "TEST 13"
python train.py logger=csv_logger trainer.min_epochs=5 trainer.max_epochs=5 trainer.gpus=1 \
print_config=false
# Test TensorBoard logger (5 epochs)
echo "TEST 14"
python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=5 trainer.gpus=1 \
print_config=false
# Test mixed-precision training
echo "TEST 15"
python train.py trainer.gpus=1 trainer.max_epochs=3 \
+amp_backend='apex' amp_level='O2' \
echo "Run with TensorBoardLogger (2 epochs)"
python train.py logger=tensorboard trainer.min_epochs=5 trainer.max_epochs=2 \
print_config=false
+6 -4
View File
@@ -4,6 +4,7 @@
# To execute:
# bash tests/sweep_tests.sh
# Method for printing test name
echo() {
termwidth="$(tput cols)"
padding="$(printf '%0.1s' ={1..500})"
@@ -13,18 +14,19 @@ echo() {
# Make python hide warnings
export PYTHONWARNINGS="ignore"
# Test default hydra sweep with wandb logging
echo "TEST 1"
echo "Default hydra sweep with wandb logging"
python train.py -m datamodule.batch_size=64,128 model.lr=0.001,0.003 \
+experiment=exp_example_simple \
trainer.gpus=1 trainer.max_epochs=2 seed=12345 \
trainer.gpus=-1 trainer.max_epochs=2 \
datamodule.num_workers=12 datamodule.pin_memory=True \
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="DefaultSweep_MNIST_SimpleDenseNet"
# Test optuna sweep with wandb logging
echo "TEST 2"
echo "Optuna sweep with wandb logging"
python train.py -m --config-name config_optuna.yaml \
+experiment=exp_example_simple \
trainer.gpus=1 trainer.max_epochs=5 seed=12345 \
trainer.gpus=-1 trainer.max_epochs=5 \
datamodule.num_workers=12 datamodule.pin_memory=True \
logger=wandb logger.wandb.project="env_tests" logger.wandb.group="Optuna_MNIST_SimpleDenseNet"
+40 -34
View File
@@ -5,6 +5,7 @@ from pytorch_lightning import seed_everything
# hydra imports
from omegaconf import DictConfig
from hydra.utils import log
import hydra
# normal imports
@@ -18,50 +19,49 @@ from src.utils import template_utils as utils
def train(config: DictConfig):
# Disable python warnings
if config['disable_warnings']:
warnings.filterwarnings('ignore')
# Disable PyTorch Lightning logs
if config['disable_lightning_logs']:
logging.getLogger('lightning').setLevel(logging.ERROR)
# Pretty print config using Rich library
if config['print_config']:
utils.print_config(config)
# A couple of optional utilities:
# - disabling warnings,
# - printing config with Rich,
# - forcing debug friendly configuration
# You can safely get rid of this line if you don't want those
utils.extras(config)
# Set seed for random number generators in pytorch, numpy and python.random
if 'seed' in config:
seed_everything(config['seed'])
if "seed" in config:
seed_everything(config.seed)
# Init PyTorch Lightning model ⚡
model: LightningModule = hydra.utils.instantiate(config['model'])
# Init Lightning model ⚡
log.info(f"Instantiating model <{config.model._target_}>")
model: LightningModule = hydra.utils.instantiate(config.model)
# Init PyTorch Lightning datamodule ⚡
datamodule: LightningDataModule = hydra.utils.instantiate(config['datamodule'])
datamodule.prepare_data()
datamodule.setup()
# Init Lightning datamodule ⚡
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
datamodule: LightningDataModule = hydra.utils.instantiate(config.datamodule)
# Init PyTorch Lightning callbacks
# Init Lightning callbacks
callbacks: List[Callback] = []
if 'callbacks' in config:
for _, cb_conf in config['callbacks'].items():
if '_target_' in cb_conf:
if "callbacks" in config:
for _, cb_conf in config["callbacks"].items():
if "_target_" in cb_conf:
log.info(f"Instantiating callback <{cb_conf._target_}>")
callbacks.append(hydra.utils.instantiate(cb_conf))
# Init PyTorch Lightning loggers
# Init Lightning loggers
logger: List[LightningLoggerBase] = []
if 'logger' in config:
for _, lg_conf in config['logger'].items():
if '_target_' in lg_conf:
if "logger" in config:
for _, lg_conf in config["logger"].items():
if "_target_" in lg_conf:
log.info(f"Instantiating logger <{lg_conf._target_}>")
logger.append(hydra.utils.instantiate(lg_conf))
# Init PyTorch Lightning trainer ⚡
# Init Lightning trainer ⚡
log.info(f"Instantiating trainer <{config.trainer._target_}>")
trainer: Trainer = hydra.utils.instantiate(
config['trainer'], callbacks=callbacks, logger=logger
config.trainer, callbacks=callbacks, logger=logger
)
# Send some parameters from config to all lightning loggers
log.info(f"Logging hyperparameters!")
utils.log_hparams_to_all_loggers(
config=config,
model=model,
@@ -72,12 +72,16 @@ def train(config: DictConfig):
)
# Train the model ⚡
log.info(f"Starting training!")
trainer.fit(model=model, datamodule=datamodule)
# Evaluate model on test set after training
if not config.trainer.get("fast_dev_run"):
log.info(f"Starting testing!")
trainer.test()
# Make sure everything closed properly
log.info(f"Finalizing!")
utils.finish(
config=config,
model=model,
@@ -87,16 +91,18 @@ def train(config: DictConfig):
logger=logger,
)
# Return metric score for optuna optimization
optimized_metric = config.get('optimized_metric', None)
# Return metric score for Optuna optimization
optimized_metric = config.get("optimized_metric")
if optimized_metric:
return trainer.callback_metrics[optimized_metric]
result = trainer.callback_metrics[optimized_metric]
log.info(f"Returning metric for Optuna: <{optimized_metric}={result}>")
return result
@hydra.main(config_path='configs/', config_name='config.yaml')
@hydra.main(config_path="configs/", config_name="config.yaml")
def main(config: DictConfig):
return train(config)
if __name__ == '__main__':
if __name__ == "__main__":
main()