* make debug mode automatically set level of all command line loggers to `DEBUG`
* make debug mode automatically set the trainer config to `debug.yaml`
* add generator seed to fix test data leaking to train data in datamodule `setup()`
* move Dockerfile to `dockerfiles` branch
* update README.md
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-10-12 15:32:19 +02:00
1 parent e34ccb0acf
commit eee3f9ccd3
11 files changed
+72 -101

No files matched your search

-57
View File
@@ -1,57 +0,0 @@
# Build: sudo docker build -t <project_name> .
# Run: sudo docker run -v $(pwd):/workspace/project --gpus all -it --rm <project_name>
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
+24 -16
View File
@@ -108,7 +108,6 @@ The directory structure of new project looks like this:
├── .gitignore <- List of files/folders ignored by git ├── .gitignore <- List of files/folders ignored by git
├── .pre-commit-config.yaml <- Configuration of automatic code formatting ├── .pre-commit-config.yaml <- Configuration of automatic code formatting
├── setup.cfg <- Configurations of linters and pytest ├── setup.cfg <- Configurations of linters and pytest
├── Dockerfile <- File for building docker container
├── requirements.txt <- File for installing python dependencies ├── requirements.txt <- File for installing python dependencies
└── README.md └── README.md
``` ```
@@ -197,7 +196,7 @@ python run.py trainer.gpus=1 +trainer.amp_backend="apex" +trainer.precision=16 \
<details> <details>
<summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases</b></summary> <summary><b>Train model with any logger available in PyTorch Lightning, like Weights&Biases</b></summary>
> 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.<br> > 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.<br>
**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.**
```yaml ```yaml
# set project and entity names in `configs/logger/wandb` # set project and entity names in `configs/logger/wandb`
@@ -207,8 +206,7 @@ wandb:
``` ```
```yaml ```yaml
# train model with Weights&Biases # train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
# link to wandb dashboard should appear in the terminal
python run.py logger=wandb python run.py logger=wandb
``` ```
@@ -216,14 +214,16 @@ python run.py logger=wandb
<details> <details>
<summary><b>Use different logging modes</b></summary> <summary><b>Use different running modes</b></summary>
```yaml ```yaml
# debug mode changes logging folder to `logs/debug/` # 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 python run.py mode=debug
# experiment mode changes logging folder to `logs/experiments/name_of_your_experiment/` # 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' 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 # print full weight summary of all PyTorch modules
python run.py trainer.weights_summary="full" 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 # raise exception, if any of the parameters or the loss are NaN or +/-inf
python run.py +trainer.terminate_on_nan=true 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 python run.py trainer=debug
# print execution time profiling after training ends
python run.py +trainer.profiler="simple"
# try overfitting to 1 batch # try overfitting to 1 batch
python run.py +trainer.overfit_batches=1 trainer.max_epochs=20 python run.py +trainer.overfit_batches=1 trainer.max_epochs=20
@@ -383,7 +384,10 @@ python run.py -m 'experiment=glob(*)'
## 🐳&nbsp;&nbsp;Docker ## 🐳&nbsp;&nbsp;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. <br> 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. <br>
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 ```bash
docker build -t <project_name> . docker build -t <project_name> .
``` ```
@@ -800,6 +804,11 @@ To provide examples of logging custom visualisations with callbacks only:
- **LogF1PrecRecHeatmap** - **LogF1PrecRecHeatmap**
- **LogImagePredictions** - **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). To see the result of all the callbacks attached, take a look at [this experiment dashboard](https://wandb.ai/hobglob/template-tests/runs/3rw7q70h).
<br><br> <br><br>
@@ -1082,11 +1091,10 @@ conda activate myenv
eval "$(python run.py -sc install=bash)" eval "$(python run.py -sc install=bash)"
# enable aliases for debugging # enable aliases for debugging
alias test='pytest' alias debug='python run.py mode=debug'
alias debug1='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 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.max_epochs=1 trainer.gpus=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.max_epochs=1 trainer.gpus=1 logger=wandb logger.wandb.project=tests'
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'
``` ```
(these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file) (these commands will be executed whenever you're openning or switching terminal to folder containing `.autoenv` file)
+1 -1
View File
@@ -21,7 +21,7 @@ defaults:
# path to original working directory # path to original working directory
# hydra hijacks working directory by changing it to the current log 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 # 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} work_dir: ${hydra:runtime.cwd}
# path to folder with data # path to folder with data
+15 -3
View File
@@ -3,13 +3,25 @@
# run in debug mode with: # run in debug mode with:
# `python run.py mode=debug` # `python run.py mode=debug`
# this flag doesn't really do anything defaults:
debug: true - override /trainer: debug.yaml
debug_mode: True
# output paths for debug mode
hydra: 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: run:
dir: logs/debug/${now:%Y-%m-%d}/${now:%H-%M-%S} dir: logs/debug/${now:%Y-%m-%d}/${now:%H-%M-%S}
sweep: sweep:
dir: logs/debug/multirun_${now:%Y-%m-%d_%H-%M-%S} dir: logs/debug/multirun_${now:%Y-%m-%d_%H-%M-%S}
subdir: ${hydra.job.num} subdir: ${hydra.job.num}
# disable rich config printing, since it will be already printed by hydra when `verbose: True`
print_config: False
+3 -1
View File
@@ -2,8 +2,10 @@
# default running mode # default running mode
# default output paths for hydra logs default_mode: True
hydra: hydra:
# default output paths for all file logs
run: run:
dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S}
sweep: sweep:
+4 -2
View File
@@ -1,13 +1,15 @@
# @package _global_ # @package _global_
# run in experiment mode with: # 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 # allows for custom naming of the experiment
name: ??? name: ???
# output paths for experiment mode
hydra: hydra:
# sets output paths for all file logs to `logs/experiment/name'
run: run:
dir: logs/experiments/${name} dir: logs/experiments/${name}
sweep: sweep:
+1 -1
View File
@@ -9,7 +9,7 @@ max_epochs: 2
# prints # prints
progress_bar_refresh_rate: null progress_bar_refresh_rate: null
weights_summary: "full" weights_summary: "full"
profiler: "simple" profiler: null
# debugs # debugs
fast_dev_run: true fast_dev_run: true
+2 -2
View File
@@ -17,8 +17,8 @@ def main(config: DictConfig):
# A couple of optional utilities: # A couple of optional utilities:
# - disabling python warnings # - 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 # You can safely get rid of this line if you don't want those
utils.extras(config) utils.extras(config)
+8 -2
View File
@@ -1,5 +1,6 @@
from typing import Optional, Tuple from typing import Optional, Tuple
import torch
from pytorch_lightning import LightningDataModule from pytorch_lightning import LightningDataModule
from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split from torch.utils.data import ConcatDataset, DataLoader, Dataset, random_split
from torchvision.datasets import MNIST from torchvision.datasets import MNIST
@@ -62,13 +63,18 @@ class MNISTDataModule(LightningDataModule):
MNIST(self.data_dir, train=False, download=True) MNIST(self.data_dir, train=False, download=True)
def setup(self, stage: Optional[str] = None): 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) trainset = MNIST(self.data_dir, train=True, transform=self.transforms)
testset = MNIST(self.data_dir, train=False, transform=self.transforms) testset = MNIST(self.data_dir, train=False, transform=self.transforms)
dataset = ConcatDataset(datasets=[trainset, testset]) dataset = ConcatDataset(datasets=[trainset, testset])
self.data_train, self.data_val, self.data_test = random_split( 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): def train_dataloader(self):
return DataLoader( return DataLoader(
+2 -1
View File
@@ -93,7 +93,8 @@ def train(config: DictConfig) -> Optional[float]:
) )
# Print path to best checkpoint # 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 # Return metric score for hyperparameter optimization
optimized_metric = config.get("optimized_metric") optimized_metric = config.get("optimized_metric")
+12 -15
View File
@@ -1,5 +1,4 @@
import logging import logging
import os
import warnings import warnings
from typing import List, Sequence from typing import List, Sequence
@@ -10,11 +9,10 @@ from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.utilities import rank_zero_only 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.""" """Initializes multi-GPU-friendly python logger."""
logger = logging.getLogger(name) logger = logging.getLogger(name)
logger.setLevel(level)
# this ensures all logging levels get marked with the rank zero decorator # 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 # 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: def extras(config: DictConfig) -> None:
"""A couple of optional utilities, controlled by main config file: """A couple of optional utilities, controlled by main config file:
- disabling warnings - disabling warnings
- easier access to debug mode
- forcing debug friendly configuration - forcing debug friendly configuration
- verifying experiment name is set when running in experiment mode
Modifies DictConfig in place. Modifies DictConfig in place.
@@ -36,24 +34,26 @@ def extras(config: DictConfig) -> None:
config (DictConfig): Configuration composed by Hydra. config (DictConfig): Configuration composed by Hydra.
""" """
log = get_logger() log = get_logger(__name__)
# enable adding new keys to config
OmegaConf.set_struct(config, False)
# disable python warnings if <config.ignore_warnings=True> # disable python warnings if <config.ignore_warnings=True>
if config.get("ignore_warnings"): if config.get("ignore_warnings"):
log.info("Disabling python warnings! <config.ignore_warnings=True>") log.info("Disabling python warnings! <config.ignore_warnings=True>")
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
# if <config.name=...> # verify experiment name is set when running in experiment mode
if config.get("name"): if config.get("experiment_mode") and not config.get("name"):
log.info("Running in experiment mode! Name: {}".format(config.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 <config.trainer.fast_dev_run=True> # force debugger friendly configuration if <config.trainer.fast_dev_run=True>
# debuggers don't like GPUs and multiprocessing
if config.trainer.get("fast_dev_run"): if config.trainer.get("fast_dev_run"):
log.info("Forcing debugger friendly configuration! <config.trainer.fast_dev_run=True>") log.info("Forcing debugger friendly configuration! <config.trainer.fast_dev_run=True>")
# Debuggers don't like GPUs or multiprocessing
if config.trainer.get("gpus"): if config.trainer.get("gpus"):
config.trainer.gpus = 0 config.trainer.gpus = 0
if config.datamodule.get("pin_memory"): if config.datamodule.get("pin_memory"):
@@ -61,9 +61,6 @@ def extras(config: DictConfig) -> None:
if config.datamodule.get("num_workers"): if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0 config.datamodule.num_workers = 0
# disable adding new keys to config
OmegaConf.set_struct(config, True)
@rank_zero_only @rank_zero_only
def print_config( def print_config(