diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index eae864a..0000000 --- a/Dockerfile +++ /dev/null @@ -1,57 +0,0 @@ -# Build: sudo docker build -t . -# Run: sudo docker run -v $(pwd):/workspace/project --gpus all -it --rm - - -FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04 - - -ENV CONDA_ENV_NAME=myenv -ENV PYTHON_VERSION=3.8 - - -# Basic setup -RUN apt update -RUN apt install -y bash \ - build-essential \ - git \ - curl \ - ca-certificates \ - wget \ - && rm -rf /var/lib/apt/lists - - -# Set working directory -WORKDIR /workspace/project - - -# Install Miniconda and create main env -ADD https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh miniconda3.sh -RUN /bin/bash miniconda3.sh -b -p /conda \ - && echo export PATH=/conda/bin:$PATH >> .bashrc \ - && rm miniconda3.sh -ENV PATH="/conda/bin:${PATH}" -RUN conda create -n ${CONDA_ENV_NAME} python=${PYTHON_VERSION} - - -# Switch to bash shell -SHELL ["/bin/bash", "-c"] - - -# Install requirements -COPY requirements.txt ./ -RUN source activate ${CONDA_ENV_NAME} \ - && pip install --no-cache-dir -r requirements.txt \ - && rm requirements.txt - - -# Uncomment this to install Apex for mixed-precision support -# RUN source activate ${CONDA_ENV_NAME} \ -# && git clone https://github.com/NVIDIA/apex \ -# && cd apex \ -# && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ \ -# && cd .. \ -# && rm -r apex - - -# Set ${CONDA_ENV_NAME} to default virutal environment -RUN echo "source activate ${CONDA_ENV_NAME}" >> ~/.bashrc diff --git a/README.md b/README.md index ffc157b..390991a 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,6 @@ The directory structure of new project looks like this: ├── .gitignore <- List of files/folders ignored by git ├── .pre-commit-config.yaml <- Configuration of automatic code formatting ├── setup.cfg <- Configurations of linters and pytest -├── Dockerfile <- File for building docker container ├── requirements.txt <- File for installing python dependencies └── README.md ``` @@ -197,7 +196,7 @@ python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
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, like Tensorboard, Neptune or simple csv files. 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.
**Click [here](https://wandb.ai/hobglob/template-dashboard/) to see example wandb dashboard generated with this template.** ```yaml # set project and entity names in `configs/logger/wandb` @@ -207,8 +206,7 @@ wandb: ``` ```yaml -# train model with Weights&Biases -# link to wandb dashboard should appear in the terminal +# train model with Weights&Biases (link to wandb dashboard should appear in the terminal) python run.py logger=wandb ``` @@ -216,14 +214,16 @@ python run.py logger=wandb
-Use different logging modes +Use different running modes ```yaml # debug mode changes logging folder to `logs/debug/` +# also enables default trainer debugging options from `configs/trainer/debug.yaml` +# also sets level of all command line loggers to 'DEBUG' python run.py mode=debug # experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/` -# also sets custom experiment name in the logger +# name is also used by experiment loggers (like tensorboard or wandb) python run.py mode=exp name='my_new_experiment_253' ``` @@ -287,15 +287,16 @@ python run.py +trainer.fast_dev_run=true # print full weight summary of all PyTorch modules python run.py trainer.weights_summary="full" -# print execution time profiling after training ends -python run.py +trainer.profiler="simple" - # raise exception, if any of the parameters or the loss are NaN or +/-inf python run.py +trainer.terminate_on_nan=true -# Quick debug with all the previous options enabled +# quick debug with all the previous options enabled +# (this is also enabled when using `python run.py mode=debug`) python run.py trainer=debug +# print execution time profiling after training ends +python run.py +trainer.profiler="simple" + # try overfitting to 1 batch python run.py +trainer.overfit_batches=1 trainer.max_epochs=20 @@ -383,7 +384,10 @@ python run.py -m 'experiment=glob(*)' ## 🐳  Docker First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
-To build the container from provided Dockerfile use: + +The template Dockerfile is provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). Copy it to the template root folder. + +To build the container use: ```bash docker build -t . ``` @@ -800,6 +804,11 @@ To provide examples of logging custom visualisations with callbacks only: - **LogF1PrecRecHeatmap** - **LogImagePredictions** +To try all of the callbacks at once, use: +```yaml +python run.py logger=wandb callbacks=wandb +``` + To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).

