Release/0.9 (#141)

* add flake8 and prettier to pre-commit-config
* add setup.cfg
* add workers=True to seed_everything()
* update lightning badge logo
* bump package versions
* update README.md
* add __init__.py files
* add more logger configs parameters
* add default Dockerfile
* change .env.template to .env.example
* move inference example to readme
* remove img_dataset.py
* simplify names of wandb callbacks
* remove wandb test marker
* format files with prettier
This commit is contained in:
Łukasz Zalewski authored and GitHub committed 2021-05-21 09:26:31 +02:00
1 parent 023d4bdecc
commit 70ab061f75
46 files changed
+312 -254

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# this is example of the file that can be used for storing private and user specific environment variables, like keys or system paths
# create a file named .env (by default .env will be excluded from version control)
# the variables declared in .env are loaded in run.py automatically
# hydra allows you to reference variables in .yaml configs with special syntax: ${oc.env:MY_VAR}
MY_VAR="/home/user/my/system/path"
MY_KEY="asdgjhawi8y23ihsghsueity23ihwd"
-8
View File
@@ -1,8 +0,0 @@
# this a template of the file that can be used for storing private and user specific environment variables, like keys or system paths
# create a file named .env
# by default .env will be excluded from version control
# the variables declared in .env are loaded automatically in run.py
MY_VAR="/home/user/my/system/path"
MY_KEY="asdgjhawi8y23ihsghsueity23ihwd"
+21 -21
View File
@@ -2,39 +2,39 @@ default_language_version:
python: python3.8 python: python3.8
repos: repos:
# Pre-commit hooks
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0 rev: v3.4.0
hooks: hooks:
# list of supported hooks: https://pre-commit.com/hooks.html # list of supported hooks: https://pre-commit.com/hooks.html
- id: trailing-whitespace - id: trailing-whitespace
- id: debug-statements - id: end-of-file-fixer
- id: detect-private-key
- id: check-yaml - id: check-yaml
- id: check-added-large-files - id: check-added-large-files
- id: debug-statements
- id: detect-private-key
# Black (code formatting) # python code formatting
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 20.8b1 rev: 20.8b1
hooks: hooks:
- id: black - id: black
args: [ args: [--line-length, "99"]
--line-length, "99",
# --exclude, src/train.py,
]
# Isort (import sorting) # python import sorting
- repo: https://github.com/PyCQA/isort - repo: https://github.com/PyCQA/isort
rev: 5.7.0 rev: 5.8.0
hooks: hooks:
- id: isort - id: isort
# profiles: https://pycqa.github.io/isort/docs/configuration/profiles/
# other flags: https://pycqa.github.io/isort/docs/configuration/options/ # yaml formatting
args: [ - repo: https://github.com/pre-commit/mirrors-prettier
--profile, black, rev: v2.3.0
--skip, src/train.py, hooks:
--skip, run.py, - id: prettier
--filter-files, types: [yaml]
]
# files: "src/.*" # python code analysis
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
hooks:
- id: flake8
+22
View File
@@ -0,0 +1,22 @@
# Build: docker build -t project_name .
# Run: docker run --gpus all -it --rm project_name
# Build from official Nvidia PyTorch image
# GPU-ready with Apex for mixed-precision support
# https://ngc.nvidia.com/catalog/containers/nvidia:pytorch
# https://docs.nvidia.com/deeplearning/frameworks/support-matrix/
FROM nvcr.io/nvidia/pytorch:21.03-py3
# Copy all files
ADD . /workspace/project
WORKDIR /workspace/project
# Create myenv
RUN conda env create -f conda_env_gpu.yaml -n myenv
RUN conda init bash
# Set myenv to default virtual environment
RUN echo "source activate myenv" >> ~/.bashrc
+93 -34
View File
@@ -2,14 +2,13 @@
# Lightning-Hydra-Template # Lightning-Hydra-Template
<!--
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/python-3.6%20%7C%203.7%20%7C%203.8-blue?logo=python&logoColor=white&style=for-the-badge"></a> <a href="https://pytorch.org/get-started/locally/"><img alt="Python" src="https://img.shields.io/badge/-Python 3.7--3.9-blue?style=for-the-badge&logo=python&logoColor=white"></a>
--> <a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch 1.8+-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"></a>
<a href="https://pytorch.org/get-started/locally/"><img alt="PyTorch" src="https://img.shields.io/badge/-PyTorch-ee4c2c?style=for-the-badge&logo=pytorch&logoColor=white"></a> <a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?style=for-the-badge&logo=pytorchlightning&logoColor=white"></a>
<a href="https://pytorchlightning.ai/"><img alt="Lightning" src="https://img.shields.io/badge/-Lightning-792ee5?style=for-the-badge"></a> <a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra-89b8cd?style=for-the-badge&labelColor=gray"></a>
<a href="https://hydra.cc/"><img alt="Config: hydra" src="https://img.shields.io/badge/config-hydra-89b8cd?style=for-the-badge"></a> <a href="https://black.readthedocs.io/en/stable/"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge&labelColor=gray"></a>
<a href="https://hub.docker.com/r/ashlev/lightning-hydra"><img alt="Docker" src="https://img.shields.io/badge/docker-257bd6?style=for-the-badge&logo=docker&logoColor=white"></a> <!-- <a href="https://hub.docker.com/r/ashlev/lightning-hydra"><img alt="Docker" src="https://img.shields.io/badge/docker-257bd6?style=for-the-badge&logo=docker&logoColor=white"></a> -->
<a href="https://black.readthedocs.io/en/stable/"><img alt="Code style: black" src="https://img.shields.io/badge/code%20style-black-black.svg?style=for-the-badge"></a>
A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br> A clean and scalable template to kickstart your deep learning project 🚀⚡🔥<br>
Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository. Click on [<kbd>Use this template</kbd>](https://github.com/ashleve/lightning-hydra-template/generate) to initialize new repository.
@@ -87,26 +86,26 @@ The directory structure of new project looks like this:
│ `1.0-jqp-initial-data-exploration.ipynb`. │ `1.0-jqp-initial-data-exploration.ipynb`.
│ │
├── tests <- Tests of any kind ├── tests <- Tests of any kind
│ ├── smoke_tests │ ├── smoke
│ └── unit_tests │ └── unit
│ │
├── src ├── src
│ ├── callbacks <- Lightning callbacks │ ├── callbacks <- Lightning callbacks
│ ├── datamodules <- Lightning datamodules │ ├── datamodules <- Lightning datamodules
│ ├── models <- Lightning models │ ├── models <- Lightning models
│ ├── utils <- Utility scripts │ ├── utils <- Utility scripts
│ │ ├── inference_example.py <- Example of inference with trained model
│ │ └── utils.py <- Extra features for the template
│ │ │ │
│ └── train.py <- Training pipeline │ └── train.py <- Training pipeline
│ │
├── run.py <- Run any pipeline with chosen experiment configuration ├── run.py <- Run any pipeline with chosen experiment configuration
│ │
├── .env.template <- Template of file for storing private environment variables ├── .env.example <- Template of the file for storing private environment variables
├── .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
├── conda_env_gpu.yaml <- File for installing conda environment ├── conda_env_gpu.yaml <- File for installing conda environment
├── Dockerfile <- File for building docker container
├── requirements.txt <- File for installing python dependencies ├── requirements.txt <- File for installing python dependencies
├── setup.cgf <- Configurations of linters and pytest
├── LICENSE ├── LICENSE
└── README.md └── README.md
``` ```
@@ -364,21 +363,15 @@ python run.py -m 'experiment=glob(*)'
## 🐳&nbsp;&nbsp;Docker ## 🐳&nbsp;&nbsp;Docker
I recommend the official [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags) (size: 6GB, it comes with installed Apex for mixed-precision training), or "devel" version of [pytorch/pytorch](https://hub.docker.com/r/pytorch/pytorch). I recommend the official [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags).
To build the container from provided Dockerfile use:
Custom dockerfiles for the template are provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). You can use them as a starting point for building your own images.
```yaml ```yaml
# download image docker build -t project_name .
docker pull nvcr.io/nvidia/pytorch:21.03-py3 docker run --gpus all -it --rm project_name
# run container from image with GPUs enabled
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
``` ```
<!--
# run container with mounted volume Others dockerfiles are provided on branch [`dockerfiles`](https://github.com/ashleve/lightning-hydra-template/tree/dockerfiles). You can use them as a starting point for building more complicated images.
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3 <br><br><br>
-->
<br><br>
@@ -693,9 +686,65 @@ Using this approach doesn't require you to add any boilerplate into your pipelin
### Inference ### Inference
Template contains simple example of loading model from checkpoint and running predictions.<br> The following is example of loading model from checkpoint and running predictions.<br>
Take a look at [inference_example.py](src/utils/inference_example.py). <details>
<br><br> <summary><b>Show inference example</b></summary>
```python
from PIL import Image
from torchvision import transforms
from src.models.mnist_model import MNISTLitModel
def predict():
"""Example of inference with trained model.
It loads trained image classification model from checkpoint.
Then it loads example image and predicts its label.
"""
# ckpt can be also a URL!
CKPT_PATH = "last.ckpt"
# load model from checkpoint
# model __init__ parameters will be loaded from ckpt automatically
# you can also pass some parameter explicitly to override it
trained_model = MNISTLitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# print model hyperparameters
print(trained_model.hparams)
# switch to evaluation mode
trained_model.eval()
trained_model.freeze()
# load data
img = Image.open("data/example_img.png").convert("L") # convert to black and white
# img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
# preprocess
mnist_transforms = transforms.Compose(
[
transforms.ToTensor(),
transforms.Resize((28, 28)),
transforms.Normalize((0.1307,), (0.3081,)),
]
)
img = mnist_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = trained_model(img)
print(output)
if __name__ == "__main__":
predict()
```
</details>
<br>
@@ -709,8 +758,8 @@ pytest
# run tests from specific file # run tests from specific file
pytest tests/smoke_tests/test_commands.py pytest tests/smoke_tests/test_commands.py
# run all tests except the ones using wandb # run all tests except the ones marked as slow
pytest -k "not wandb" pytest -k "not slow"
``` ```
I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests](tests/smoke_tests) folder. I often find myself running into bugs that come out only in edge cases or on some specific hardware/environment. To speed up the development, I usually constantly execute tests that run a couple of quick 1 epoch experiments, like overfitting to 10 batches, training on 25% of data, etc. Those kind of tests don't check for any specific output - they exist to simply verify that executing some commands doesn't end up in throwing exceptions. You can find them implemented in [tests/smoke_tests](tests/smoke_tests) folder.
@@ -729,8 +778,11 @@ To support reproducibility:
To provide examples of logging custom visualisations with callbacks only: To provide examples of logging custom visualisations with callbacks only:
- **LogConfusionMatrix** - **LogConfusionMatrix**
- **LogF1PrecRecHeatmap** - **LogF1PrecRecHeatmap**
- **ImagePredictionLogger** - **LogImagePredictions**
<br>
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>
### Multi-GPU Training ### Multi-GPU Training
@@ -1012,8 +1064,15 @@ Now you can add any commands to your `.autoenv` file, e.g. activation of virtual
# activate conda environment # activate conda environment
conda activate myenv conda activate myenv
# initialize hydra tab completion for bash # activate hydra tab completion for bash
eval "$(python run.py -sc install=bash)" eval "$(python run.py -sc install=bash)"
# enable aliases for debugging
alias test='pytest'
alias debug1='python run.py debug=true'
alias debug2='python run.py trainer.gpus=1 trainer.max_epochs=1'
alias debug3='python run.py trainer.gpus=1 trainer.max_epochs=1 +trainer.limit_train_batches=0.1'
alias debug_wandb='python run.py 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)
-2
View File
@@ -7,8 +7,6 @@ channels:
dependencies: dependencies:
- python=3.8 - python=3.8
- pip - pip
- notebook
- ipython
- cudatoolkit - cudatoolkit
- pytorch=1.8.1 - pytorch=1.8.1
- torchvision=0.9.1 - torchvision=0.9.1
+2 -3
View File
@@ -5,9 +5,8 @@ model_checkpoint:
save_last: True # additionaly always save model from last epoch save_last: True # additionaly always save model from last epoch
mode: "max" # can be "max" or "min" mode: "max" # can be "max" or "min"
verbose: False verbose: False
dirpath: 'checkpoints/' dirpath: "checkpoints/"
filename: '{epoch:02d}' filename: "{epoch:02d}"
early_stopping: early_stopping:
_target_: pytorch_lightning.callbacks.EarlyStopping _target_: pytorch_lightning.callbacks.EarlyStopping
+7 -13
View File
@@ -1,32 +1,26 @@
defaults: defaults:
- default.yaml - default.yaml
watch_model: watch_model:
_target_: src.callbacks.wandb_callbacks.WatchModelWithWandb _target_: src.callbacks.wandb_callbacks.WatchModel
log: "all" log: "all"
log_freq: 100 log_freq: 100
upload_code_as_artifact: upload_code_as_artifact:
_target_: src.callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact _target_: src.callbacks.wandb_callbacks.UploadCodeAsArtifact
code_dir: ${work_dir}/src code_dir: ${work_dir}/src
upload_ckpts_as_artifact: upload_ckpts_as_artifact:
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact _target_: src.callbacks.wandb_callbacks.UploadCheckpointsAsArtifact
ckpt_dir: "checkpoints/" ckpt_dir: "checkpoints/"
upload_best_only: True upload_best_only: True
log_f1_precision_recall_heatmap: log_f1_precision_recall_heatmap:
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb _target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmap
log_confusion_matrix: log_confusion_matrix:
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb _target_: src.callbacks.wandb_callbacks.LogConfusionMatrix
log_image_predictions:
log_images_with_predictions: _target_: src.callbacks.wandb_callbacks.LogImagePredictions
_target_: src.callbacks.wandb_callbacks.ImagePredictionLogger
num_samples: 8 num_samples: 8
-5
View File
@@ -17,28 +17,23 @@ defaults:
- override hydra/hydra_logging: colorlog - override hydra/hydra_logging: colorlog
- override hydra/job_logging: colorlog - override hydra/job_logging: colorlog
# 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 # learn more here: 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
data_dir: ${work_dir}/data/ data_dir: ${work_dir}/data/
# use `python run.py debug=true` for easy debugging! # use `python run.py debug=true` for easy debugging!
# this will run 1 train, val and test loop with only 1 batch # this will run 1 train, val and test loop with only 1 batch
# equivalent to running `python run.py trainer.fast_dev_run=true` # equivalent to running `python run.py trainer.fast_dev_run=true`
# (this is placed here just for easier access from command line) # (this is placed here just for easier access from command line)
debug: False debug: False
# pretty print config at the start of the run using Rich library # pretty print config at the start of the run using Rich library
print_config: True print_config: True
# disable python warnings if they annoy you # disable python warnings if they annoy you
ignore_warnings: True ignore_warnings: True
+2 -2
View File
@@ -52,8 +52,8 @@ callbacks:
save_top_k: 2 save_top_k: 2
save_last: True save_last: True
mode: "max" mode: "max"
dirpath: 'checkpoints/' dirpath: "checkpoints/"
filename: 'sample-mnist-{epoch:02d}' filename: "sample-mnist-{epoch:02d}"
early_stopping: early_stopping:
_target_: pytorch_lightning.callbacks.EarlyStopping _target_: pytorch_lightning.callbacks.EarlyStopping
monitor: "val/acc" monitor: "val/acc"
-2
View File
@@ -8,11 +8,9 @@
defaults: defaults:
- override /hydra/sweeper: optuna - override /hydra/sweeper: optuna
# choose metric which will be optimized by Optuna # choose metric which will be optimized by Optuna
optimized_metric: "val/acc" optimized_metric: "val/acc"
hydra: hydra:
# here we define Optuna hyperparameter search # here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator # it optimizes for value returned from function with @hydra.main decorator
+2 -2
View File
@@ -2,6 +2,6 @@
comet: comet:
_target_: pytorch_lightning.loggers.comet.CometLogger _target_: pytorch_lightning.loggers.comet.CometLogger
api_key: ??? api_key: ${oc.env:COMET_API_TOKEN} # api key is laoded from environment variable
project_name: "project_template_test" project_name: "template-tests"
experiment_name: null experiment_name: null
+3 -1
View File
@@ -1,6 +1,8 @@
# CSVLogger built in PyTorch Lightning # csv logger built in lightning
csv: csv:
_target_: pytorch_lightning.loggers.csv_logs.CSVLogger _target_: pytorch_lightning.loggers.csv_logs.CSVLogger
save_dir: "." save_dir: "."
name: "csv/" name: "csv/"
version: null
prefix: ""
+5 -3
View File
@@ -1,8 +1,10 @@
# train with many loggers at once # train with many loggers at once
defaults: defaults:
- csv.yaml # - aim.yaml
- wandb.yaml
# - neptune.yaml
# - comet.yaml # - comet.yaml
- csv.yaml
# - mlflow.yaml
# - neptune.yaml
# - tensorboard.yaml # - tensorboard.yaml
- wandb.yaml
+10
View File
@@ -0,0 +1,10 @@
# https://mlflow.org
mlflow:
_target_: pytorch_lightning.loggers.mlflow.MLFlowLogger
experiment_name: default
tracking_uri: null
tags: null
save_dir: ./mlruns
prefix: ""
artifact_location: null
+6 -2
View File
@@ -2,6 +2,10 @@
neptune: neptune:
_target_: pytorch_lightning.loggers.neptune.NeptuneLogger _target_: pytorch_lightning.loggers.neptune.NeptuneLogger
project_name: "your_name/lightning-hydra-template-test"
api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is laoded from environment variable api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is laoded from environment variable
# experiment_name: "some_experiment" project_name: your_name/template-tests
close_after_fit: True
offline_mode: False
experiment_name: null
experiment_id: null
prefix: ""
+5 -1
View File
@@ -1,6 +1,10 @@
# TensorBoard # https://www.tensorflow.org/tensorboard/
tensorboard: tensorboard:
_target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger _target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger
save_dir: "tensorboard/" save_dir: "tensorboard/"
name: "default" name: "default"
version: null
log_graph: False
default_hp_metric: True
prefix: ""
+8 -3
View File
@@ -1,10 +1,15 @@
# https://wandb.ai (Weights&Biases) # https://wandb.ai
wandb: wandb:
_target_: pytorch_lightning.loggers.wandb.WandbLogger _target_: pytorch_lightning.loggers.wandb.WandbLogger
project: "template-tests" project: "template-tests"
name: null
save_dir: "."
offline: False # set True to store all logs only locally
id: null # pass correct id to resume experiment!
# entity: "" # set to name of your wandb team or just remove it # entity: "" # set to name of your wandb team or just remove it
# offline: False # set True to store all logs only locally log_model: False
prefix: ""
job_type: "train" job_type: "train"
group: "" group: ""
save_dir: "." tags: []
-1
View File
@@ -1,4 +1,3 @@
_target_: pytorch_lightning.Trainer _target_: pytorch_lightning.Trainer
gpus: 4 gpus: 4
+1 -1
View File
@@ -3,7 +3,7 @@ _target_: pytorch_lightning.Trainer
gpus: 0 gpus: 0
min_epochs: 1 min_epochs: 1
max_epochs: 3 max_epochs: 2
# prints # prints
progress_bar_refresh_rate: null progress_bar_refresh_rate: null
+3 -3
View File
@@ -30,7 +30,7 @@ log_every_n_steps: 50
accelerator: null accelerator: null
sync_batchnorm: False sync_batchnorm: False
precision: 32 precision: 32
weights_summary: 'top' weights_summary: "top"
weights_save_path: null weights_save_path: null
num_sanity_val_steps: 2 num_sanity_val_steps: 2
truncated_bptt_steps: null truncated_bptt_steps: null
@@ -45,6 +45,6 @@ terminate_on_nan: False
auto_scale_batch_size: False auto_scale_batch_size: False
prepare_data_per_node: True prepare_data_per_node: True
plugins: null plugins: null
amp_backend: 'native' amp_backend: "native"
amp_level: 'O2' amp_level: "O2"
move_metrics_to_cpu: False move_metrics_to_cpu: False
-1
View File
@@ -8,5 +8,4 @@ max_epochs: 10
weights_summary: null weights_summary: null
progress_bar_refresh_rate: 10 progress_bar_refresh_rate: 10
# resume_from_checkpoint: null # resume_from_checkpoint: null
+17 -11
View File
@@ -1,31 +1,37 @@
# --------- pytorch --------- # # --------- pytorch --------- #
torch==1.8.1 torch==1.8.1
torchvision==0.9.1 torchvision==0.9.1
pytorch-lightning>=1.2.10 pytorch-lightning>=1.3.2
torchmetrics torchmetrics>=0.3.2
# --------- hydra --------- # # --------- hydra --------- #
hydra-core==1.1.0.dev6 hydra-core==1.1.0.rc1
hydra-colorlog==1.1.0.dev1 hydra-colorlog==1.1.0.dev1
hydra-optuna-sweeper==1.1.0.dev1 hydra-optuna-sweeper==1.1.0.dev2
# hydra-ax-sweeper==1.1.0
# hydra-ray-launcher==0.1.2 # hydra-ray-launcher==0.1.2
# hydra-submitit-launcher==1.1.0 # hydra-submitit-launcher==1.1.0
# --------- loggers --------- # # --------- loggers --------- #
wandb>=0.10.28 wandb>=0.10.30
# neptune-client # neptune-client
# comet-ml
# mlflow # mlflow
# comet-ml
# torch_tb_profiler
# --------- linters --------- #
pre-commit
black
isort
flake8
# --------- others --------- # # --------- others --------- #
rich jupyterlab
python-dotenv python-dotenv
rich
pytest pytest
sh sh
pre-commit
scikit-learn scikit-learn
pandas
matplotlib
seaborn seaborn
# pudb pudb
# dvc # dvc
+43
View File
@@ -0,0 +1,43 @@
[metadata]
project_name = ...
author = ...
contact = ...
license_file = LICENSE
description_file = README.md
project_template = https://github.com/ashleve/lightning-hydra-template
[isort]
line_length = 99
profile = black
filter_files = True
[flake8]
max_line_length = 99
show_source = True
format = pylint
ignore =
F401 # Module imported but unused
W504 # Line break occurred after a binary operator
F841 # Local variable name is assigned to but never used
exclude =
.git
__pycache__
data/*
tests/*
notebooks/*
logs/*
[tool:pytest]
python_files = tests/*
log_cli = True
markers =
slow
addopts =
--durations=0
--strict-markers
--doctest-modules
filterwarnings =
ignore::DeprecationWarning
-1
View File
@@ -1 +0,0 @@
#
File renamed without changes.
+7 -7
View File
@@ -28,8 +28,8 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger:
) )
class WatchModelWithWandb(Callback): class WatchModel(Callback):
"""Make WandbLogger watch model at the beginning of the run.""" """Make wandb watch model at the beginning of the run."""
def __init__(self, log: str = "gradients", log_freq: int = 100): def __init__(self, log: str = "gradients", log_freq: int = 100):
self.log = log self.log = log
@@ -40,7 +40,7 @@ class WatchModelWithWandb(Callback):
logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq) logger.watch(model=trainer.model, log=self.log, log_freq=self.log_freq)
class UploadCodeToWandbAsArtifact(Callback): class UploadCodeAsArtifact(Callback):
"""Upload all *.py files to wandb as an artifact, at the beginning of the run.""" """Upload all *.py files to wandb as an artifact, at the beginning of the run."""
def __init__(self, code_dir: str): def __init__(self, code_dir: str):
@@ -57,7 +57,7 @@ class UploadCodeToWandbAsArtifact(Callback):
experiment.use_artifact(code) experiment.use_artifact(code)
class UploadCheckpointsToWandbAsArtifact(Callback): class UploadCheckpointsAsArtifact(Callback):
"""Upload checkpoints to wandb as an artifact, at the end of run.""" """Upload checkpoints to wandb as an artifact, at the end of run."""
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False): def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
@@ -79,7 +79,7 @@ class UploadCheckpointsToWandbAsArtifact(Callback):
experiment.use_artifact(ckpts) experiment.use_artifact(ckpts)
class LogConfusionMatrixToWandb(Callback): class LogConfusionMatrix(Callback):
"""Generate confusion matrix every epoch and send it to wandb. """Generate confusion matrix every epoch and send it to wandb.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
""" """
@@ -137,7 +137,7 @@ class LogConfusionMatrixToWandb(Callback):
self.targets.clear() self.targets.clear()
class LogF1PrecRecHeatmapToWandb(Callback): class LogF1PrecRecHeatmap(Callback):
"""Generate f1, precision, recall heatmap every epoch and send it to wandb. """Generate f1, precision, recall heatmap every epoch and send it to wandb.
Expects validation step to return predictions and targets. Expects validation step to return predictions and targets.
""" """
@@ -200,7 +200,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
self.targets.clear() self.targets.clear()
class ImagePredictionLogger(Callback): class LogImagePredictions(Callback):
"""Logs a validation batch and their predictions to wandb. """Logs a validation batch and their predictions to wandb.
Example adapted from: Example adapted from:
https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
File renamed without changes.
Whitespace-only changes.
-25
View File
@@ -1,25 +0,0 @@
import os
from typing import Callable, Optional
from PIL import Image
from torch.utils.data import Dataset
class ImgDataset(Dataset):
"""Example dataset class for loading images from folder."""
def __init__(self, dir: str, transform: Optional[Callable] = None):
self.transform = transform
self.images = [os.path.join(dir, fname) for fname in os.listdir(dir)]
def __getitem__(self, idx: int):
image = Image.open(self.images[idx]).convert("L") # convert to black and white
# image = Image.open(self.images[idx]).convert("RGB")
if self.transform:
image = self.transform(image)
return image
def __len__(self):
return len(self.images)
View File
Whitespace-only changes.
View File
Whitespace-only changes.
+9 -5
View File
@@ -1,11 +1,15 @@
from typing import List, Optional from typing import List, Optional
from pytorch_lightning import LightningModule, LightningDataModule, Callback, Trainer
from pytorch_lightning.loggers import LightningLoggerBase
from pytorch_lightning import seed_everything
import hydra import hydra
from omegaconf import DictConfig from omegaconf import DictConfig
from pytorch_lightning import (
Callback,
LightningDataModule,
LightningModule,
Trainer,
seed_everything,
)
from pytorch_lightning.loggers import LightningLoggerBase
from src.utils import utils from src.utils import utils
@@ -25,7 +29,7 @@ def train(config: DictConfig) -> Optional[float]:
# Set seed for random number generators in pytorch, numpy and python.random # Set seed for random number generators in pytorch, numpy and python.random
if "seed" in config: if "seed" in config:
seed_everything(config.seed) seed_everything(config.seed, workers=True)
# Init Lightning datamodule # Init Lightning datamodule
log.info(f"Instantiating datamodule <{config.datamodule._target_}>") log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
View File
Whitespace-only changes.
-49
View File
@@ -1,49 +0,0 @@
from PIL import Image
from torchvision import transforms
from src.models.mnist_model import MNISTLitModel
def predict():
"""Example of inference with trained model.
It loads trained image classification model from checkpoint.
Then it loads example image and predicts its label.
"""
# ckpt can be also a URL!
CKPT_PATH = "last.ckpt"
# load model from checkpoint
# model __init__ parameters will be loaded from ckpt automatically
# you can also pass some parameter explicitly to override it
trained_model = MNISTLitModel.load_from_checkpoint(checkpoint_path=CKPT_PATH)
# print model hyperparameters
print(trained_model.hparams)
# switch to evaluation mode
trained_model.eval()
trained_model.freeze()
# load data
img = Image.open("data/example_img.png").convert("L") # convert to black and white
# img = Image.open("data/example_img.png").convert("RGB") # convert to RGB
# preprocess
mnist_transforms = transforms.Compose(
[
transforms.ToTensor(),
transforms.Resize((28, 28)),
transforms.Normalize((0.1307,), (0.3081,)),
]
)
img = mnist_transforms(img)
img = img.reshape((1, *img.size())) # reshape to form batch of size 1
# inference
output = trained_model(img)
print(output)
if __name__ == "__main__":
predict()
+22 -22
View File
@@ -3,17 +3,16 @@ import warnings
from typing import List, Sequence from typing import List, Sequence
import pytorch_lightning as pl import pytorch_lightning as pl
import rich import rich.syntax
import rich.tree
import wandb import wandb
from omegaconf import DictConfig, OmegaConf from omegaconf import DictConfig, OmegaConf
from pytorch_lightning.loggers.wandb import WandbLogger from pytorch_lightning.loggers.wandb import WandbLogger
from pytorch_lightning.utilities import rank_zero_only from pytorch_lightning.utilities import rank_zero_only
from rich.syntax import Syntax
from rich.tree import Tree
def get_logger(name=__name__, level=logging.INFO): def get_logger(name=__name__, level=logging.INFO) -> logging.Logger:
"""Initializes python logger.""" """Initializes multi-GPU-friendly python logger."""
logger = logging.getLogger(name) logger = logging.getLogger(name)
logger.setLevel(level) logger.setLevel(level)
@@ -26,25 +25,27 @@ def get_logger(name=__name__, level=logging.INFO):
return logger return logger
log = get_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 - easier access to debug mode
- forcing debug friendly configuration - forcing debug friendly configuration
- forcing multi-gpu friendly configuration - forcing multi-gpu friendly configuration
Modifies DictConfig in place.
Args: Args:
config (DictConfig): [description] config (DictConfig): Configuration composed by Hydra.
""" """
log = get_logger()
# enable adding new keys to config # enable adding new keys to config
OmegaConf.set_struct(config, False) 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(f"Disabling python warnings! <config.ignore_warnings=True>") log.info("Disabling python warnings! <config.ignore_warnings=True>")
warnings.filterwarnings("ignore") warnings.filterwarnings("ignore")
# set <config.trainer.fast_dev_run=True> if <config.debug=True> # set <config.trainer.fast_dev_run=True> if <config.debug=True>
@@ -64,9 +65,9 @@ def extras(config: DictConfig) -> None:
config.datamodule.num_workers = 0 config.datamodule.num_workers = 0
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp> # force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]: accelerator = config.trainer.get("accelerator")
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>") if accelerator in ["ddp", "ddp_spawn", "dp", "ddp2"]:
# ddp doesn't like num_workers>0 or pin_memory=True log.info(f"Forcing ddp friendly configuration! <config.trainer.accelerator={accelerator}>")
if config.datamodule.get("num_workers"): if config.datamodule.get("num_workers"):
config.datamodule.num_workers = 0 config.datamodule.num_workers = 0
if config.datamodule.get("pin_memory"): if config.datamodule.get("pin_memory"):
@@ -92,14 +93,14 @@ def print_config(
"""Prints content of DictConfig using Rich library and its tree structure. """Prints content of DictConfig using Rich library and its tree structure.
Args: Args:
config (DictConfig): Config. config (DictConfig): Configuration composed by Hydra.
fields (Sequence[str], optional): Determines which main fields from config will be printed fields (Sequence[str], optional): Determines which main fields from config will
and in what order. be printed and in what order.
resolve (bool, optional): Whether to resolve reference fields of DictConfig. resolve (bool, optional): Whether to resolve reference fields of DictConfig.
""" """
style = "dim" style = "dim"
tree = Tree(f":gear: CONFIG", style=style, guide_style=style) tree = rich.tree.Tree(":gear: CONFIG", style=style, guide_style=style)
for field in fields: for field in fields:
branch = tree.add(field, style=style, guide_style=style) branch = tree.add(field, style=style, guide_style=style)
@@ -109,7 +110,7 @@ def print_config(
if isinstance(config_section, DictConfig): if isinstance(config_section, DictConfig):
branch_content = OmegaConf.to_yaml(config_section, resolve=resolve) branch_content = OmegaConf.to_yaml(config_section, resolve=resolve)
branch.add(Syntax(branch_content, "yaml")) branch.add(rich.syntax.Syntax(branch_content, "yaml"))
rich.print(tree) rich.print(tree)
@@ -139,8 +140,6 @@ def log_hyperparameters(
hparams["trainer"] = config["trainer"] hparams["trainer"] = config["trainer"]
hparams["model"] = config["model"] hparams["model"] = config["model"]
hparams["datamodule"] = config["datamodule"] hparams["datamodule"] = config["datamodule"]
if "optimizer" in config:
hparams["optimizer"] = config["optimizer"]
if "callbacks" in config: if "callbacks" in config:
hparams["callbacks"] = config["callbacks"] hparams["callbacks"] = config["callbacks"]
@@ -157,7 +156,8 @@ def log_hyperparameters(
trainer.logger.log_hyperparams(hparams) trainer.logger.log_hyperparams(hparams)
# disable logging any more hyperparameters for all loggers # 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) # this is just a trick to prevent trainer from logging hparams of model,
# since we already did that above
trainer.logger.log_hyperparams = empty trainer.logger.log_hyperparams = empty
-3
View File
@@ -1,3 +0,0 @@
def pytest_configure(config):
config.addinivalue_line("markers", "slow: Run slow tests.")
config.addinivalue_line("markers", "wandb: Run the wandb tests.")
+1 -2
View File
@@ -8,8 +8,7 @@ Adapted from:
def _module_available(module_path: str) -> bool: def _module_available(module_path: str) -> bool:
""" """Check if a path is available in your environment.
Check if a path is available in your environment.
>>> _module_available('os') >>> _module_available('os')
True True
+9 -17
View File
@@ -11,7 +11,6 @@ Adapted from:
https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/helpers/runif.py https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/helpers/runif.py
""" """
from tests.helpers.module_available import ( from tests.helpers.module_available import (
_APEX_AVAILABLE, _APEX_AVAILABLE,
_DEEPSPEED_AVAILABLE, _DEEPSPEED_AVAILABLE,
@@ -23,12 +22,16 @@ from tests.helpers.module_available import (
class RunIf: class RunIf:
""" """
RunIf wrapper for simple marking specific cases, fully compatible with pytest.mark:: RunIf wrapper for conditional skipping of tests.
Fully compatible with `@pytest.mark`.
@RunIf(min_torch="0.0") Example:
@pytest.mark.parametrize("arg1", [1, 2.0])
@RunIf(min_torch="1.8")
@pytest.mark.parametrize("arg1", [1.0, 2.0])
def test_wrapper(arg1): def test_wrapper(arg1):
assert arg1 > 0.0 assert arg1 > 0
""" """
def __new__( def __new__(
@@ -51,7 +54,7 @@ class RunIf:
max_torch: maximum pytorch version to run test max_torch: maximum pytorch version to run test
min_python: minimum python version required to run test min_python: minimum python version required to run test
amp_apex: NVIDIA Apex is installed amp_apex: NVIDIA Apex is installed
skip_windows: skip test for Windows platform (typically fo some limited torch functionality) skip_windows: skip test for Windows platform
rpc: requires Remote Procedure Call (RPC) rpc: requires Remote Procedure Call (RPC)
fairscale: if `fairscale` module is required to run the test fairscale: if `fairscale` module is required to run the test
deepspeed: if `deepspeed` module is required to run the test deepspeed: if `deepspeed` module is required to run the test
@@ -107,14 +110,3 @@ class RunIf:
reason=f"Requires: [{' + '.join(reasons)}]", reason=f"Requires: [{' + '.join(reasons)}]",
**kwargs, **kwargs,
) )
@RunIf(min_torch="99")
def test_always_skip():
exit(1)
@pytest.mark.parametrize("arg1", [0.5, 1.0, 2.0])
@RunIf(min_torch="0.0")
def test_wrapper(arg1: float):
assert arg1 > 0.0
View File
Whitespace-only changes.
@@ -1,3 +1,5 @@
import pytest
from tests.helpers.run_command import run_command from tests.helpers.run_command import run_command
from tests.helpers.runif import RunIf from tests.helpers.runif import RunIf
@@ -26,6 +28,7 @@ def test_default_gpu():
run_command(command) run_command(command)
@pytest.mark.slow
def test_experiments(): def test_experiments():
"""Train 1 epoch with all experiment configs.""" """Train 1 epoch with all experiment configs."""
command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"] command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"]
File renamed without changes.
@@ -3,12 +3,12 @@ import pytest
from tests.helpers.run_command import run_command from tests.helpers.run_command import run_command
""" """
Use the following command to skip wandb tests: Use the following command to skip slow tests:
pytest -k "not wandb" pytest -k "not slow"
""" """
# @pytest.mark.wandb # @pytest.mark.slow
# def test_wandb_optuna_sweep(): # def test_wandb_optuna_sweep():
# """Test wandb logging with Optuna sweep.""" # """Test wandb logging with Optuna sweep."""
# command = [ # command = [
@@ -26,7 +26,7 @@ Use the following command to skip wandb tests:
# run_command(command) # run_command(command)
# @pytest.mark.wandb # @pytest.mark.slow
# def test_wandb_callbacks(): # def test_wandb_callbacks():
# """Test wandb callbacks.""" # """Test wandb callbacks."""
# command = [ # command = [
View File
Whitespace-only changes.
File renamed without changes.