From 70ab061f759de0ff5f7fe1263bac8c4a33fae18f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Zalewski?= Date: Fri, 21 May 2021 09:26:31 +0200 Subject: [PATCH] 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 --- .env.example | 7 + .env.template | 8 -- .pre-commit-config.yaml | 44 +++--- Dockerfile | 22 +++ README.md | 127 +++++++++++++----- conda_env_gpu.yaml | 2 - configs/callbacks/default.yaml | 27 ++-- configs/callbacks/wandb.yaml | 34 ++--- configs/config.yaml | 27 ++-- configs/datamodule/mnist_datamodule.yaml | 2 +- configs/experiment/example_full.yaml | 96 ++++++------- configs/experiment/example_simple.yaml | 28 ++-- configs/hparams_search/mnist_optuna.yaml | 90 ++++++------- configs/hydra/default.yaml | 10 +- configs/logger/comet.yaml | 8 +- configs/logger/csv.yaml | 10 +- configs/logger/many_loggers.yaml | 12 +- configs/logger/mlflow.yaml | 10 ++ configs/logger/neptune.yaml | 12 +- configs/logger/tensorboard.yaml | 12 +- configs/logger/wandb.yaml | 21 +-- configs/trainer/ddp.yaml | 1 - configs/trainer/debug.yaml | 2 +- configs/trainer/default.yaml | 6 +- configs/trainer/minimal.yaml | 1 - requirements.txt | 28 ++-- setup.cfg | 43 ++++++ src/__init__.py | 1 - .../smoke_tests => src/callbacks}/__init__.py | 0 src/callbacks/wandb_callbacks.py | 14 +- .../datamodules}/__init__.py | 0 src/datamodules/datasets/__init__.py | 0 src/datamodules/datasets/img_dataset.py | 25 ---- src/models/__init__.py | 0 src/models/modules/__init__.py | 0 src/train.py | 14 +- src/utils/__init__.py | 0 src/utils/inference_example.py | 49 ------- src/utils/utils.py | 52 +++---- tests/conftest.py | 3 - tests/helpers/module_available.py | 3 +- tests/helpers/runif.py | 26 ++-- tests/smoke/__init__.py | 0 tests/{smoke_tests => smoke}/test_commands.py | 3 + .../test_mixed_precision.py | 0 tests/{smoke_tests => smoke}/test_sweeps.py | 0 tests/{smoke_tests => smoke}/test_wandb.py | 8 +- tests/unit/__init__.py | 0 tests/{unit_tests => unit}/test_sth.py | 0 49 files changed, 473 insertions(+), 415 deletions(-) create mode 100644 .env.example delete mode 100644 .env.template create mode 100644 Dockerfile create mode 100644 configs/logger/mlflow.yaml create mode 100644 setup.cfg rename {tests/smoke_tests => src/callbacks}/__init__.py (100%) rename {tests/unit_tests => src/datamodules}/__init__.py (100%) create mode 100644 src/datamodules/datasets/__init__.py delete mode 100644 src/datamodules/datasets/img_dataset.py create mode 100644 src/models/__init__.py create mode 100644 src/models/modules/__init__.py create mode 100644 src/utils/__init__.py delete mode 100644 src/utils/inference_example.py delete mode 100644 tests/conftest.py create mode 100644 tests/smoke/__init__.py rename tests/{smoke_tests => smoke}/test_commands.py (98%) rename tests/{smoke_tests => smoke}/test_mixed_precision.py (100%) rename tests/{smoke_tests => smoke}/test_sweeps.py (100%) rename tests/{smoke_tests => smoke}/test_wandb.py (88%) create mode 100644 tests/unit/__init__.py rename tests/{unit_tests => unit}/test_sth.py (100%) diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ea8769b --- /dev/null +++ b/.env.example @@ -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" diff --git a/.env.template b/.env.template deleted file mode 100644 index f40c021..0000000 --- a/.env.template +++ /dev/null @@ -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" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 074ecf9..3fa033b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,40 +1,40 @@ default_language_version: - python: python3.8 + 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 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..d4c3e96 --- /dev/null +++ b/Dockerfile @@ -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 diff --git a/README.md b/README.md index cee7894..1077608 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,13 @@ # Lightning-Hydra-Template - -PyTorch -Lightning -Config: hydra -Docker -Code style: black + +Python +PyTorch +Lightning +Config: hydra +Code style: black + A clean and scalable template to kickstart your deep learning project 🚀⚡🔥
Click on [Use this template](https://github.com/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 ``` - -

+ +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. +


@@ -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.
-Take a look at [inference_example.py](src/utils/inference_example.py). -

+The following is example of loading model from checkpoint and running predictions.
+
+Show inference example + +```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() + +``` + +
+
@@ -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** -
+- **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). +