@@ -1082,11 +1091,10 @@ conda activate myenv eval "$(python run.py -sc install=bash)" # enable aliases for debugging -alias test='pytest' -alias debug1='python run.py mode=debug' -alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.gpus=1 trainer.max_epochs=1' -alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.gpus=1 trainer.max_epochs=1 +trainer.limit_train_batches=0.1' -alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.gpus=1 trainer.max_epochs=1 logger=wandb logger.wandb.project=tests' +alias debug='python run.py mode=debug' +alias debug2='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=0' +alias debug3='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1' +alias debug_wandb='python run.py mode=debug trainer.fast_dev_run=false trainer.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests' ``` (these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file) diff --git a/configs/config.yaml b/configs/config.yaml index 1b96911..ffa7daf 100644 --- a/configs/config.yaml +++ b/configs/config.yaml @@ -21,7 +21,7 @@ defaults: # path to original working directory # hydra hijacks working directory by changing it to the current log directory, # so it's useful to have this path as a special variable -# learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory +# https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory work_dir: ${hydra:runtime.cwd} # path to folder with data diff --git a/configs/mode/debug.yaml b/configs/mode/debug.yaml index 2cfb62c..db12125 100644 --- a/configs/mode/debug.yaml +++ b/configs/mode/debug.yaml @@ -3,13 +3,25 @@ # run in debug mode with: # `python run.py mode=debug` -# this flag doesn't really do anything -debug: true +defaults: + - override /trainer: debug.yaml + +debug_mode: True -# output paths for debug mode hydra: + # sets level of all command line loggers to 'DEBUG' + verbose: True + + # https://hydra.cc/docs/tutorials/basic/running_your_app/logging/ + # sets level of only chosen command line loggers to 'DEBUG' + # verbose: [src.train, src.utils.utils] + + # sets output paths for all file logs to 'logs/debug/' run: dir: logs/debug/${now:%Y-%m-%d}/${now:%H-%M-%S} sweep: dir: logs/debug/multirun_${now:%Y-%m-%d_%H-%M-%S} subdir: ${hydra.job.num} + +# disable rich config printing, since it will be already printed by hydra when `verbose: True` +print_config: False diff --git a/configs/mode/default.yaml b/configs/mode/default.yaml index 65336fa..3995570 100644 --- a/configs/mode/default.yaml +++ b/configs/mode/default.yaml @@ -2,8 +2,10 @@ # default running mode -# default output paths for hydra logs +default_mode: True + hydra: + # default output paths for all file logs run: dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} sweep: diff --git a/configs/mode/exp.yaml b/configs/mode/exp.yaml index f465877..4035a7d 100644 --- a/configs/mode/exp.yaml +++ b/configs/mode/exp.yaml @@ -1,13 +1,15 @@ # @package _global_ # run in experiment mode with: -# python run.py mode=exp name='my_new_experiment_23' +# `python run.py mode=exp name=experiment_name` + +experiment_mode: True # allows for custom naming of the experiment name: ??? -# output paths for experiment mode hydra: + # sets output paths for all file logs to `logs/experiment/name' run: dir: logs/experiments/${name} sweep: diff --git a/configs/trainer/debug.yaml b/configs/trainer/debug.yaml index e729b6e..18b73ed 100644 --- a/configs/trainer/debug.yaml +++ b/configs/trainer/debug.yaml @@ -9,7 +9,7 @@ max_epochs: 2 # prints progress_bar_refresh_rate: null weights_summary: "full" -profiler: "simple" +profiler: null # debugs fast_dev_run: true diff --git a/run.py b/run.py index 03e3ff9..0410199 100644 --- a/run.py +++ b/run.py @@ -17,8 +17,8 @@ def main(config: DictConfig): # A couple of optional utilities: # - disabling python warnings - # - easier access to debug mode - # - forcing debug friendly configuration + # - forcing debug-friendly configuration + # - verifying experiment name is set when running in experiment mode # You can safely get rid of this line if you don't want those utils.extras(config) diff --git a/src/datamodules/mnist_datamodule.py b/src/datamodules/mnist_datamodule.py index 07aa878..577cf61 100644 --- a/src/datamodules/mnist_datamodule.py +++ b/src/datamodules/mnist_datamodule.py @@ -1,5 +1,6 @@ from typing import Optional, Tuple +import torch from pytorch_lightning import LightningDataModule from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split from torchvision.datasets import MNIST @@ -62,13 +63,18 @@ class MNISTDataModule(LightningDataModule): MNIST(self.data_dir, train=False, download=True) def setup(self, stage: Optional[str] = None): - """Load data. Set variables: self.data_train, self.data_val, self.data_test.""" + """Load data. Set variables: self.data_train, self.data_val, self.data_test. + This method is called by lightning separately when using `trainer.fit()` and `trainer.test()`! + The `stage` can be used to differentiate whether the `setup()` is called before trainer.fit()` or `trainer.test()`.""" trainset = MNIST(self.data_dir, train=True, transform=self.transforms) testset = MNIST(self.data_dir, train=False, transform=self.transforms) dataset = ConcatDataset(datasets=[trainset, testset]) self.data_train, self.data_val, self.data_test = random_split( - dataset, self.train_val_test_split + dataset, self.train_val_test_split, generator=torch.Generator().manual_seed(42) ) + # always use generator seed in `random_split()` or else the test data + # might leak to train data when `setup()` is called the second time! + # alternatively, you can set the test dataset and train dataset separately for each stage def train_dataloader(self): return DataLoader( diff --git a/src/train.py b/src/train.py index 40f0fdd..39e38dd 100644 --- a/src/train.py +++ b/src/train.py @@ -93,7 +93,8 @@ def train(config: DictConfig) -> Optional[float]: ) # Print path to best checkpoint - log.info(f"Best checkpoint path:\n{trainer.checkpoint_callback.best_model_path}") + if not config.trainer.get("fast_dev_run"): + log.info(f"Best model ckpt: {trainer.checkpoint_callback.best_model_path}") # Return metric score for hyperparameter optimization optimized_metric = config.get("optimized_metric") diff --git a/src/utils/utils.py b/src/utils/utils.py index 79276f7..3e4aaaa 100644 --- a/src/utils/utils.py +++ b/src/utils/utils.py @@ -1,5 +1,4 @@ import logging -import os import warnings from typing import List, Sequence @@ -10,11 +9,10 @@ from omegaconf import DictConfig, OmegaConf from pytorch_lightning.utilities import rank_zero_only -def get_logger(name=__name__, level=logging.INFO) -> logging.Logger: +def get_logger(name=__name__) -> logging.Logger: """Initializes multi-GPU-friendly python logger.""" logger = logging.getLogger(name) - logger.setLevel(level) # this ensures all logging levels get marked with the rank zero decorator # otherwise logs would get multiplied for each GPU process in multi-GPU setup @@ -27,8 +25,8 @@ def get_logger(name=__name__, level=logging.INFO) -> logging.Logger: def extras(config: DictConfig) -> None: """A couple of optional utilities, controlled by main config file: - disabling warnings - - easier access to debug mode - forcing debug friendly configuration + - verifying experiment name is set when running in experiment mode Modifies DictConfig in place. @@ -36,24 +34,26 @@ def extras(config: DictConfig) -> None: config (DictConfig): Configuration composed by Hydra. """ - log = get_logger() - - # enable adding new keys to config - OmegaConf.set_struct(config, False) + log = get_logger(__name__) # disable python warnings if if config.get("ignore_warnings"): log.info("Disabling python warnings! ") warnings.filterwarnings("ignore") - # if - if config.get("name"): - log.info("Running in experiment mode! Name: {}".format(config.name)) + # verify experiment name is set when running in experiment mode + if config.get("experiment_mode") and not config.get("name"): + log.info( + "Running in experiment mode without the experiment name specified! " + "Use `python run.py mode=exp name=experiment_name`" + ) + log.info("Exiting...") + exit() # force debugger friendly configuration if + # debuggers don't like GPUs and multiprocessing if config.trainer.get("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("pin_memory"): @@ -61,9 +61,6 @@ def extras(config: DictConfig) -> None: if config.datamodule.get("num_workers"): config.datamodule.num_workers = 0 - # disable adding new keys to config - OmegaConf.set_struct(config, True) - @rank_zero_only def print_config(