diff --git a/README.md b/README.md index a431ba8..f6f4214 100644 --- a/README.md +++ b/README.md @@ -130,12 +130,15 @@ SIMPLE_CONFIG_EXAMPLE_MNIST: batch_size: 64 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:
+ `python train.py --run_config_name SIMPLE_CONFIG_EXAMPLE_MNIST` + +Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
+EVERY OTHER SECTION IS OPTIONAL! (see [run_configs.yaml](project/run_configs.yaml) for more advanced config example with optional sections)
-Each run configuration needs to contain sections `trainer`, `model` and `datamodule`.
-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)).
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)).
+ 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)).

@@ -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) - specify path to your model 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) 4. Run training with chosen run config
```bash diff --git a/project/models/simple_mnist_classifier/lightning_module.py b/project/models/simple_mnist_classifier/lightning_module.py index 7a981b2..99d7617 100644 --- a/project/models/simple_mnist_classifier/lightning_module.py +++ b/project/models/simple_mnist_classifier/lightning_module.py @@ -12,7 +12,7 @@ class LitModel(pl.LightningModule): 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 '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. You can just remove 'validation_step()' or 'test_step()' methods if you don't want to have them during training. diff --git a/project/project_config.yaml b/project/project_config.yaml index 4869a9c..ff29583 100644 --- a/project/project_config.yaml +++ b/project/project_config.yaml @@ -1,5 +1,5 @@ # 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) @@ -18,15 +18,15 @@ loggers: # 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 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 - monitor: "val_acc" - save_top_k: 1 - save_last: True - mode: "max" + ModelCheckpoint: # name of PyTorch Lightning class for checkpointing callback + 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" + 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 diff --git a/project/run_configs.yaml b/project/run_configs.yaml index 4a5c1d1..22d5196 100644 --- a/project/run_configs.yaml +++ b/project/run_configs.yaml @@ -78,9 +78,9 @@ ADVANCED_CONFIG_EXAMPLE_MNIST: save_top_k: 1 save_last: True 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"] - 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"] resume_training: checkpoint_path: None # path to your checkpoint diff --git a/project/template_utils/execute_all_runs.py b/project/template_utils/execute_all_runs.py index 4c5ce61..193f9e6 100644 --- a/project/template_utils/execute_all_runs.py +++ b/project/template_utils/execute_all_runs.py @@ -2,7 +2,7 @@ # YOU CAN ALSO SPECIFY PATH TO DIFFERENT FILE WITH RUN CONFIGS from argparse import ArgumentParser -from train import train +import train import wandb import yaml import os @@ -18,25 +18,17 @@ def main(project_config_path, run_configs_path): # EXECUTE ALL RUNS ONE AFTER THE OTHER for conf_name in run_configs: - print() - print("EXECUTING RUN:", conf_name) - 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) + print(f"\nEXECUTING RUN: {conf_name}\n") + train.train(project_config=project_config, run_config=run_configs[conf_name], use_wandb=True) wandb.finish() if __name__ == "__main__": parser = ArgumentParser() 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, - 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() main(project_config_path=args.project_config_path, run_configs_path=args.run_configs_path) diff --git a/project/template_utils/execute_sweep.py b/project/template_utils/execute_sweep.py index 9442d6a..7a205ab 100644 --- a/project/template_utils/execute_sweep.py +++ b/project/template_utils/execute_sweep.py @@ -6,7 +6,7 @@ import train # Choose which run config to optimize -RUN_CONFIG_NAME = "MNIST_CLASSIFIER_V1" +RUN_CONFIG_NAME = "SIMPLE_CONFIG_EXAMPLE_MNIST" # Load configs 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(): if key == "_wandb": continue - elif key in run_config["trainer"].keys(): - run_config["trainer"][key] = value - elif key in run_config["model"].keys(): - run_config["model"][key] = value - elif key in run_config["dataset"].keys(): - run_config["dataset"][key] = value + elif key in run_config["trainer"]["args"]: + run_config["trainer"]["args"][key] = value + elif key in run_config["model"]["hparams"]: + run_config["model"]["hparams"][key] = value + elif key in run_config["datamodule"]["hparams"]: + run_config["datamodule"]["hparams"][key] = value # Execute run train.train(project_config=project_config, run_config=run_config, use_wandb=True) diff --git a/project/template_utils/initializers.py b/project/template_utils/initializers.py index 6de8388..8a1e067 100644 --- a/project/template_utils/initializers.py +++ b/project/template_utils/initializers.py @@ -274,7 +274,7 @@ 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(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["model"]["hparams"]) wandb_logger.log_hyperparams(run_config["model"]["load_from"]) diff --git a/project/template_utils/wandb_callbacks.py b/project/template_utils/wandb_callbacks.py index f56783e..3a4b94a 100644 --- a/project/template_utils/wandb_callbacks.py +++ b/project/template_utils/wandb_callbacks.py @@ -31,7 +31,7 @@ class SaveOnnxModelToWandbCallback(Callback): 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. """ @@ -58,7 +58,7 @@ class ImagePredictionLoggerCallback(Callback): ]}, commit=False) -class MetricsHeatmapLoggerCallback(Callback): +class MetricsHeatmapWandbLoggerCallback(Callback): """ Generate f1, precision and recall heatmap from validation epoch outputs. Expects validation step to return predictions and targets. @@ -107,7 +107,7 @@ class MetricsHeatmapLoggerCallback(Callback): self.targets = [] -class ConfusionMatrixLoggerCallback(Callback): +class ConfusionMatrixWandbLoggerCallback(Callback): """ Generate Confusion Matrix. Expects validation step to return predictions and targets. diff --git a/project/train.py b/project/train.py index d26643e..514493c 100644 --- a/project/train.py +++ b/project/train.py @@ -106,10 +106,23 @@ def main(project_config_path: str, run_configs_path: str, run_config_name: str, if __name__ == "__main__": parser = ArgumentParser() - parser.add_argument("--project_config_path", type=str, default="project_config.yaml") - parser.add_argument("--run_configs_path", type=str, default="run_configs.yaml") - parser.add_argument("--run_config_name", type=str, default="SIMPLE_CONFIG_EXAMPLE_MNIST") - parser.add_argument("--no_wandb", dest='use_wandb', action='store_false') + parser.add_argument("--project_config_path", + type=str, + default="project_config.yaml", + 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) args = parser.parse_args()