From 3586f355b9c171b9e4a520ae8cdbd22495e8e42f Mon Sep 17 00:00:00 2001 From: hobogalaxy Date: Thu, 11 Mar 2021 00:13:52 +0100 Subject: [PATCH] add optimizer to rich printing --- README.md | 14 +++---- configs/trainer/default_trainer.yaml | 14 +++---- src/datamodules/mnist_datamodule.py | 9 +++-- src/models/mnist_model.py | 2 +- src/utils/template_utils.py | 59 +++++++++++++++++----------- train.py | 6 +-- 6 files changed, 56 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index aaf7dbd..ad2675c 100644 --- a/README.md +++ b/README.md @@ -43,14 +43,13 @@ to your `README.md`. ## Introduction -This template tries to be as general as possible. -By using it, you avoid writing any boilerplate code. At the same time it's flexible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [train.py](train.py). +This template tries to be as general as possible - you can easily delete any unwanted features from the pipeline or rewire the configuration, by modifying behavior in [train.py](train.py). > Effective usage of this template requires learning of a couple of technologies: [PyTorch](https://pytorch.org), [PyTorch Lightning](https://www.pytorchlightning.ai) and [Hydra](https://hydra.cc). Knowledge of some experiment logging framework like [Weights&Biases](https://wandb.com), [Neptune](https://neptune.ai) or [MLFlow](https://mlflow.org) is also recommended. -The main advantage of using it, is that it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it might be the most convenient and all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility. +Why you should use it: it allows you to rapidly iterate over new models and scale your projects from small single experiments to large hyperparameter searches on computing clusters, without writing any boilerplate code. To my knowledge, it's one of the most, if not the most convenient all-in-one technology stack for Deep Learning research. It's also a collection of best practices for efficient workflow and reproducibility. -The main arguments for not using this template, are that Lightning and Hydra are not yet mature, which means you will probably run into some bugs. Also Lightning is not well suited for everything, e.g. for Reinforcement Learning it's probably better to replace it with Ray/RLlib. +Why you shouldn't use it: Lightning and Hydra are not yet mature, which means you might run into some bugs sooner or later. ### Why PyTorch Lightning? PyTorch Lightning is a lightweight PyTorch wrapper for high-performance AI research. @@ -204,7 +203,7 @@ wandb: # link to wandb dashboard should appear in the terminal python train.py logger=wandb ``` -> *Click [here]() to see example wandb dashboard generated with this template.* +> **Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.** @@ -340,8 +339,7 @@ python train.py -m '+experiment=glob(*)' ### How To Start? - First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) -- Next, read this blog post: [Keeping Up with PyTorch Lightning and Hydra](https://towardsdatascience.com/keeping-up-with-pytorch-lightning-and-hydra-2nd-edition-34f88e9d5c90) -- Lastly, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) and [docs about instantiating objects with Hydra](https://hydra.cc/docs/patterns/instantiate_objects/overview) +- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) and [docs about instantiating objects with Hydra](https://hydra.cc/docs/patterns/instantiate_objects/overview)
### Main Project Configuration @@ -615,7 +613,7 @@ To format all files in the project use command: ```yaml pre-commit run --all-files ``` -You can exclude chosen files from automatic formatting, by modifying config (see [.pre-commit-config.yaml](pre-commit-config.yaml)) +You can exclude chosen files from automatic formatting, by modifying config (see [.pre-commit-config.yaml](.pre-commit-config.yaml)) ### Tests diff --git a/configs/trainer/default_trainer.yaml b/configs/trainer/default_trainer.yaml index 02ded78..d2703ab 100644 --- a/configs/trainer/default_trainer.yaml +++ b/configs/trainer/default_trainer.yaml @@ -7,11 +7,13 @@ gpus: 0 min_epochs: 1 max_epochs: 10 +# prints +progress_bar_refresh_rate: null +weights_summary: null +profiler: null # all of the parameters below are set to Lightning defaults -resume_from_checkpoint: null - # tricks gradient_clip_val: 0 accumulate_grad_batches: 1 @@ -28,11 +30,6 @@ limit_val_batches: 1.0 limit_test_batches: 1.0 track_grad_norm: -1 -# prints -progress_bar_refresh_rate: null -weights_summary: null -profiler: null - # others amp_backend: "native" amp_level: "02" @@ -41,3 +38,6 @@ accelerator: null num_nodes: 1 tpu_cores: null deterministic: False + +# resume +resume_from_checkpoint: null diff --git a/src/datamodules/mnist_datamodule.py b/src/datamodules/mnist_datamodule.py index 4db3e2d..4a5eff4 100644 --- a/src/datamodules/mnist_datamodule.py +++ b/src/datamodules/mnist_datamodule.py @@ -1,7 +1,8 @@ from pytorch_lightning import LightningDataModule -from torch.utils.data import ConcatDataset, DataLoader, random_split +from torch.utils.data import ConcatDataset, DataLoader, random_split, Dataset from torchvision.datasets import MNIST from torchvision.transforms import transforms +from typing import Optional, Sequence class MNISTDataModule(LightningDataModule): @@ -31,9 +32,9 @@ class MNISTDataModule(LightningDataModule): # self.dims is returned when you call datamodule.size() self.dims = (1, 28, 28) - self.data_train = None - self.data_val = None - self.data_test = None + self.data_train: Optional[Dataset] = None + self.data_val: Optional[Dataset] = None + self.data_test: Optional[Dataset] = None def prepare_data(self): """Download data if needed. This method is called only from a single GPU. diff --git a/src/models/mnist_model.py b/src/models/mnist_model.py index 01f5473..64ae6e1 100644 --- a/src/models/mnist_model.py +++ b/src/models/mnist_model.py @@ -93,7 +93,7 @@ class LitModelMNIST(pl.LightningModule): self.log("test/loss", loss, on_step=False, on_epoch=True) self.log("test/acc", acc, on_step=False, on_epoch=True) - return {"loss": loss} + return loss # [OPTIONAL METHOD] def training_epoch_end(self, outputs: List[Any]) -> None: diff --git a/src/utils/template_utils.py b/src/utils/template_utils.py index 852b073..d25ed38 100644 --- a/src/utils/template_utils.py +++ b/src/utils/template_utils.py @@ -71,6 +71,8 @@ def print_config(config: DictConfig, resolve: bool = True): # TODO print main config path and experiment config path # directory = to_absolute_path("configs/config.yaml") # print(f"Main config path: [link file://{directory}]{directory}") + + #TODO make this method more general style = "dim" @@ -87,6 +89,10 @@ def print_config(config: DictConfig, resolve: bool = True): datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=resolve) datamodule_branch = tree.add("Datamodule", style=style, guide_style=style) datamodule_branch.add(Syntax(datamodule, "yaml")) + + optimizer = OmegaConf.to_yaml(config["optimizer"], resolve=resolve) + optimizer_branch = tree.add("Optimizer", style=style, guide_style=style) + optimizer_branch.add(Syntax(optimizer, "yaml")) callbacks_branch = tree.add("Callbacks", style=style, guide_style=style) if "callbacks" in config: @@ -111,7 +117,7 @@ def print_config(config: DictConfig, resolve: bool = True): print(tree) -def log_hparams_to_all_loggers( +def log_hyperparameters( config: DictConfig, model: pl.LightningModule, datamodule: pl.LightningDataModule, @@ -120,7 +126,10 @@ def log_hparams_to_all_loggers( logger: List[pl.loggers.LightningLoggerBase], ): """This method controls which parameters from Hydra config are saved by Lightning loggers. - It additionaly saves sizes of each dataset and number of trainable model parameters. + + Additionaly saves: + - sizes of train, val, test dataset + - number of trainable model parameters Args: config (DictConfig): [description] @@ -132,39 +141,41 @@ 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_") - - # save seed - hparams["seed"] = config.get("seed", "None") - - # save targets - hparams["_class_model"] = config["model"]["_target_"] - hparams["_class_datamodule"] = config["datamodule"]["_target_"] + + # choose which parts of hydra config will be saved to loggers + hparams["trainer"] = config["trainer"] + hparams["model"] = config["model"] + hparams["optimizer"] = config["optimizer"] + hparams["datamodule"] = config["datamodule"] + if "callbacks" in config: + hparams["callbacks"] = config["callbacks"] # 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) + # (requires calling `datamodule.setup()` first to initialize datasets) + # datamodule.setup() + # if hasattr(datamodule, "data_train") and datamodule.data_train: + # hparams["datamodule/train_size"] = len(datamodule.data_train) + # if hasattr(datamodule, "data_val") and datamodule.data_val: + # hparams["datamodule/val_size"] = len(datamodule.data_val) + # if hasattr(datamodule, "data_test") and datamodule.data_test: + # hparams["datamodule/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["model/params_total"] = sum(p.numel() for p in model.parameters()) + hparams["model/params_trainable"] = sum( p.numel() for p in model.parameters() if p.requires_grad ) - hparams["#params_not_trainable"] = sum( + hparams["model/params_not_trainable"] = sum( p.numel() for p in model.parameters() if not p.requires_grad ) # send hparams to all loggers trainer.logger.log_hyperparams(hparams) + + # disable logging any more hyperparameters for all loggers + # (this is just to prevent trainer logging hparams of model as we manage it ourselves) + for lg in logger: + lg.log_hyperparams = lambda x: None def finish( diff --git a/train.py b/train.py index 2364a2a..763e57b 100644 --- a/train.py +++ b/train.py @@ -68,7 +68,7 @@ def train(config: DictConfig): # Send some parameters from config to all lightning loggers log.info(f"Logging hyperparameters!") - utils.log_hparams_to_all_loggers( + utils.log_hyperparameters( config=config, model=model, datamodule=datamodule, @@ -100,9 +100,7 @@ def train(config: DictConfig): # Return metric score for Optuna optimization optimized_metric = config.get("optimized_metric") if optimized_metric: - result = trainer.callback_metrics[optimized_metric] - log.info(f"Returning metric for Optuna: <{optimized_metric}={result}>") - return result + return trainer.callback_metrics[optimized_metric] @hydra.main(config_path="configs/", config_name="config.yaml")