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:
1 parent
023d4bdecc
commit
70ab061f75
46 files changed
+312
-254
No files matched your search
@@ -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"
|
||||
@@ -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
@@ -2,39 +2,39 @@ default_language_version:
|
||||
python: python3.8
|
||||
|
||||
repos:
|
||||
|
||||
# Pre-commit hooks
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v3.2.0
|
||||
rev: v3.4.0
|
||||
hooks:
|
||||
# list of supported hooks: https://pre-commit.com/hooks.html
|
||||
- id: trailing-whitespace
|
||||
- id: debug-statements
|
||||
- id: detect-private-key
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-added-large-files
|
||||
- id: debug-statements
|
||||
- id: detect-private-key
|
||||
|
||||
# Black (code formatting)
|
||||
# python code formatting
|
||||
- repo: https://github.com/psf/black
|
||||
rev: 20.8b1
|
||||
hooks:
|
||||
- id: black
|
||||
args: [
|
||||
--line-length, "99",
|
||||
# --exclude, src/train.py,
|
||||
]
|
||||
args: [--line-length, "99"]
|
||||
|
||||
# Isort (import sorting)
|
||||
# python import sorting
|
||||
- repo: https://github.com/PyCQA/isort
|
||||
rev: 5.7.0
|
||||
rev: 5.8.0
|
||||
hooks:
|
||||
- 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,
|
||||
]
|
||||
# files: "src/.*"
|
||||
|
||||
# yaml formatting
|
||||
- repo: https://github.com/pre-commit/mirrors-prettier
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: prettier
|
||||
types: [yaml]
|
||||
|
||||
# python code analysis
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 3.9.2
|
||||
hooks:
|
||||
- id: flake8
|
||||
+22
@@ -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
|
||||
@@ -2,14 +2,13 @@
|
||||
|
||||
# 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="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"></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://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 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://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://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://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 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.
|
||||
@@ -87,26 +86,26 @@ The directory structure of new project looks like this:
|
||||
│ `1.0-jqp-initial-data-exploration.ipynb`.
|
||||
│
|
||||
├── tests <- Tests of any kind
|
||||
│ ├── smoke_tests
|
||||
│ └── unit_tests
|
||||
│ ├── smoke
|
||||
│ └── unit
|
||||
│
|
||||
├── src
|
||||
│ ├── callbacks <- Lightning callbacks
|
||||
│ ├── datamodules <- Lightning datamodules
|
||||
│ ├── models <- Lightning models
|
||||
│ ├── utils <- Utility scripts
|
||||
│ │ ├── inference_example.py <- Example of inference with trained model
|
||||
│ │ └── utils.py <- Extra features for the template
|
||||
│ │
|
||||
│ └── train.py <- Training pipeline
|
||||
│
|
||||
├── 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
|
||||
├── .pre-commit-config.yaml <- Configuration of automatic code formatting
|
||||
├── conda_env_gpu.yaml <- File for installing conda environment
|
||||
├── Dockerfile <- File for building docker container
|
||||
├── requirements.txt <- File for installing python dependencies
|
||||
├── setup.cgf <- Configurations of linters and pytest
|
||||
├── LICENSE
|
||||
└── README.md
|
||||
```
|
||||
@@ -364,21 +363,15 @@ python run.py -m 'experiment=glob(*)'
|
||||
|
||||
|
||||
## 🐳 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).
|
||||
|
||||
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.
|
||||
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:
|
||||
```yaml
|
||||
# download image
|
||||
docker pull nvcr.io/nvidia/pytorch:21.03-py3
|
||||
|
||||
# run container from image with GPUs enabled
|
||||
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
|
||||
docker build -t project_name .
|
||||
docker run --gpus all -it --rm project_name
|
||||
```
|
||||
<!--
|
||||
# run container with mounted volume
|
||||
docker run --gpus all -it --rm nvcr.io/nvidia/pytorch:21.03-py3
|
||||
-->
|
||||
<br><br>
|
||||
|
||||
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.
|
||||
<br><br><br>
|
||||
|
||||
|
||||
|
||||
@@ -693,9 +686,65 @@ Using this approach doesn't require you to add any boilerplate into your pipelin
|
||||
|
||||
|
||||
### Inference
|
||||
Template contains simple example of loading model from checkpoint and running predictions.<br>
|
||||
Take a look at [inference_example.py](src/utils/inference_example.py).
|
||||
<br><br>
|
||||
The following is example of loading model from checkpoint and running predictions.<br>
|
||||
<details>
|
||||
<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
|
||||
pytest tests/smoke_tests/test_commands.py
|
||||
|
||||
# run all tests except the ones using wandb
|
||||
pytest -k "not wandb"
|
||||
# run all tests except the ones marked as slow
|
||||
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.
|
||||
|
||||
@@ -729,8 +778,11 @@ To support reproducibility:
|
||||
To provide examples of logging custom visualisations with callbacks only:
|
||||
- **LogConfusionMatrix**
|
||||
- **LogF1PrecRecHeatmap**
|
||||
- **ImagePredictionLogger**
|
||||
<br>
|
||||
- **LogImagePredictions**
|
||||
|
||||
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
|
||||
@@ -1012,8 +1064,15 @@ Now you can add any commands to your `.autoenv` file, e.g. activation of virtual
|
||||
# activate conda environment
|
||||
conda activate myenv
|
||||
|
||||
# initialize hydra tab completion for bash
|
||||
# activate hydra tab completion for 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)
|
||||
|
||||
|
||||
@@ -7,8 +7,6 @@ channels:
|
||||
dependencies:
|
||||
- python=3.8
|
||||
- pip
|
||||
- notebook
|
||||
- ipython
|
||||
- cudatoolkit
|
||||
- pytorch=1.8.1
|
||||
- torchvision=0.9.1
|
||||
|
||||
@@ -5,9 +5,8 @@ model_checkpoint:
|
||||
save_last: True # additionaly always save model from last epoch
|
||||
mode: "max" # can be "max" or "min"
|
||||
verbose: False
|
||||
dirpath: 'checkpoints/'
|
||||
filename: '{epoch:02d}'
|
||||
|
||||
dirpath: "checkpoints/"
|
||||
filename: "{epoch:02d}"
|
||||
|
||||
early_stopping:
|
||||
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||
|
||||
@@ -1,32 +1,26 @@
|
||||
defaults:
|
||||
- default.yaml
|
||||
|
||||
|
||||
watch_model:
|
||||
_target_: src.callbacks.wandb_callbacks.WatchModelWithWandb
|
||||
_target_: src.callbacks.wandb_callbacks.WatchModel
|
||||
log: "all"
|
||||
log_freq: 100
|
||||
|
||||
|
||||
upload_code_as_artifact:
|
||||
_target_: src.callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact
|
||||
_target_: src.callbacks.wandb_callbacks.UploadCodeAsArtifact
|
||||
code_dir: ${work_dir}/src
|
||||
|
||||
|
||||
upload_ckpts_as_artifact:
|
||||
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact
|
||||
_target_: src.callbacks.wandb_callbacks.UploadCheckpointsAsArtifact
|
||||
ckpt_dir: "checkpoints/"
|
||||
upload_best_only: True
|
||||
|
||||
|
||||
log_f1_precision_recall_heatmap:
|
||||
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmapToWandb
|
||||
|
||||
_target_: src.callbacks.wandb_callbacks.LogF1PrecRecHeatmap
|
||||
|
||||
log_confusion_matrix:
|
||||
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrixToWandb
|
||||
_target_: src.callbacks.wandb_callbacks.LogConfusionMatrix
|
||||
|
||||
|
||||
log_images_with_predictions:
|
||||
_target_: src.callbacks.wandb_callbacks.ImagePredictionLogger
|
||||
log_image_predictions:
|
||||
_target_: src.callbacks.wandb_callbacks.LogImagePredictions
|
||||
num_samples: 8
|
||||
@@ -17,28 +17,23 @@ defaults:
|
||||
- override hydra/hydra_logging: colorlog
|
||||
- override hydra/job_logging: colorlog
|
||||
|
||||
|
||||
# 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
|
||||
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
|
||||
ignore_warnings: True
|
||||
@@ -52,8 +52,8 @@ callbacks:
|
||||
save_top_k: 2
|
||||
save_last: True
|
||||
mode: "max"
|
||||
dirpath: 'checkpoints/'
|
||||
filename: 'sample-mnist-{epoch:02d}'
|
||||
dirpath: "checkpoints/"
|
||||
filename: "sample-mnist-{epoch:02d}"
|
||||
early_stopping:
|
||||
_target_: pytorch_lightning.callbacks.EarlyStopping
|
||||
monitor: "val/acc"
|
||||
|
||||
@@ -8,11 +8,9 @@
|
||||
defaults:
|
||||
- override /hydra/sweeper: optuna
|
||||
|
||||
|
||||
# choose metric which will be optimized by Optuna
|
||||
optimized_metric: "val/acc"
|
||||
|
||||
|
||||
hydra:
|
||||
# here we define Optuna hyperparameter search
|
||||
# it optimizes for value returned from function with @hydra.main decorator
|
||||
|
||||
@@ -2,6 +2,6 @@
|
||||
|
||||
comet:
|
||||
_target_: pytorch_lightning.loggers.comet.CometLogger
|
||||
api_key: ???
|
||||
project_name: "project_template_test"
|
||||
api_key: ${oc.env:COMET_API_TOKEN} # api key is laoded from environment variable
|
||||
project_name: "template-tests"
|
||||
experiment_name: null
|
||||
@@ -1,6 +1,8 @@
|
||||
# CSVLogger built in PyTorch Lightning
|
||||
# csv logger built in lightning
|
||||
|
||||
csv:
|
||||
_target_: pytorch_lightning.loggers.csv_logs.CSVLogger
|
||||
save_dir: "."
|
||||
name: "csv/"
|
||||
version: null
|
||||
prefix: ""
|
||||
@@ -1,8 +1,10 @@
|
||||
# train with many loggers at once
|
||||
|
||||
defaults:
|
||||
- csv.yaml
|
||||
- wandb.yaml
|
||||
# - neptune.yaml
|
||||
# - aim.yaml
|
||||
# - comet.yaml
|
||||
- csv.yaml
|
||||
# - mlflow.yaml
|
||||
# - neptune.yaml
|
||||
# - tensorboard.yaml
|
||||
- wandb.yaml
|
||||
@@ -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
|
||||
@@ -2,6 +2,10 @@
|
||||
|
||||
neptune:
|
||||
_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
|
||||
# experiment_name: "some_experiment"
|
||||
project_name: your_name/template-tests
|
||||
close_after_fit: True
|
||||
offline_mode: False
|
||||
experiment_name: null
|
||||
experiment_id: null
|
||||
prefix: ""
|
||||
@@ -1,6 +1,10 @@
|
||||
# TensorBoard
|
||||
# https://www.tensorflow.org/tensorboard/
|
||||
|
||||
tensorboard:
|
||||
_target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger
|
||||
save_dir: "tensorboard/"
|
||||
name: "default"
|
||||
version: null
|
||||
log_graph: False
|
||||
default_hp_metric: True
|
||||
prefix: ""
|
||||
@@ -1,10 +1,15 @@
|
||||
# https://wandb.ai (Weights&Biases)
|
||||
# https://wandb.ai
|
||||
|
||||
wandb:
|
||||
_target_: pytorch_lightning.loggers.wandb.WandbLogger
|
||||
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
|
||||
# offline: False # set True to store all logs only locally
|
||||
log_model: False
|
||||
prefix: ""
|
||||
job_type: "train"
|
||||
group: ""
|
||||
save_dir: "."
|
||||
tags: []
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
_target_: pytorch_lightning.Trainer
|
||||
|
||||
gpus: 4
|
||||
|
||||
@@ -3,7 +3,7 @@ _target_: pytorch_lightning.Trainer
|
||||
gpus: 0
|
||||
|
||||
min_epochs: 1
|
||||
max_epochs: 3
|
||||
max_epochs: 2
|
||||
|
||||
# prints
|
||||
progress_bar_refresh_rate: null
|
||||
|
||||
@@ -30,7 +30,7 @@ log_every_n_steps: 50
|
||||
accelerator: null
|
||||
sync_batchnorm: False
|
||||
precision: 32
|
||||
weights_summary: 'top'
|
||||
weights_summary: "top"
|
||||
weights_save_path: null
|
||||
num_sanity_val_steps: 2
|
||||
truncated_bptt_steps: null
|
||||
@@ -45,6 +45,6 @@ terminate_on_nan: False
|
||||
auto_scale_batch_size: False
|
||||
prepare_data_per_node: True
|
||||
plugins: null
|
||||
amp_backend: 'native'
|
||||
amp_level: 'O2'
|
||||
amp_backend: "native"
|
||||
amp_level: "O2"
|
||||
move_metrics_to_cpu: False
|
||||
@@ -8,5 +8,4 @@ max_epochs: 10
|
||||
|
||||
weights_summary: null
|
||||
progress_bar_refresh_rate: 10
|
||||
|
||||
# resume_from_checkpoint: null
|
||||
+17
-11
@@ -1,31 +1,37 @@
|
||||
# --------- pytorch --------- #
|
||||
torch==1.8.1
|
||||
torchvision==0.9.1
|
||||
pytorch-lightning>=1.2.10
|
||||
torchmetrics
|
||||
pytorch-lightning>=1.3.2
|
||||
torchmetrics>=0.3.2
|
||||
|
||||
# --------- hydra --------- #
|
||||
hydra-core==1.1.0.dev6
|
||||
hydra-core==1.1.0.rc1
|
||||
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-submitit-launcher==1.1.0
|
||||
|
||||
# --------- loggers --------- #
|
||||
wandb>=0.10.28
|
||||
wandb>=0.10.30
|
||||
# neptune-client
|
||||
# comet-ml
|
||||
# mlflow
|
||||
# comet-ml
|
||||
# torch_tb_profiler
|
||||
|
||||
# --------- linters --------- #
|
||||
pre-commit
|
||||
black
|
||||
isort
|
||||
flake8
|
||||
|
||||
# --------- others --------- #
|
||||
rich
|
||||
jupyterlab
|
||||
python-dotenv
|
||||
rich
|
||||
pytest
|
||||
sh
|
||||
pre-commit
|
||||
scikit-learn
|
||||
pandas
|
||||
matplotlib
|
||||
seaborn
|
||||
# pudb
|
||||
pudb
|
||||
# dvc
|
||||
@@ -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 +0,0 @@
|
||||
#
|
||||
File renamed without changes.
@@ -28,8 +28,8 @@ def get_wandb_logger(trainer: Trainer) -> WandbLogger:
|
||||
)
|
||||
|
||||
|
||||
class WatchModelWithWandb(Callback):
|
||||
"""Make WandbLogger watch model at the beginning of the run."""
|
||||
class WatchModel(Callback):
|
||||
"""Make wandb watch model at the beginning of the run."""
|
||||
|
||||
def __init__(self, log: str = "gradients", log_freq: int = 100):
|
||||
self.log = log
|
||||
@@ -40,7 +40,7 @@ class WatchModelWithWandb(Callback):
|
||||
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."""
|
||||
|
||||
def __init__(self, code_dir: str):
|
||||
@@ -57,7 +57,7 @@ class UploadCodeToWandbAsArtifact(Callback):
|
||||
experiment.use_artifact(code)
|
||||
|
||||
|
||||
class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
class UploadCheckpointsAsArtifact(Callback):
|
||||
"""Upload checkpoints to wandb as an artifact, at the end of run."""
|
||||
|
||||
def __init__(self, ckpt_dir: str = "checkpoints/", upload_best_only: bool = False):
|
||||
@@ -79,7 +79,7 @@ class UploadCheckpointsToWandbAsArtifact(Callback):
|
||||
experiment.use_artifact(ckpts)
|
||||
|
||||
|
||||
class LogConfusionMatrixToWandb(Callback):
|
||||
class LogConfusionMatrix(Callback):
|
||||
"""Generate confusion matrix every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
"""
|
||||
@@ -137,7 +137,7 @@ class LogConfusionMatrixToWandb(Callback):
|
||||
self.targets.clear()
|
||||
|
||||
|
||||
class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
class LogF1PrecRecHeatmap(Callback):
|
||||
"""Generate f1, precision, recall heatmap every epoch and send it to wandb.
|
||||
Expects validation step to return predictions and targets.
|
||||
"""
|
||||
@@ -200,7 +200,7 @@ class LogF1PrecRecHeatmapToWandb(Callback):
|
||||
self.targets.clear()
|
||||
|
||||
|
||||
class ImagePredictionLogger(Callback):
|
||||
class LogImagePredictions(Callback):
|
||||
"""Logs a validation batch and their predictions to wandb.
|
||||
Example adapted from:
|
||||
https://wandb.ai/wandb/wandb-lightning/reports/Image-Classification-using-PyTorch-Lightning--VmlldzoyODk1NzY
|
||||
|
||||
File renamed without changes.
Whitespace-only changes.
@@ -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)
|
||||
Whitespace-only changes.
Whitespace-only changes.
+9
-5
@@ -1,11 +1,15 @@
|
||||
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
|
||||
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
|
||||
|
||||
@@ -25,7 +29,7 @@ def train(config: DictConfig) -> Optional[float]:
|
||||
|
||||
# Set seed for random number generators in pytorch, numpy and python.random
|
||||
if "seed" in config:
|
||||
seed_everything(config.seed)
|
||||
seed_everything(config.seed, workers=True)
|
||||
|
||||
# Init Lightning datamodule
|
||||
log.info(f"Instantiating datamodule <{config.datamodule._target_}>")
|
||||
|
||||
Whitespace-only changes.
@@ -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
@@ -3,17 +3,16 @@ import warnings
|
||||
from typing import List, Sequence
|
||||
|
||||
import pytorch_lightning as pl
|
||||
import rich
|
||||
import rich.syntax
|
||||
import rich.tree
|
||||
import wandb
|
||||
from omegaconf import DictConfig, OmegaConf
|
||||
from pytorch_lightning.loggers.wandb import WandbLogger
|
||||
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):
|
||||
"""Initializes python logger."""
|
||||
def get_logger(name=__name__, level=logging.INFO) -> logging.Logger:
|
||||
"""Initializes multi-GPU-friendly python logger."""
|
||||
|
||||
logger = logging.getLogger(name)
|
||||
logger.setLevel(level)
|
||||
@@ -26,25 +25,27 @@ def get_logger(name=__name__, level=logging.INFO):
|
||||
return logger
|
||||
|
||||
|
||||
log = get_logger()
|
||||
|
||||
|
||||
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
|
||||
- easier access to debug mode
|
||||
- forcing debug friendly configuration
|
||||
- forcing multi-gpu friendly configuration
|
||||
|
||||
Modifies DictConfig in place.
|
||||
|
||||
Args:
|
||||
config (DictConfig): [description]
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
"""
|
||||
|
||||
log = get_logger()
|
||||
|
||||
# enable adding new keys to config
|
||||
OmegaConf.set_struct(config, False)
|
||||
|
||||
# disable python warnings if <config.ignore_warnings=True>
|
||||
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")
|
||||
|
||||
# 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
|
||||
|
||||
# force multi-gpu friendly configuration if <config.trainer.accelerator=ddp>
|
||||
if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info("Forcing ddp friendly configuration! <config.trainer.accelerator=ddp>")
|
||||
# ddp doesn't like num_workers>0 or pin_memory=True
|
||||
accelerator = config.trainer.get("accelerator")
|
||||
if accelerator in ["ddp", "ddp_spawn", "dp", "ddp2"]:
|
||||
log.info(f"Forcing ddp friendly configuration! <config.trainer.accelerator={accelerator}>")
|
||||
if config.datamodule.get("num_workers"):
|
||||
config.datamodule.num_workers = 0
|
||||
if config.datamodule.get("pin_memory"):
|
||||
@@ -92,14 +93,14 @@ def print_config(
|
||||
"""Prints content of DictConfig using Rich library and its tree structure.
|
||||
|
||||
Args:
|
||||
config (DictConfig): Config.
|
||||
fields (Sequence[str], optional): Determines which main fields from config will be printed
|
||||
and in what order.
|
||||
config (DictConfig): Configuration composed by Hydra.
|
||||
fields (Sequence[str], optional): Determines which main fields from config will
|
||||
be printed and in what order.
|
||||
resolve (bool, optional): Whether to resolve reference fields of DictConfig.
|
||||
"""
|
||||
|
||||
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:
|
||||
branch = tree.add(field, style=style, guide_style=style)
|
||||
@@ -109,7 +110,7 @@ def print_config(
|
||||
if isinstance(config_section, DictConfig):
|
||||
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)
|
||||
|
||||
@@ -139,8 +140,6 @@ def log_hyperparameters(
|
||||
hparams["trainer"] = config["trainer"]
|
||||
hparams["model"] = config["model"]
|
||||
hparams["datamodule"] = config["datamodule"]
|
||||
if "optimizer" in config:
|
||||
hparams["optimizer"] = config["optimizer"]
|
||||
if "callbacks" in config:
|
||||
hparams["callbacks"] = config["callbacks"]
|
||||
|
||||
@@ -157,7 +156,8 @@ def log_hyperparameters(
|
||||
trainer.logger.log_hyperparams(hparams)
|
||||
|
||||
# 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
|
||||
|
||||
|
||||
|
||||
@@ -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.")
|
||||
@@ -8,8 +8,7 @@ Adapted from:
|
||||
|
||||
|
||||
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')
|
||||
True
|
||||
|
||||
+9
-17
@@ -11,7 +11,6 @@ Adapted from:
|
||||
https://github.com/PyTorchLightning/pytorch-lightning/blob/master/tests/helpers/runif.py
|
||||
"""
|
||||
|
||||
|
||||
from tests.helpers.module_available import (
|
||||
_APEX_AVAILABLE,
|
||||
_DEEPSPEED_AVAILABLE,
|
||||
@@ -23,12 +22,16 @@ from tests.helpers.module_available import (
|
||||
|
||||
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")
|
||||
@pytest.mark.parametrize("arg1", [1, 2.0])
|
||||
Example:
|
||||
|
||||
@RunIf(min_torch="1.8")
|
||||
@pytest.mark.parametrize("arg1", [1.0, 2.0])
|
||||
def test_wrapper(arg1):
|
||||
assert arg1 > 0.0
|
||||
assert arg1 > 0
|
||||
|
||||
"""
|
||||
|
||||
def __new__(
|
||||
@@ -51,7 +54,7 @@ class RunIf:
|
||||
max_torch: maximum pytorch version to run test
|
||||
min_python: minimum python version required to run test
|
||||
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)
|
||||
fairscale: if `fairscale` 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)}]",
|
||||
**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
|
||||
Whitespace-only changes.
@@ -1,3 +1,5 @@
|
||||
import pytest
|
||||
|
||||
from tests.helpers.run_command import run_command
|
||||
from tests.helpers.runif import RunIf
|
||||
|
||||
@@ -26,6 +28,7 @@ def test_default_gpu():
|
||||
run_command(command)
|
||||
|
||||
|
||||
@pytest.mark.slow
|
||||
def test_experiments():
|
||||
"""Train 1 epoch with all experiment configs."""
|
||||
command = ["run.py", "-m", "experiment=glob(*)", "trainer.max_epochs=1"]
|
||||
File renamed without changes.
File renamed without changes.
@@ -3,12 +3,12 @@ import pytest
|
||||
from tests.helpers.run_command import run_command
|
||||
|
||||
"""
|
||||
Use the following command to skip wandb tests:
|
||||
pytest -k "not wandb"
|
||||
Use the following command to skip slow tests:
|
||||
pytest -k "not slow"
|
||||
"""
|
||||
|
||||
|
||||
# @pytest.mark.wandb
|
||||
# @pytest.mark.slow
|
||||
# def test_wandb_optuna_sweep():
|
||||
# """Test wandb logging with Optuna sweep."""
|
||||
# command = [
|
||||
@@ -26,7 +26,7 @@ Use the following command to skip wandb tests:
|
||||
# run_command(command)
|
||||
|
||||
|
||||
# @pytest.mark.wandb
|
||||
# @pytest.mark.slow
|
||||
# def test_wandb_callbacks():
|
||||
# """Test wandb callbacks."""
|
||||
# command = [
|
||||
Whitespace-only changes.
File renamed without changes.
Reference in new issue
Block a user