add optimizer to rich printing

This commit is contained in:
hobogalaxy committed 2021-03-11 00:13:52 +01:00
1 parent 5f57eb7875
commit 3586f355b9
6 files changed
+56 -48

No files matched your search

+6 -8
View File
@@ -43,14 +43,13 @@ to your `README.md`.
## Introduction ## Introduction
This template tries to be as general as possible. 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).
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).
> 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. > 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? ### Why PyTorch Lightning?
PyTorch Lightning is a lightweight PyTorch wrapper for high-performance AI research. 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 # link to wandb dashboard should appear in the terminal
python train.py logger=wandb 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.**
</details> </details>
@@ -340,8 +339,7 @@ python train.py -m '+experiment=glob(*)'
### How To Start? ### How To Start?
- First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) - 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) - 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)
- 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)
<br> <br>
### Main Project Configuration ### Main Project Configuration
@@ -615,7 +613,7 @@ To format all files in the project use command:
```yaml ```yaml
pre-commit run --all-files 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 ### Tests
+7 -7
View File
@@ -7,11 +7,13 @@ gpus: 0
min_epochs: 1 min_epochs: 1
max_epochs: 10 max_epochs: 10
# prints
progress_bar_refresh_rate: null
weights_summary: null
profiler: null
# all of the parameters below are set to Lightning defaults # all of the parameters below are set to Lightning defaults
resume_from_checkpoint: null
# tricks # tricks
gradient_clip_val: 0 gradient_clip_val: 0
accumulate_grad_batches: 1 accumulate_grad_batches: 1
@@ -28,11 +30,6 @@ limit_val_batches: 1.0
limit_test_batches: 1.0 limit_test_batches: 1.0
track_grad_norm: -1 track_grad_norm: -1
# prints
progress_bar_refresh_rate: null
weights_summary: null
profiler: null
# others # others
amp_backend: "native" amp_backend: "native"
amp_level: "02" amp_level: "02"
@@ -41,3 +38,6 @@ accelerator: null
num_nodes: 1 num_nodes: 1
tpu_cores: null tpu_cores: null
deterministic: False deterministic: False
# resume
resume_from_checkpoint: null
+5 -4
View File
@@ -1,7 +1,8 @@
from pytorch_lightning import LightningDataModule 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.datasets import MNIST
from torchvision.transforms import transforms from torchvision.transforms import transforms
from typing import Optional, Sequence
class MNISTDataModule(LightningDataModule): class MNISTDataModule(LightningDataModule):
@@ -31,9 +32,9 @@ class MNISTDataModule(LightningDataModule):
# self.dims is returned when you call datamodule.size() # self.dims is returned when you call datamodule.size()
self.dims = (1, 28, 28) self.dims = (1, 28, 28)
self.data_train = None self.data_train: Optional[Dataset] = None
self.data_val = None self.data_val: Optional[Dataset] = None
self.data_test = None self.data_test: Optional[Dataset] = None
def prepare_data(self): def prepare_data(self):
"""Download data if needed. This method is called only from a single GPU. """Download data if needed. This method is called only from a single GPU.
+1 -1
View File
@@ -93,7 +93,7 @@ class LitModelMNIST(pl.LightningModule):
self.log("test/loss", loss, on_step=False, on_epoch=True) self.log("test/loss", loss, on_step=False, on_epoch=True)
self.log("test/acc", acc, on_step=False, on_epoch=True) self.log("test/acc", acc, on_step=False, on_epoch=True)
return {"loss": loss} return loss
# [OPTIONAL METHOD] # [OPTIONAL METHOD]
def training_epoch_end(self, outputs: List[Any]) -> None: def training_epoch_end(self, outputs: List[Any]) -> None:
+35 -24
View File
@@ -71,6 +71,8 @@ def print_config(config: DictConfig, resolve: bool = True):
# TODO print main config path and experiment config path # TODO print main config path and experiment config path
# directory = to_absolute_path("configs/config.yaml") # directory = to_absolute_path("configs/config.yaml")
# print(f"Main config path: [link file://{directory}]{directory}") # print(f"Main config path: [link file://{directory}]{directory}")
#TODO make this method more general
style = "dim" style = "dim"
@@ -87,6 +89,10 @@ def print_config(config: DictConfig, resolve: bool = True):
datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=resolve) datamodule = OmegaConf.to_yaml(config["datamodule"], resolve=resolve)
datamodule_branch = tree.add("Datamodule", style=style, guide_style=style) datamodule_branch = tree.add("Datamodule", style=style, guide_style=style)
datamodule_branch.add(Syntax(datamodule, "yaml")) 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) callbacks_branch = tree.add("Callbacks", style=style, guide_style=style)
if "callbacks" in config: if "callbacks" in config:
@@ -111,7 +117,7 @@ def print_config(config: DictConfig, resolve: bool = True):
print(tree) print(tree)
def log_hparams_to_all_loggers( def log_hyperparameters(
config: DictConfig, config: DictConfig,
model: pl.LightningModule, model: pl.LightningModule,
datamodule: pl.LightningDataModule, datamodule: pl.LightningDataModule,
@@ -120,7 +126,10 @@ def log_hparams_to_all_loggers(
logger: List[pl.loggers.LightningLoggerBase], logger: List[pl.loggers.LightningLoggerBase],
): ):
"""This method controls which parameters from Hydra config are saved by Lightning loggers. """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: Args:
config (DictConfig): [description] config (DictConfig): [description]
@@ -132,39 +141,41 @@ def log_hparams_to_all_loggers(
""" """
hparams = {} hparams = {}
# save all params of model, datamodule and trainer # choose which parts of hydra config will be saved to loggers
hparams.update(config["model"]) hparams["trainer"] = config["trainer"]
hparams.update(config["datamodule"]) hparams["model"] = config["model"]
hparams.update(config["trainer"]) hparams["optimizer"] = config["optimizer"]
hparams.pop("_target_") hparams["datamodule"] = config["datamodule"]
if "callbacks" in config:
# save seed hparams["callbacks"] = config["callbacks"]
hparams["seed"] = config.get("seed", "None")
# save targets
hparams["_class_model"] = config["model"]["_target_"]
hparams["_class_datamodule"] = config["datamodule"]["_target_"]
# save sizes of each dataset # save sizes of each dataset
if hasattr(datamodule, "data_train") and datamodule.data_train: # (requires calling `datamodule.setup()` first to initialize datasets)
hparams["train_size"] = len(datamodule.data_train) # datamodule.setup()
if hasattr(datamodule, "data_val") and datamodule.data_val: # if hasattr(datamodule, "data_train") and datamodule.data_train:
hparams["val_size"] = len(datamodule.data_val) # hparams["datamodule/train_size"] = len(datamodule.data_train)
if hasattr(datamodule, "data_test") and datamodule.data_test: # if hasattr(datamodule, "data_val") and datamodule.data_val:
hparams["test_size"] = len(datamodule.data_test) # 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 # save number of model parameters
hparams["#params_total"] = sum(p.numel() for p in model.parameters()) hparams["model/params_total"] = sum(p.numel() for p in model.parameters())
hparams["#params_trainable"] = sum( hparams["model/params_trainable"] = sum(
p.numel() for p in model.parameters() if p.requires_grad 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 p.numel() for p in model.parameters() if not p.requires_grad
) )
# send hparams to all loggers # send hparams to all loggers
trainer.logger.log_hyperparams(hparams) 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( def finish(
+2 -4
View File
@@ -68,7 +68,7 @@ def train(config: DictConfig):
# Send some parameters from config to all lightning loggers # Send some parameters from config to all lightning loggers
log.info(f"Logging hyperparameters!") log.info(f"Logging hyperparameters!")
utils.log_hparams_to_all_loggers( utils.log_hyperparameters(
config=config, config=config,
model=model, model=model,
datamodule=datamodule, datamodule=datamodule,
@@ -100,9 +100,7 @@ def train(config: DictConfig):
# Return metric score for Optuna optimization # Return metric score for Optuna optimization
optimized_metric = config.get("optimized_metric") optimized_metric = config.get("optimized_metric")
if optimized_metric: if optimized_metric:
result = trainer.callback_metrics[optimized_metric] return 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")