From 99b9c1a717b5cdabd32476a452afcac955575e5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Zalewski?= Date: Tue, 30 Mar 2021 03:19:32 +0200 Subject: [PATCH] Dev (#113) * change local lambda to normal function and move it outside of main method to enable DDP * update .pre-commit-config.yaml * update requirements.txt * reformat files * remove disabling lightning logs feature * change logging strings to enable python 3.7 * update README.md * remove double logging bug prevention since lightning fixed that --- .pre-commit-config.yaml | 14 ++- README.md | 147 ++++++++++++++-------------- conda_env_gpu.yaml | 5 +- configs/config.yaml | 10 +- requirements.txt | 12 +-- run.py | 3 +- src/pl_callbacks/wandb_callbacks.py | 39 +++----- src/pl_models/mnist_model.py | 8 +- src/utils/template_utils.py | 48 ++++----- 9 files changed, 146 insertions(+), 140 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 6e49b0e..074ecf9 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -3,7 +3,7 @@ default_language_version: repos: -# Pre-commit-hooks +# Pre-commit hooks - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.2.0 hooks: @@ -19,7 +19,10 @@ repos: rev: 20.8b1 hooks: - id: black - # args: [--force-exclude, src/train.py] + args: [ + --line-length, "99", + # --exclude, src/train.py, + ] # Isort (import sorting) - repo: https://github.com/PyCQA/isort @@ -28,5 +31,10 @@ repos: - id: isort # profiles: https://pycqa.github.io/isort/docs/configuration/profiles/ # other flags: https://pycqa.github.io/isort/docs/configuration/options/ - args: [--profile, black, --skip, src/train.py, --skip, run.py, --filter-files] + args: [ + --profile, black, + --skip, src/train.py, + --skip, run.py, + --filter-files, + ] # files: "src/.*" diff --git a/README.md b/README.md index 12375a3..942b091 100644 --- a/README.md +++ b/README.md @@ -2,15 +2,15 @@ # Lightning-Hydra-Template -PyTorch -Lightning +PyTorch +Lightning Config: hydra Code style: black A clean and scalable template to kickstart your deep learning project 🚀⚡🔥
Click on [Use this template](https://github.com/hobogalaxy/lightning-hydra-template/generate) to initialize new repository. -*This template is work in progress. Suggestions are always welcome!* +*This template is work in progress. Currently uses dev version of Hydra.
Suggestions are always welcome!*

@@ -20,34 +20,9 @@ Click on [Use this template](https://github.com/hobogalaxy/lightning- If you use this template please add
[![](https://shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=303030)](https://github.com/hobogalaxy/lightning-hydra-template)
to your `README.md`. -
+

-**Contents** -- [Introduction](#introduction) -- [Main Ideas Of This Template](#main-ideas-of-this-template) -- [Project Structure](#project-structure) -- [Quickstart](#quickstart) -- [Guide](#guide) - - [How To Learn?](#how-to-learn) - - [Main Project Configuration](#main-project-configuration) - - [Experiment Configuration](#experiment-configuration) - - [Workflow](#workflow) - - [Logs](#logs) - - [Experiment Tracking](#experiment-tracking) - - [Inference](#inference) - - [Callbacks](#callbacks) -- [Best Practices](#best-practices) - - [Miniconda](#miniconda) - - [Automatic Code Formatting](#automatic-code-formatting) - - [Environment Variables](#environment-variables) - - [Data Version Control](#data-version-control) - - [Installing Project As A Package](#support-installing-project-as-a-package) - - [Tests](#tests) -- [Tricks](#tricks) -- [Other Repositories](#other-repositories) -
- ## Introduction 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 [src/train.py](src/train.py). @@ -80,6 +55,7 @@ It makes your code neatly organized and provides lots of useful features, like a - Logs: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - Hyperparameter Search: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) - Best Practices: a couple of recommended tools, practices and standards (see [#Best Practices](#best-practices)) +- Extra Features: optional utilities to make your life easier (see [#Extra Features](#extra-features)) - Workflow: comes down to 4 simple steps (see [#Workflow](#workflow))
@@ -155,16 +131,16 @@ When running `python run.py` you should see something like this: ### Your Superpowers -##### (click to expand) +**(click to expand)**
Override any config parameter from command line -> *Hydra allows you to overwrite any parameter defined in your config, without writing any code!* +> Hydra allows you to overwrite any parameter defined in your config, without writing any code! ```yaml python run.py trainer.max_epochs=20 optimizer.lr=1e-4 ``` -> *You can also add new parameters with `+` sign.* +> You can also add new parameters with `+` sign. ```yaml python run.py +model.new_param="uwu" @@ -176,7 +152,7 @@ python run.py +model.new_param="uwu"
Train on CPU, GPU, TPU or even with DDP and mixed precision -> *PyTorch Lightning makes it really easy to train your models on different hardware.* +> PyTorch Lightning makes it really easy to train your models on different hardware. ```yaml # train on CPU python run.py trainer.gpus=0 @@ -187,11 +163,15 @@ python run.py trainer.gpus=1 # train on TPU python run.py +trainer.tpu_cores=8 +# train with DDP (Distributed Data Parallel) (4 GPUs) +python run.py trainer.gpus=4 +trainer.accelerator='ddp' + # train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes) python run.py trainer.gpus=4 +trainer.num_nodes=2 +trainer.accelerator='ddp' # train with mixed precision -python run.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.precision=16 +python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \ ++trainer.amp_level="O2" ```
@@ -200,7 +180,7 @@ python run.py +trainer.amp_backend="apex" +trainer.amp_level="O1" +trainer.preci
Train model with any logger available in PyTorch Lightning, like Weights&Biases -> *PyTorch Lightning provides convenient integrations with most popular logging frameworks. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below.* +> PyTorch Lightning provides convenient integrations with most popular logging frameworks. Read more [here](#experiment-tracking). Using wandb requires you to [setup account](https://www.wandb.com/) first. After that just complete the config as below. ```yaml # set project and entity names in `configs/logger/wandb` wandb: @@ -213,7 +193,7 @@ wandb: # link to wandb dashboard should appear in the terminal python run.py logger=wandb ``` -> ***Click [here](https://wandb.ai/hobglob/template-dashboard/) 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.**
@@ -221,7 +201,7 @@ python run.py logger=wandb
Train model with chosen experiment config -> *Experiment configurations are placed in [configs/experiment/](configs/experiment/).* +> Experiment configurations are placed in [configs/experiment/](configs/experiment/). ```yaml python run.py +experiment=exp_example_simple ``` @@ -232,8 +212,8 @@ python run.py +experiment=exp_example_simple
Attach some callbacks to run -> *Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).
-Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/).* +> Callbacks can be used for things such as as model checkpointing, early stopping and [many more](https://pytorch-lightning.readthedocs.io/en/latest/extensions/callbacks.html#built-in-callbacks).
+Callbacks configurations are placed in [configs/callbacks/](configs/callbacks/). ```yaml python run.py callbacks=default_callbacks ``` @@ -244,7 +224,7 @@ python run.py callbacks=default_callbacks
Use different tricks available in Pytorch Lightning -> *PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags).* +> PyTorch Lightning provides about [40+ useful trainer flags](https://pytorch-lightning.readthedocs.io/en/latest/common/trainer.html#trainer-flags). ```yaml # gradient clipping may be enabled to avoid exploding gradients python run.py +trainer.gradient_clip_val=0.5 @@ -259,7 +239,6 @@ python run.py +trainer.val_check_interval=0.25 python run.py +trainer.accumulate_grad_batches=10 ``` -
@@ -295,7 +274,7 @@ python run.py +trainer.limit_train_batches=0.2 \ # path should be absolute! python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt" ``` -> *Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.* +> Currently loading ckpt in Lightning doesn't resume logger experiment, but it will be supported in future Lightning release.
@@ -308,7 +287,7 @@ python run.py +trainer.resume_from_checkpoint="/absolute/path/to/ckpt/name.ckpt" # each with different combination of batch_size and learning rate python run.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005 ``` -> *Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.* +> Currently sweeps aren't failure resistant (if one job crashes than the whole sweep crashes), but it will be supported in future Hydra release.
@@ -316,54 +295,47 @@ python run.py -m datamodule.batch_size=32,64,128 optimizer.lr=0.001,0.0005
Create a sweep over hyperparameters with Optuna +> Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a [single config file](configs/config_optuna.yaml)! ```yaml # this will run hyperparameter search defined in `configs/config_optuna.yaml` # over chosen experiment config python run.py -m --config-name config_optuna.yaml +experiment=exp_example_simple ``` -> *Using [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) plugin doesn't require you to code any boilerplate into your pipeline, everything is defined in a single config file!*
Execute all experiments from folder +> Hydra provides special syntax for controlling behavior of multiruns. Learn more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run). The command below executes all experiments from folder [configs/experiment/](configs/experiment/). ```yaml -# execute all experiments from folder `configs/experiment/` python run.py -m '+experiment=glob(*)' ``` -> *Hydra provides special syntax for controlling behavior of multiruns. Read more [here](https://hydra.cc/docs/next/tutorials/basic/running_your_app/multi-run).*
Execute sweep on a remote AWS cluster -> *This should be achievable with simple config using [Ray AWS launcher for Hydra](https://hydra.cc/docs/next/plugins/ray_launcher). Example is not yet implemented in this template.* +> This should be achievable with simple config using [Ray AWS launcher for Hydra](https://hydra.cc/docs/next/plugins/ray_launcher). Example is not yet implemented in this template.
Execute sweep on a Linux SLURM cluster -> *This should be achievable with simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.* +> This should be achievable with simple config using [Submitit launcher for Hydra](https://hydra.cc/docs/plugins/submitit_launcher). Example is not yet implemented in this template.
- +
@@ -416,10 +388,6 @@ print_config: True disable_warnings: False -# disable lightning logs if they annoy you -disable_lightning_logs: False - - # output paths for hydra logs hydra: run: @@ -603,11 +571,47 @@ Take a look at [inference_example.py](src/utils/inference_example.py). ### Callbacks -Template contains example callbacks for better Weights&Biases integration (see [wandb_callbacks.py](src/pl_callbacks/wandb_callbacks.py)).
-To support reproducibility: *UploadCodeToWandbAsArtifact*, *UploadCheckpointsToWandbAsArtifact*, *WatchModelWithWandb*.
-To provide examples of logging custom visualisations with callbacks only: *LogConfusionMatrixToWandb*, *LogF1PrecRecHeatmapToWandb*.
+Template contains example callbacks enabling better Weights&Biases integration, which you can use as a reference for writing your own callbacks (see [wandb_callbacks.py](src/pl_callbacks/wandb_callbacks.py)).
+To support reproducibility: **WatchModelWithWandb**, **UploadCodeToWandbAsArtifact**, **UploadCheckpointsToWandbAsArtifact**.
+To provide examples of logging custom visualisations with callbacks only: **LogConfusionMatrixToWandb**, **LogF1PrecRecHeatmapToWandb**.
+
+ + +### Multi-GPU Training +Lightning supports multiple ways of doing distributed training.
+The most common one is DDP, which spawns separate process for each GPU and averages gradients between them. To learn about other approaches read [lightning docs](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html). + +You can run DDP on mnist example with 4 GPUs like this: +```yaml +python run.py trainer.gpus=4 +trainer.accelerator="ddp" +``` +When using DDP you should remember about a couple of things: +1. Make sure you set `datamodule.num_workers=0` and `datamodule.pin_memory=False`. +2. Use metrics api objects, e.g. `pytorch_lightning.metrics.classification.Accuracy` when logging metrics in `LightningModule`, to ensure proper reduction over multiple GPUs. You can also use `sync_dist` parameter instead with `self.log(..., sync_dist=True)`. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#synchronize-validation-and-test-logging). +3. Remember `outputs` parameters in hooks like `validation_epoch_end()` will contain only outputs from subset of data processed on given GPU. +4. Init tensors using `type_as` and `register_buffer`. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#init-tensors-using-type-as-and-register-buffer). +5. Make sure your model is pickable. Learn more [here](https://pytorch-lightning.readthedocs.io/en/latest/advanced/multi_gpu.html#make-models-pickleable).

+### Extra Features +List of extra utilities available in the template: +- loading environment variables from [.env](.env.tmp) file +- pretty printing config with [Rich](https://github.com/willmcgugan/rich) library +- disabling python warnings +- easier access to debug mode +- forcing debug friendly configuration +- forcing multi-gpu friendly configuration +- method for logging hyperparameters to loggers +- (TODO) resuming latest run + +You can easily remove all of those by modifying [run.py](run.py) and [src/train.py](src/train.py). +

+ + +### How To Speed Up Training +(TODO) +


+ ## Best Practices @@ -638,7 +642,7 @@ Currently template contains configurations of **Black** (python code formatting) To format all files in the project use command: ```yaml -pre-commit run --all-files +pre-commit run -a ```
@@ -712,7 +716,7 @@ from project_name.pl_datamodules.mnist_datamodule import MNISTDataModule ```
- + ## Tricks + ### Accessing Datamodule Attributes In Model The simplest way is to pass datamodule attribute directly to model on initialization: ```python @@ -800,7 +805,7 @@ This template was inspired by: -### DELETE EVERYTHING ABOVE FOR YOUR PROJECT +**DELETE EVERYTHING ABOVE FOR YOUR PROJECT** --- @@ -808,10 +813,10 @@ This template was inspired by: # Your Project Name -PyTorch -Lightning +PyTorch +Lightning Config: Hydra -[![](https://shields.io/badge/-Lightning--Hydra--Template-017F2F?style=flat&logo=github&labelColor=303030)](https://github.com/hobogalaxy/lightning-hydra-template) +Template diff --git a/conda_env_gpu.yaml b/conda_env_gpu.yaml index 7282075..18a45a2 100644 --- a/conda_env_gpu.yaml +++ b/conda_env_gpu.yaml @@ -10,6 +10,5 @@ dependencies: - pip - notebook - cudatoolkit - - pytorch - - torchvision - - torchaudio + - pytorch=1.8.1 + - torchvision=0.9.1 diff --git a/configs/config.yaml b/configs/config.yaml index 219b38e..38f4347 100644 --- a/configs/config.yaml +++ b/configs/config.yaml @@ -10,8 +10,8 @@ defaults: - logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`) # enable color logging - # - override hydra/hydra_logging: colorlog - # - override hydra/job_logging: colorlog + - override hydra/hydra_logging: colorlog + - override hydra/job_logging: colorlog # path to original working directory @@ -20,23 +20,25 @@ defaults: # learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory work_dir: ${hydra:runtime.cwd} + # path to folder with data data_dir: ${work_dir}/data/ + # use `python run.py debug=true` for easy debugging! # this will run 1 train, val and test loop with only 1 batch # equivalent to running `python run.py trainer.fast_dev_run=true` # (this is placed here just for easier access from command line) debug: False + # pretty print config at the start of the run using Rich library print_config: True + # disable python warnings if they annoy you disable_warnings: True -# disable lightning logs if they annoy you -disable_lightning_logs: False hydra: # output paths for hydra logs diff --git a/requirements.txt b/requirements.txt index 55763c1..26a69e3 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,20 +1,20 @@ # --------- pytorch --------- # -torch==1.7.1 -torchvision==0.8.2 +torch==1.8.1 +torchvision==0.9.1 pytorch-lightning>=1.2.5 # --------- hydra --------- # hydra-core==1.1.0.dev5 -hydra_colorlog>=1.0.0 -hydra-optuna-sweeper>=0.9.0rc2 -# hydra-ray-launcher>=0.1.2 +hydra-colorlog==1.0.0 +hydra-optuna-sweeper==0.9.0rc2 +# hydra-ray-launcher==0.1.2 +# hydra-submitit-launcher==1.1.0 # --------- loggers --------- # wandb>=0.10.20 # neptune-client # comet_ml # mlflow -# tensorboard # --------- others --------- # rich diff --git a/run.py b/run.py index 410416b..cd700e7 100644 --- a/run.py +++ b/run.py @@ -3,6 +3,7 @@ import hydra from omegaconf import DictConfig # load environment variables from `.env` file if it exists +# recursively searches for `.env` in all folders starting from work dir dotenv.load_dotenv(override=True) @@ -16,9 +17,9 @@ def main(config: DictConfig): # A couple of optional utilities: # - disabling python warnings - # - disabling lightning logs # - easier access to debug mode # - forcing debug friendly configuration + # - forcing multi-gpu friendly configuration # You can safely get rid of this line if you don't want those template_utils.extras(config) diff --git a/src/pl_callbacks/wandb_callbacks.py b/src/pl_callbacks/wandb_callbacks.py index 5ef89fc..1f5d3fd 100644 --- a/src/pl_callbacks/wandb_callbacks.py +++ b/src/pl_callbacks/wandb_callbacks.py @@ -22,11 +22,22 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger: return logger raise Exception( - "You are using wandb related callback," - "but WandbLogger was not found for some reason..." + "You are using wandb related callback, but WandbLogger was not found for some reason..." ) +class WatchModelWithWandb(Callback): + """Make WandbLogger watch model at the beginning of the run.""" + + def __init__(self, log: str = "gradients", log_freq: int = 100): + self.log = log + self.log_freq = log_freq + + def on_train_start(self, trainer, pl_module): + logger = get_wandb_logger(trainer=trainer) + logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq) + + class UploadCodeToWandbAsArtifact(Callback): """Upload all *.py files to wandb as an artifact, at the beginning of the run.""" @@ -60,26 +71,12 @@ class UploadCheckpointsToWandbAsArtifact(Callback): if self.upload_best_only: ckpts.add_file(trainer.checkpoint_callback.best_model_path) else: - for path in glob.glob( - os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True - ): + for path in glob.glob(os.path.join(self.ckpt_dir, "**/*.ckpt"), recursive=True): ckpts.add_file(path) experiment.use_artifact(ckpts) -class WatchModelWithWandb(Callback): - """Make WandbLogger watch model at the beginning of the run.""" - - def __init__(self, log: str = "gradients", log_freq: int = 100): - self.log = log - self.log_freq = log_freq - - def on_train_start(self, trainer, pl_module): - logger = get_wandb_logger(trainer=trainer) - logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq) - - class LogConfusionMatrixToWandb(Callback): """Generate confusion matrix every epoch and send it to wandb. Expects validation step to return predictions and targets. @@ -126,9 +123,7 @@ class LogConfusionMatrixToWandb(Callback): sn.heatmap(confusion_matrix, annot=True, annot_kws={"size": 8}, fmt="g") # names should be uniqe or else charts from different experiments in wandb will overlap - experiment.log( - {f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False - ) + experiment.log({f"confusion_matrix/{experiment.name}": wandb.Image(plt)}, commit=False) # according to wandb docs this should also work but it crashes # experiment.log(f{"confusion_matrix/{experiment.name}": plt}) @@ -194,9 +189,7 @@ class LogF1PrecRecHeatmapToWandb(Callback): ) # names should be uniqe or else charts from different experiments in wandb will overlap - experiment.log( - {f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False - ) + experiment.log({f"f1_p_r_heatmap/{experiment.name}": wandb.Image(plt)}, commit=False) # reset plot plt.clf() diff --git a/src/pl_models/mnist_model.py b/src/pl_models/mnist_model.py index 1b2286e..7c4711c 100644 --- a/src/pl_models/mnist_model.py +++ b/src/pl_models/mnist_model.py @@ -105,9 +105,7 @@ class MNISTLitModel(LightningModule): def training_epoch_end(self, outputs: List[Any]) -> None: # log best so far train acc and train loss self.metric_hist["train/acc"].append(self.trainer.callback_metrics["train/acc"]) - self.metric_hist["train/loss"].append( - self.trainer.callback_metrics["train/loss"] - ) + self.metric_hist["train/loss"].append(self.trainer.callback_metrics["train/loss"]) self.log("train/acc_best", max(self.metric_hist["train/acc"]), prog_bar=False) self.log("train/loss_best", min(self.metric_hist["train/loss"]), prog_bar=False) @@ -133,7 +131,5 @@ class MNISTLitModel(LightningModule): https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers """ - optim = hydra.utils.instantiate( - self.hparams.optimizer, params=self.parameters() - ) + optim = hydra.utils.instantiate(self.hparams.optimizer, params=self.parameters()) return optim diff --git a/src/utils/template_utils.py b/src/utils/template_utils.py index 2afcca6..9a729a7 100644 --- a/src/utils/template_utils.py +++ b/src/utils/template_utils.py @@ -16,48 +16,45 @@ log = logging.getLogger(__name__) def extras(config: DictConfig) -> None: """A couple of optional utilities, controlled by main config file. - disabling warnings - - disabling lightning logs - easier access to debug mode - forcing debug friendly configuration + - forcing multi-gpu friendly configuration Args: config (DictConfig): [description] """ - # Enable adding new keys to config + # enable adding new keys to config OmegaConf.set_struct(config, False) - # Fix double logging bug (this will be removed when lightning releases patch) - pl_logger = logging.getLogger("lightning") - pl_logger.propagate = False - - # [OPTIONAL] Disable python warnings if + # disable python warnings if if config.get("disable_warnings"): - log.info(f"Disabling python warnings! <{config.disable_warnings=}>") + log.info(f"Disabling python warnings! - if config.get("disable_lightning_logs"): - log.info(f"Disabling lightning logs! {config.disable_lightning_logs=}>") - logging.getLogger("lightning").setLevel(logging.ERROR) - - # [OPTIONAL] Set if + # set if if config.get("debug"): - log.info(f"Running in debug mode! <{config.debug=}>") + log.info("Running in debug mode! ") config.trainer.fast_dev_run = True - # [OPTIONAL] Force debugger friendly configuration if + # force debugger friendly configuration if if config.trainer.get("fast_dev_run"): - log.info( - f"Forcing debugger friendly configuration! " - f"<{config.trainer.fast_dev_run=}>" - ) + log.info("Forcing debugger friendly configuration! ") # 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 + + # force multi-gpu friendly configuration if + if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]: + log.info("Forcing ddp friendly configuration! ") + # ddp doesn't like num_workers>0 or pin_memory=True + if config.datamodule.get("num_workers"): + config.datamodule.num_workers = 0 + if config.datamodule.get("pin_memory"): + config.datamodule.pin_memory = False - # Disable adding new keys to config + # disable adding new keys to config OmegaConf.set_struct(config, True) @@ -99,6 +96,10 @@ def print_config( print(tree) +def empty(*args, **kwargs): + pass + + def log_hyperparameters( config: DictConfig, model: pl.LightningModule, @@ -127,8 +128,9 @@ def log_hyperparameters( # 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 "optimizer" in config: + hparams["optimizer"] = config["optimizer"] if "callbacks" in config: hparams["callbacks"] = config["callbacks"] @@ -156,7 +158,7 @@ def log_hyperparameters( # disable logging any more hyperparameters for all loggers # (this is just a trick to prevent trainer from logging hparams of model, since we already did that above) - trainer.logger.log_hyperparams = lambda params: None + trainer.logger.log_hyperparams = empty def finish(