+ ### 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) diff --git a/conda_env_gpu.yaml b/conda_env_gpu.yaml index 8db3b48..106d240 100644 --- a/conda_env_gpu.yaml +++ b/conda_env_gpu.yaml @@ -7,8 +7,6 @@ channels: dependencies: - python=3.8 - pip - - notebook - - ipython - cudatoolkit - pytorch=1.8.1 - torchvision=0.9.1 diff --git a/configs/callbacks/default.yaml b/configs/callbacks/default.yaml index 4288157..f891bc7 100644 --- a/configs/callbacks/default.yaml +++ b/configs/callbacks/default.yaml @@ -1,17 +1,16 @@ model_checkpoint: - _target_: pytorch_lightning.callbacks.ModelCheckpoint - monitor: "val/acc" # name of the logged metric which determines when model is improving - save_top_k: 1 # save k best models (determined by above metric) - save_last: True # additionaly always save model from last epoch - mode: "max" # can be "max" or "min" - verbose: False - dirpath: 'checkpoints/' - filename: '{epoch:02d}' - + _target_: pytorch_lightning.callbacks.ModelCheckpoint + monitor: "val/acc" # name of the logged metric which determines when model is improving + save_top_k: 1 # save k best models (determined by above metric) + save_last: True # additionaly always save model from last epoch + mode: "max" # can be "max" or "min" + verbose: False + dirpath: "checkpoints/" + filename: "{epoch:02d}" early_stopping: - _target_: pytorch_lightning.callbacks.EarlyStopping - monitor: "val/acc" # name of the logged metric which determines when model is improving - patience: 100 # how many epochs of not improving until training stops - mode: "max" # can be "max" or "min" - min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement + _target_: pytorch_lightning.callbacks.EarlyStopping + monitor: "val/acc" # name of the logged metric which determines when model is improving + patience: 100 # how many epochs of not improving until training stops + mode: "max" # can be "max" or "min" + min_delta: 0 # minimum change in the monitored metric needed to qualify as an improvement diff --git a/configs/callbacks/wandb.yaml b/configs/callbacks/wandb.yaml index 1e2ad31..c6ae21d 100644 --- a/configs/callbacks/wandb.yaml +++ b/configs/callbacks/wandb.yaml @@ -1,32 +1,26 @@ defaults: - - default.yaml - + - default.yaml watch_model: - _target_: src.callbacks.wandb_callbacks.WatchModelWithWandb - log: "all" - log_freq: 100 - + _target_: src.callbacks.wandb_callbacks.WatchModel + log: "all" + log_freq: 100 upload_code_as_artifact: - _target_: src.callbacks.wandb_callbacks.UploadCodeToWandbAsArtifact - code_dir: ${work_dir}/src - + _target_: src.callbacks.wandb_callbacks.UploadCodeAsArtifact + code_dir: ${work_dir}/src upload_ckpts_as_artifact: - _target_: src.callbacks.wandb_callbacks.UploadCheckpointsToWandbAsArtifact - ckpt_dir: "checkpoints/" - upload_best_only: True - + _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 - num_samples: 8 +log_image_predictions: + _target_: src.callbacks.wandb_callbacks.LogImagePredictions + num_samples: 8 diff --git a/configs/config.yaml b/configs/config.yaml index eeb4bc7..48c9448 100644 --- a/configs/config.yaml +++ b/configs/config.yaml @@ -2,21 +2,20 @@ # specify here default training configuration defaults: - - trainer: minimal.yaml - - model: mnist_model.yaml - - datamodule: mnist_datamodule.yaml - - callbacks: default.yaml # set this to null if you don't want to use callbacks - - logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`) + - trainer: minimal.yaml + - model: mnist_model.yaml + - datamodule: mnist_datamodule.yaml + - callbacks: default.yaml # set this to null if you don't want to use callbacks + - logger: null # set logger here or use command line (e.g. `python run.py logger=wandb`) - - experiment: null - - hparams_search: null + - experiment: null + - hparams_search: null - - hydra: default.yaml - - # enable color logging - - override hydra/hydra_logging: colorlog - - override hydra/job_logging: colorlog + - hydra: default.yaml + # enable color logging + - 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, @@ -24,21 +23,17 @@ defaults: # learn more here: https://hydra.cc/docs/next/tutorials/basic/running_your_app/working_directory work_dir: ${hydra:runtime.cwd} - # path to folder with data data_dir: ${work_dir}/data/ - # use `python run.py debug=true` for easy debugging! # this will run 1 train, val and test loop with only 1 batch # equivalent to running `python run.py trainer.fast_dev_run=true` # (this is placed here just for easier access from command line) debug: False - # pretty print config at the start of the run using Rich library print_config: True - # disable python warnings if they annoy you ignore_warnings: True diff --git a/configs/datamodule/mnist_datamodule.yaml b/configs/datamodule/mnist_datamodule.yaml index 1633939..cc9a005 100644 --- a/configs/datamodule/mnist_datamodule.yaml +++ b/configs/datamodule/mnist_datamodule.yaml @@ -1,6 +1,6 @@ _target_: src.datamodules.mnist_datamodule.MNISTDataModule -data_dir: ${data_dir} # data_dir is specified in config.yaml +data_dir: ${data_dir} # data_dir is specified in config.yaml batch_size: 64 train_val_test_split: [55_000, 5_000, 10_000] num_workers: 0 diff --git a/configs/experiment/example_full.yaml b/configs/experiment/example_full.yaml index 2b8e3fe..d7eb838 100644 --- a/configs/experiment/example_full.yaml +++ b/configs/experiment/example_full.yaml @@ -4,11 +4,11 @@ # python run.py experiment=example_full.yaml defaults: - - override /trainer: null # override trainer to null so it's not loaded from main config defaults... - - override /model: null - - override /datamodule: null - - override /callbacks: null - - override /logger: null + - override /trainer: null # override trainer to null so it's not loaded from main config defaults... + - override /model: null + - override /datamodule: null + - override /callbacks: null + - override /logger: null # we override default configurations with nulls to prevent them from loading at all # instead we define all modules and their paths directly in this config, @@ -17,54 +17,54 @@ defaults: seed: 12345 trainer: - _target_: pytorch_lightning.Trainer - gpus: 0 - min_epochs: 1 - max_epochs: 10 - gradient_clip_val: 0.5 - accumulate_grad_batches: 2 - weights_summary: null - # resume_from_checkpoint: ${work_dir}/last.ckpt + _target_: pytorch_lightning.Trainer + gpus: 0 + min_epochs: 1 + max_epochs: 10 + gradient_clip_val: 0.5 + accumulate_grad_batches: 2 + weights_summary: null + # resume_from_checkpoint: ${work_dir}/last.ckpt model: - _target_: src.models.mnist_model.MNISTLitModel - lr: 0.001 - weight_decay: 0.00005 - architecture: SimpleDenseNet - input_size: 784 - lin1_size: 256 - lin2_size: 256 - lin3_size: 128 - output_size: 10 + _target_: src.models.mnist_model.MNISTLitModel + lr: 0.001 + weight_decay: 0.00005 + architecture: SimpleDenseNet + input_size: 784 + lin1_size: 256 + lin2_size: 256 + lin3_size: 128 + output_size: 10 datamodule: - _target_: src.datamodules.mnist_datamodule.MNISTDataModule - data_dir: ${data_dir} - batch_size: 64 - train_val_test_split: [55_000, 5_000, 10_000] - num_workers: 0 - pin_memory: False + _target_: src.datamodules.mnist_datamodule.MNISTDataModule + data_dir: ${data_dir} + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] + num_workers: 0 + pin_memory: False callbacks: - model_checkpoint: - _target_: pytorch_lightning.callbacks.ModelCheckpoint - monitor: "val/acc" - save_top_k: 2 - save_last: True - mode: "max" - dirpath: 'checkpoints/' - filename: 'sample-mnist-{epoch:02d}' - early_stopping: - _target_: pytorch_lightning.callbacks.EarlyStopping - monitor: "val/acc" - patience: 10 - mode: "max" + model_checkpoint: + _target_: pytorch_lightning.callbacks.ModelCheckpoint + monitor: "val/acc" + save_top_k: 2 + save_last: True + mode: "max" + dirpath: "checkpoints/" + filename: "sample-mnist-{epoch:02d}" + early_stopping: + _target_: pytorch_lightning.callbacks.EarlyStopping + monitor: "val/acc" + patience: 10 + mode: "max" logger: - wandb: - tags: ["best_model", "uwu"] - notes: "Description of this model." - neptune: - tags: ["best_model"] - csv_logger: - save_dir: "." + wandb: + tags: ["best_model", "uwu"] + notes: "Description of this model." + neptune: + tags: ["best_model"] + csv_logger: + save_dir: "." diff --git a/configs/experiment/example_simple.yaml b/configs/experiment/example_simple.yaml index 117c654..7a5fcc5 100644 --- a/configs/experiment/example_simple.yaml +++ b/configs/experiment/example_simple.yaml @@ -4,11 +4,11 @@ # python run.py experiment=example_simple.yaml defaults: - - override /trainer: minimal.yaml # choose trainer from 'configs/trainer/' - - override /model: mnist_model.yaml - - override /datamodule: mnist_datamodule.yaml - - override /callbacks: default.yaml - - override /logger: null + - override /trainer: minimal.yaml # choose trainer from 'configs/trainer/' + - override /model: mnist_model.yaml + - override /datamodule: mnist_datamodule.yaml + - override /callbacks: default.yaml + - override /logger: null # all parameters below will be merged with parameters from default configurations set above # this allows you to overwrite only specified parameters @@ -16,16 +16,16 @@ defaults: seed: 12345 trainer: - min_epochs: 1 - max_epochs: 10 - gradient_clip_val: 0.5 + min_epochs: 1 + max_epochs: 10 + gradient_clip_val: 0.5 model: - lin1_size: 128 - lin2_size: 256 - lin3_size: 64 - lr: 0.002 + lin1_size: 128 + lin2_size: 256 + lin3_size: 64 + lr: 0.002 datamodule: - batch_size: 64 - train_val_test_split: [55_000, 5_000, 10_000] + batch_size: 64 + train_val_test_split: [55_000, 5_000, 10_000] diff --git a/configs/hparams_search/mnist_optuna.yaml b/configs/hparams_search/mnist_optuna.yaml index 389a7cc..509def3 100644 --- a/configs/hparams_search/mnist_optuna.yaml +++ b/configs/hparams_search/mnist_optuna.yaml @@ -6,58 +6,56 @@ # python run.py -m hparams_search=mnist_optuna experiment=example_simple logger=wandb defaults: - - override /hydra/sweeper: optuna - + - 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 - # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper - sweeper: - _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper - storage: null - study_name: null - n_jobs: 1 + # here we define Optuna hyperparameter search + # it optimizes for value returned from function with @hydra.main decorator + # learn more here: https://hydra.cc/docs/next/plugins/optuna_sweeper + sweeper: + _target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper + storage: null + study_name: null + n_jobs: 1 - # 'minimize' or 'maximize' the objective - direction: maximize + # 'minimize' or 'maximize' the objective + direction: maximize - # number of experiments that will be executed - n_trials: 20 + # number of experiments that will be executed + n_trials: 20 - # choose Optuna hyperparameter sampler - # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html - sampler: - _target_: optuna.samplers.TPESampler - seed: 12345 - consider_prior: true - prior_weight: 1.0 - consider_magic_clip: true - consider_endpoints: false - n_startup_trials: 10 - n_ei_candidates: 24 - multivariate: false - warn_independent_sampling: true + # choose Optuna hyperparameter sampler + # learn more here: https://optuna.readthedocs.io/en/stable/reference/samplers.html + sampler: + _target_: optuna.samplers.TPESampler + seed: 12345 + consider_prior: true + prior_weight: 1.0 + consider_magic_clip: true + consider_endpoints: false + n_startup_trials: 10 + n_ei_candidates: 24 + multivariate: false + warn_independent_sampling: true - # define range of hyperparameters - search_space: - datamodule.batch_size: - type: categorical - choices: [32, 64, 128] - model.lr: - type: float - low: 0.0001 - high: 0.2 - model.lin1_size: - type: categorical - choices: [32, 64, 128, 256, 512] - model.lin2_size: - type: categorical - choices: [32, 64, 128, 256, 512] - model.lin3_size: - type: categorical - choices: [32, 64, 128, 256, 512] + # define range of hyperparameters + search_space: + datamodule.batch_size: + type: categorical + choices: [32, 64, 128] + model.lr: + type: float + low: 0.0001 + high: 0.2 + model.lin1_size: + type: categorical + choices: [32, 64, 128, 256, 512] + model.lin2_size: + type: categorical + choices: [32, 64, 128, 256, 512] + model.lin3_size: + type: categorical + choices: [32, 64, 128, 256, 512] diff --git a/configs/hydra/default.yaml b/configs/hydra/default.yaml index 4cdac91..a086d12 100644 --- a/configs/hydra/default.yaml +++ b/configs/hydra/default.yaml @@ -1,12 +1,12 @@ # output paths for hydra logs run: - dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} + dir: logs/runs/${now:%Y-%m-%d}/${now:%H-%M-%S} sweep: - dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S} - subdir: ${hydra.job.num} + dir: logs/multiruns/${now:%Y-%m-%d_%H-%M-%S} + subdir: ${hydra.job.num} # you can set here environment variables that are universal for all users # for system specific variables (like data paths) it's better to use .env file! job: - env_set: - EXAMPLE_VAR: "example_value" + env_set: + EXAMPLE_VAR: "example_value" diff --git a/configs/logger/comet.yaml b/configs/logger/comet.yaml index 3447b5e..07d2f5d 100644 --- a/configs/logger/comet.yaml +++ b/configs/logger/comet.yaml @@ -1,7 +1,7 @@ # https://www.comet.ml comet: - _target_: pytorch_lightning.loggers.comet.CometLogger - api_key: ??? - project_name: "project_template_test" - experiment_name: null + _target_: pytorch_lightning.loggers.comet.CometLogger + api_key: ${oc.env:COMET_API_TOKEN} # api key is laoded from environment variable + project_name: "template-tests" + experiment_name: null diff --git a/configs/logger/csv.yaml b/configs/logger/csv.yaml index c76f1f1..85a78a2 100644 --- a/configs/logger/csv.yaml +++ b/configs/logger/csv.yaml @@ -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/" + _target_: pytorch_lightning.loggers.csv_logs.CSVLogger + save_dir: "." + name: "csv/" + version: null + prefix: "" diff --git a/configs/logger/many_loggers.yaml b/configs/logger/many_loggers.yaml index 87569f2..cb5bc0c 100644 --- a/configs/logger/many_loggers.yaml +++ b/configs/logger/many_loggers.yaml @@ -1,8 +1,10 @@ # train with many loggers at once defaults: - - csv.yaml - - wandb.yaml - # - neptune.yaml - # - comet.yaml - # - tensorboard.yaml + # - aim.yaml + # - comet.yaml + - csv.yaml + # - mlflow.yaml + # - neptune.yaml + # - tensorboard.yaml + - wandb.yaml diff --git a/configs/logger/mlflow.yaml b/configs/logger/mlflow.yaml new file mode 100644 index 0000000..c7b4fda --- /dev/null +++ b/configs/logger/mlflow.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 diff --git a/configs/logger/neptune.yaml b/configs/logger/neptune.yaml index b2bf4ae..9ca93ec 100644 --- a/configs/logger/neptune.yaml +++ b/configs/logger/neptune.yaml @@ -1,7 +1,11 @@ # https://neptune.ai 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" + _target_: pytorch_lightning.loggers.neptune.NeptuneLogger + api_key: ${oc.env:NEPTUNE_API_TOKEN} # api key is laoded from environment variable + project_name: your_name/template-tests + close_after_fit: True + offline_mode: False + experiment_name: null + experiment_id: null + prefix: "" diff --git a/configs/logger/tensorboard.yaml b/configs/logger/tensorboard.yaml index 2bb8dee..39386a9 100644 --- a/configs/logger/tensorboard.yaml +++ b/configs/logger/tensorboard.yaml @@ -1,6 +1,10 @@ -# TensorBoard +# https://www.tensorflow.org/tensorboard/ tensorboard: - _target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger - save_dir: "tensorboard/" - name: "default" + _target_: pytorch_lightning.loggers.tensorboard.TensorBoardLogger + save_dir: "tensorboard/" + name: "default" + version: null + log_graph: False + default_hp_metric: True + prefix: "" diff --git a/configs/logger/wandb.yaml b/configs/logger/wandb.yaml index 63eab8b..18e2cda 100644 --- a/configs/logger/wandb.yaml +++ b/configs/logger/wandb.yaml @@ -1,10 +1,15 @@ -# https://wandb.ai (Weights&Biases) +# https://wandb.ai wandb: - _target_: pytorch_lightning.loggers.wandb.WandbLogger - project: "template-tests" - # entity: "" # set to name of your wandb team or just remove it - # offline: False # set True to store all logs only locally - job_type: "train" - group: "" - save_dir: "." + _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 + log_model: False + prefix: "" + job_type: "train" + group: "" + tags: [] diff --git a/configs/trainer/ddp.yaml b/configs/trainer/ddp.yaml index d14a2d9..d860c6a 100644 --- a/configs/trainer/ddp.yaml +++ b/configs/trainer/ddp.yaml @@ -1,4 +1,3 @@ - _target_: pytorch_lightning.Trainer gpus: 4 diff --git a/configs/trainer/debug.yaml b/configs/trainer/debug.yaml index 9eca67b..aebe67b 100644 --- a/configs/trainer/debug.yaml +++ b/configs/trainer/debug.yaml @@ -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 diff --git a/configs/trainer/default.yaml b/configs/trainer/default.yaml index 450a6fd..067c295 100644 --- a/configs/trainer/default.yaml +++ b/configs/trainer/default.yaml @@ -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 diff --git a/configs/trainer/minimal.yaml b/configs/trainer/minimal.yaml index bcfc53e..999de14 100644 --- a/configs/trainer/minimal.yaml +++ b/configs/trainer/minimal.yaml @@ -8,5 +8,4 @@ max_epochs: 10 weights_summary: null progress_bar_refresh_rate: 10 - # resume_from_checkpoint: null diff --git a/requirements.txt b/requirements.txt index c92238a..0f23f30 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..7848eee --- /dev/null +++ b/setup.cfg @@ -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 diff --git a/src/__init__.py b/src/__init__.py index 792d600..e69de29 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -1 +0,0 @@ -# diff --git a/tests/smoke_tests/__init__.py b/src/callbacks/__init__.py similarity index 100% rename from tests/smoke_tests/__init__.py rename to src/callbacks/__init__.py diff --git a/src/callbacks/wandb_callbacks.py b/src/callbacks/wandb_callbacks.py index 88714a9..d677965 100644 --- a/src/callbacks/wandb_callbacks.py +++ b/src/callbacks/wandb_callbacks.py @@ -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 diff --git a/tests/unit_tests/__init__.py b/src/datamodules/__init__.py similarity index 100% rename from tests/unit_tests/__init__.py rename to src/datamodules/__init__.py diff --git a/src/datamodules/datasets/__init__.py b/src/datamodules/datasets/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/datamodules/datasets/img_dataset.py b/src/datamodules/datasets/img_dataset.py deleted file mode 100644 index bc08ee0..0000000 --- a/src/datamodules/datasets/img_dataset.py +++ /dev/null @@ -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) diff --git a/src/models/__init__.py b/src/models/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/models/modules/__init__.py b/src/models/modules/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/train.py b/src/train.py index c0bea9e..b50a2a1 100644 --- a/src/train.py +++ b/src/train.py @@ -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_}>") diff --git a/src/utils/__init__.py b/src/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/utils/inference_example.py b/src/utils/inference_example.py deleted file mode 100644 index 2cc3f0e..0000000 --- a/src/utils/inference_example.py +++ /dev/null @@ -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() diff --git a/src/utils/utils.py b/src/utils/utils.py index a285f3d..97ad088 100644 --- a/src/utils/utils.py +++ b/src/utils/utils.py @@ -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. - - disabling warnings - - easier access to debug mode - - forcing debug friendly configuration - - forcing multi-gpu friendly configuration + """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 if config.get("ignore_warnings"): - log.info(f"Disabling python warnings! ") + log.info("Disabling python warnings! ") warnings.filterwarnings("ignore") # set if @@ -64,9 +65,9 @@ def extras(config: DictConfig) -> None: config.datamodule.num_workers = 0 # force multi-gpu friendly configuration if - if config.trainer.get("accelerator") in ["ddp", "ddp_spawn", "dp", "ddp2"]: - log.info("Forcing ddp friendly configuration! ") - # ddp doesn't like num_workers>0 or pin_memory=True + accelerator = config.trainer.get("accelerator") + if accelerator in ["ddp", "ddp_spawn", "dp", "ddp2"]: + log.info(f"Forcing ddp friendly configuration! ") 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 diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index d4c82b7..0000000 --- a/tests/conftest.py +++ /dev/null @@ -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.") diff --git a/tests/helpers/module_available.py b/tests/helpers/module_available.py index 50688c2..9c82e38 100644 --- a/tests/helpers/module_available.py +++ b/tests/helpers/module_available.py @@ -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 diff --git a/tests/helpers/runif.py b/tests/helpers/runif.py index 9c66ff4..92bffc0 100644 --- a/tests/helpers/runif.py +++ b/tests/helpers/runif.py @@ -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 diff --git a/tests/smoke/__init__.py b/tests/smoke/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/smoke_tests/test_commands.py b/tests/smoke/test_commands.py similarity index 98% rename from tests/smoke_tests/test_commands.py rename to tests/smoke/test_commands.py index e8b72e6..72d5294 100644 --- a/tests/smoke_tests/test_commands.py +++ b/tests/smoke/test_commands.py @@ -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"] diff --git a/tests/smoke_tests/test_mixed_precision.py b/tests/smoke/test_mixed_precision.py similarity index 100% rename from tests/smoke_tests/test_mixed_precision.py rename to tests/smoke/test_mixed_precision.py diff --git a/tests/smoke_tests/test_sweeps.py b/tests/smoke/test_sweeps.py similarity index 100% rename from tests/smoke_tests/test_sweeps.py rename to tests/smoke/test_sweeps.py diff --git a/tests/smoke_tests/test_wandb.py b/tests/smoke/test_wandb.py similarity index 88% rename from tests/smoke_tests/test_wandb.py rename to tests/smoke/test_wandb.py index ffe04a2..5cb8a36 100644 --- a/tests/smoke_tests/test_wandb.py +++ b/tests/smoke/test_wandb.py @@ -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 = [ diff --git a/tests/unit/__init__.py b/tests/unit/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/unit_tests/test_sth.py b/tests/unit/test_sth.py similarity index 100% rename from tests/unit_tests/test_sth.py rename to tests/unit/test_sth.py