many small improvements

This commit is contained in:
hobogalaxy committed 2020-12-13 22:36:20 +01:00
1 parent f75d2a83ef
commit afb4e17b2c
9 files changed
+52 -44

No files matched your search

+7 -4
View File
@@ -130,12 +130,15 @@ SIMPLE_CONFIG_EXAMPLE_MNIST:
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]
``` ```
To start training with this configuration run: `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` To start training with this configuration run:<br>
`python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST`
Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.<br>
EVERY OTHER SECTION IS OPTIONAL! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)<br>
Each run configuration needs to contain sections `trainer`, `model` and `datamodule`. <br>
Sections `seed`, `callbacks`, `wandb` and `resume_training` are optional and can be removed (see advanced config example in [run_configs.yaml](project/run_configs.yaml)).<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 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_datamodule](project/datamodules/mnist_datamodule/datamodule.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_datamodule](project/datamodules/mnist_datamodule/datamodule.py)).<br>
<br> <br>
@@ -146,7 +149,7 @@ Every parameter specified in datamodule hparams section will be passed to your d
3. Create new run config in [run_configs.yaml](project/run_configs.yaml) 3. Create new run config in [run_configs.yaml](project/run_configs.yaml)
- specify path to your model class - specify path to your model class
- specify path to your datamodule class - specify path to your datamodule class
- you can add there and hyperparameters you want! - you can add there any hyperparameters you want!
3. Configure your project in [project_config.yaml](project/project_config.yaml) 3. Configure your project in [project_config.yaml](project/project_config.yaml)
4. Run training with chosen run config<br> 4. Run training with chosen run config<br>
```bash ```bash
@@ -12,7 +12,7 @@ class LitModel(pl.LightningModule):
This is example of lightning model for MNIST digits classification. This is example of lightning model for MNIST digits classification.
The path to model should be specified in your run config. (run_configs.yaml) 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) The 'hparams' dict contains your hparams specified in your run config. (run_configs.yaml)
This class enables you to specify what happens during training, validation and test step. 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. You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training.
+9 -9
View File
@@ -1,5 +1,5 @@
# set -1 to train on all GPUs abailable, set 0 to train on CPU only # set -1 to train on all GPUs abailable, set 0 to train on CPU only
num_of_gpus: 0 num_of_gpus: -1
# Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases) # Weights&Biases configuration (just remove this section if you don't want tu use Weights&Biases)
@@ -18,15 +18,15 @@ loggers:
# if you specify the same callback class also in run config then it will overwrite the one set here # if you specify the same callback class also in run config then it will overwrite the one set here
# all of the callback parameters will be passed to it on initialization # all of the callback parameters will be passed to it on initialization
default_callbacks: default_callbacks:
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
monitor: "val_acc"
patience: 5
mode: "max"
ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback
monitor: "val_acc" monitor: "val_acc" # name of the logged metric which determines when model is improving
save_top_k: 1 save_top_k: 1 # save k best models (determined by above metric)
save_last: True save_last: True # additionaly always save model from last epoch
mode: "max" mode: "max" # can be "max" or "min"
EarlyStopping: # name of PyTorch Lightning class for early stopping callback
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"
# configure things which are printed in terminal # configure things which are printed in terminal
+2 -2
View File
@@ -78,9 +78,9 @@ ADVANCED_CONFIG_EXAMPLE_MNIST:
save_top_k: 1 save_top_k: 1
save_last: True save_last: True
mode: "max" mode: "max"
ConfusionMatrixLoggerCallback: # some custom callback class from template_utils/callbacks.py ConfusionMatrixWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
MetricsHeatmapLoggerCallback: # some custom callback class from template_utils/callbacks.py MetricsHeatmapWandbLoggerCallback: # some custom callback class from template_utils/wandb_callbacks.py
class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] class_names: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
resume_training: resume_training:
checkpoint_path: None # path to your checkpoint checkpoint_path: None # path to your checkpoint
+5 -13
View File
@@ -2,7 +2,7 @@
# YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS # YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS
from argparse import ArgumentParser from argparse import ArgumentParser
from train import train import train
import wandb import wandb
import yaml import yaml
import os import os
@@ -18,25 +18,17 @@ def main(project_config_path, run_configs_path):
# EXECUTE ALL RUNS ONE AFTER THE OTHER # EXECUTE ALL RUNS ONE AFTER THE OTHER
for conf_name in run_configs: for conf_name in run_configs:
print() print(f"\nEXECUTING RUN: {conf_name}\n")
print("EXECUTING RUN:", conf_name) train.train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
print("CONFIG:")
for section in run_configs[conf_name]:
print(" " + section + ":")
for key in run_configs[conf_name][section]:
print(" " + key + ":", run_configs[conf_name][section][key])
print()
train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True)
wandb.finish() wandb.finish()
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(os.path.dirname(os.path.dirname(__file__)), "project_config.yaml")) default=os.path.join(train.BASE_DIR, "project_config.yaml"))
parser.add_argument("-r", "--run_configs_path", type=str, parser.add_argument("-r", "--run_configs_path", type=str,
default=os.path.join(os.path.dirname(os.path.dirname(__file__)), "run_configs.yaml")) default=os.path.join(train.BASE_DIR, "run_configs.yaml"))
args = parser.parse_args() args = parser.parse_args()
main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path) main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path)
+7 -7
View File
@@ -6,7 +6,7 @@ import train
# Choose which run config to optimize # Choose which run config to optimize
RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1" RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST"
# Load configs # Load configs
project_config = train.load_config("project_config.yaml") project_config = train.load_config("project_config.yaml")
@@ -20,12 +20,12 @@ sweep_hparams = wandb.Config._as_dict(wandb.config)
for key, value in sweep_hparams.items(): for key, value in sweep_hparams.items():
if key == "_wandb": if key == "_wandb":
continue continue
elif key in run_config["trainer"].keys(): elif key in run_config["trainer"]["args"]:
run_config["trainer"][key] = value run_config["trainer"]["args"][key] = value
elif key in run_config["model"].keys(): elif key in run_config["model"]["hparams"]:
run_config["model"][key] = value run_config["model"]["hparams"][key] = value
elif key in run_config["dataset"].keys(): elif key in run_config["datamodule"]["hparams"]:
run_config["dataset"][key] = value run_config["datamodule"]["hparams"][key] = value
# Execute run # Execute run
train.train(project_config=project_config, run_config=run_config, use_wandb=True) train.train(project_config=project_config, run_config=run_config, use_wandb=True)
+1 -1
View File
@@ -274,7 +274,7 @@ def init_wandb_logger(project_config: dict,
"test_size": len(datamodule.data_test) "test_size": len(datamodule.data_test)
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,
}) })
wandb_logger.log_hyperparams(project_config["num_of_gpus"]) wandb_logger.log_hyperparams({"num_of_gpus": project_config["num_of_gpus"]})
wandb_logger.log_hyperparams(run_config["trainer"]["args"]) wandb_logger.log_hyperparams(run_config["trainer"]["args"])
wandb_logger.log_hyperparams(run_config["model"]["hparams"]) wandb_logger.log_hyperparams(run_config["model"]["hparams"])
wandb_logger.log_hyperparams(run_config["model"]["load_from"]) wandb_logger.log_hyperparams(run_config["model"]["load_from"])
+3 -3
View File
@@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback):
wandb.save(file_path, base_path=self.wandb_save_dir) wandb.save(file_path, base_path=self.wandb_save_dir)
class ImagePredictionLoggerCallback(Callback): class ImagePredictionWandbLoggerCallback(Callback):
""" """
Each epoch upload to wandb a couple of the same images with predicted labels. Each epoch upload to wandb a couple of the same images with predicted labels.
""" """
@@ -58,7 +58,7 @@ class ImagePredictionLoggerCallback(Callback):
]}, commit=False) ]}, commit=False)
class MetricsHeatmapLoggerCallback(Callback): class MetricsHeatmapWandbLoggerCallback(Callback):
""" """
Generate f1, precision and recall heatmap from validation epoch outputs. Generate f1, precision and recall heatmap from validation epoch outputs.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
@@ -107,7 +107,7 @@ class MetricsHeatmapLoggerCallback(Callback):
self.targets = [] self.targets = []
class ConfusionMatrixLoggerCallback(Callback): class ConfusionMatrixWandbLoggerCallback(Callback):
""" """
Generate Confusion Matrix. Generate Confusion Matrix.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
+17 -4
View File
@@ -106,10 +106,23 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str,
if __name__ == "__main__": if __name__ == "__main__":
parser = ArgumentParser() parser = ArgumentParser()
parser.add_argument("--project_config_path", type=str, default="project_config.yaml") parser.add_argument("--project_config_path",
parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") type=str,
parser.add_argument("--run_config_name", type=str, default="SIMPLE_CONFIG_EXAMPLE_MNIST") default="project_config.yaml",
parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') help="Path to file containing your project configuration")
parser.add_argument("--run_configs_path",
type=str,
default="run_configs.yaml",
help="Path to file containing your run configurations")
parser.add_argument("--run_config_name",
type=str,
default="SIMPLE_CONFIG_EXAMPLE_MNIST",
help="Name of you configuration in run_configs.yaml")
parser.add_argument("--no_wandb",
dest='use_wandb',
action='store_false',
help="Whether to use Weights&Biases or not")
parser.set_defaults(use_wandb=True) parser.set_defaults(use_wandb=True)
args = parser.parse_args() args = parser.parse_args()