From d45f604bc8adb4e3d38ed544f1f413bc14593873 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20Zalewski?= Date: Wed, 21 Jul 2021 03:37:45 +0200 Subject: [PATCH] Release/1.0 (#156) * update to Hydra 1.1 * add bash folder with scripts for conda setup and run scheduling * add saving seed in `log_hyperparameters()` method * redesign Dockerfile to make it weight less * add `test_after_training` parameter to config * add inheritance to trainer configs * remove forcing ddp-friendly configuration * refactor tests * remove conda_env_gpu.yaml * remove default langage version from pre-commit config * add mnist datamodule unit test * rename test folder from 'smoke' to 'shell' * remove wandb import from utils.py * change 'use_artifact' to 'log_artifact' in wandb callbacks * add rank zero decorator to wandb callbacks * add dumping rich tree config to file * get rid of `=` character in ckpt names * update requirements.txt * update LICENSE * update README.md --- .pre-commit-config.yaml | 3 - Dockerfile | 62 +++++++++++---- LICENSE | 2 +- README.md | 80 +++++++++---------- bash/schedule.sh | 9 +++ bash/setup_conda.sh | 33 ++++++++ conda_env_gpu.yaml | 14 ---- configs/callbacks/default.yaml | 7 +- configs/config.yaml | 6 +- configs/experiment/example_full.yaml | 1 - configs/experiment/example_simple.yaml | 2 +- configs/logger/neptune.yaml | 2 +- configs/trainer/all_params.yaml | 50 ++++++++++++ configs/trainer/ddp.yaml | 3 +- configs/trainer/debug.yaml | 5 +- configs/trainer/default.yaml | 53 ++----------- configs/trainer/minimal.yaml | 11 --- requirements.txt | 46 +++++------ run.py | 1 - setup.cfg | 3 + src/callbacks/wandb_callbacks.py | 8 +- src/datamodules/mnist_datamodule.py | 3 +- src/models/mnist_model.py | 1 - src/train.py | 18 ++--- src/utils/utils.py | 24 +++--- tests/helpers/module_available.py | 3 - tests/{smoke => shell}/__init__.py | 0 tests/shell/test_basic_commands.py | 58 ++++++++++++++ tests/shell/test_mixed_precision.py | 47 +++++++++++ tests/{smoke => shell}/test_sweeps.py | 12 +-- tests/smoke/test_commands.py | 106 ------------------------- tests/smoke/test_mixed_precision.py | 47 ----------- tests/smoke/test_wandb.py | 40 ---------- tests/unit/test_mnist_datamodule.py | 36 +++++++++ tests/unit/test_sth.py | 26 ------ 35 files changed, 398 insertions(+), 424 deletions(-) create mode 100644 bash/schedule.sh create mode 100644 bash/setup_conda.sh delete mode 100644 conda_env_gpu.yaml create mode 100644 configs/trainer/all_params.yaml delete mode 100644 configs/trainer/minimal.yaml rename tests/{smoke => shell}/__init__.py (100%) create mode 100644 tests/shell/test_basic_commands.py create mode 100644 tests/shell/test_mixed_precision.py rename tests/{smoke => shell}/test_sweeps.py (66%) delete mode 100644 tests/smoke/test_commands.py delete mode 100644 tests/smoke/test_mixed_precision.py delete mode 100644 tests/smoke/test_wandb.py create mode 100644 tests/unit/test_mnist_datamodule.py delete mode 100644 tests/unit/test_sth.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3fa033b..dad27b3 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,3 @@ -default_language_version: - python: python3.8 - repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v3.4.0 diff --git a/Dockerfile b/Dockerfile index e1ef4e0..eae864a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,23 +1,57 @@ -# Build: docker build -t project_name . -# Run: docker run -v $(pwd):/workspace/project --gpus all -it --rm project_name +# Build: sudo docker build -t . +# Run: sudo docker run -v $(pwd):/workspace/project --gpus all -it --rm + + +FROM nvidia/cuda:10.2-cudnn7-devel-ubuntu18.04 + + +ENV CONDA_ENV_NAME=myenv +ENV PYTHON_VERSION=3.8 + + +# Basic setup +RUN apt update +RUN apt install -y bash \ + build-essential \ + git \ + curl \ + ca-certificates \ + wget \ + && rm -rf /var/lib/apt/lists -# 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.05-py3 # Set working directory WORKDIR /workspace/project -# Copy files to create conda environment -COPY conda_env_gpu.yaml requirements.txt ./ +# Install Miniconda and create main env +ADD https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh miniconda3.sh +RUN /bin/bash miniconda3.sh -b -p /conda \ + && echo export PATH=/conda/bin:$PATH >> .bashrc \ + && rm miniconda3.sh +ENV PATH="/conda/bin:${PATH}" +RUN conda create -n ${CONDA_ENV_NAME} python=${PYTHON_VERSION} -# Create myenv -RUN conda env create -f conda_env_gpu.yaml -n myenv \ - && conda init bash +# Switch to bash shell +SHELL ["/bin/bash", "-c"] -# Set myenv to default virtual environment -RUN echo "source activate myenv" >> ~/.bashrc + +# Install requirements +COPY requirements.txt ./ +RUN source activate ${CONDA_ENV_NAME} \ + && pip install --no-cache-dir -r requirements.txt \ + && rm requirements.txt + + +# Uncomment this to install Apex for mixed-precision support +# RUN source activate ${CONDA_ENV_NAME} \ +# && git clone https://github.com/NVIDIA/apex \ +# && cd apex \ +# && pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ \ +# && cd .. \ +# && rm -r apex + + +# Set ${CONDA_ENV_NAME} to default virutal environment +RUN echo "source activate ${CONDA_ENV_NAME}" >> ~/.bashrc diff --git a/LICENSE b/LICENSE index b1e3df6..adaaede 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2020 KINoAI +Copyright (c) 2020 ashleve Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 7b9ef64..b8eba76 100644 --- a/README.md +++ b/README.md @@ -3,17 +3,17 @@ # Lightning-Hydra-Template -Python +Python PyTorch -Lightning -Config: hydra +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. -*Currently uses dev version of Hydra.
Suggestions are always welcome!* +*Suggestions are always welcome!*

@@ -56,7 +56,7 @@ It makes your code neatly organized and provides lots of useful features, like a - **Experiment Tracking**: many logging frameworks can be easily integrated! (see [#Experiment Tracking](#experiment-tracking)) - **Logs**: all logs (checkpoints, data from loggers, chosen hparams, etc.) are stored in a convenient folder structure imposed by Hydra (see [#Logs](#logs)) - **Hyperparameter Search**: made easier with Hydra built in plugins like [Optuna Sweeper](https://hydra.cc/docs/next/plugins/optuna_sweeper) (see [#Hyperparameter Search](#hyperparameter-search)) -- **Tests**: unit tests and smoke tests (see [#Tests](#tests)) +- **Tests**: unit tests and command based tests (see [#Tests](#tests)) - **Extra Features**: optional utilities to make your life easier (see [#Extra Features](#extra-features)) - **Best Practices**: a couple of recommended tools, practices and standards for efficient workflow and reproducibility (see [#Best Practices](#best-practices))
@@ -65,6 +65,10 @@ It makes your code neatly organized and provides lots of useful features, like a ## Project Structure The directory structure of new project looks like this: ``` +├── bash <- Bash scripts +│ ├── setup_conda.sh <- Setup conda environment +│ └── schedule.sh <- Schedule execution of many runs +│ ├── configs <- Hydra configuration files │ ├── callbacks <- Callbacks configs │ ├── datamodule <- Datamodule configs @@ -86,8 +90,9 @@ The directory structure of new project looks like this: │ `1.0-jqp-initial-data-exploration.ipynb`. │ ├── tests <- Tests of any kind -│ ├── smoke -│ └── unit +│ ├── helpers <- A couple of testing utilities +│ ├── shell <- Shell/command based tests +│ └── unit <- Unit tests │ ├── src │ ├── callbacks <- Lightning callbacks @@ -97,15 +102,14 @@ The directory structure of new project looks like this: │ │ │ └── train.py <- Training pipeline │ -├── run.py <- Run any pipeline with chosen experiment configuration +├── run.py <- Run pipeline with chosen experiment configuration │ ├── .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 +├── setup.cfg <- Configurations of linters and pytest ├── Dockerfile <- File for building docker container ├── requirements.txt <- File for installing python dependencies -├── setup.cgf <- Configurations of linters and pytest ├── LICENSE └── README.md ``` @@ -119,8 +123,7 @@ git clone https://github.com/ashleve/lightning-hydra-template cd lightning-hydra-template # [OPTIONAL] create conda environment -conda env create -f conda_env_gpu.yaml -n myenv -conda activate myenv +bash bash/setup_conda.sh # install requirements pip install -r requirements.txt @@ -363,8 +366,7 @@ python run.py -m 'experiment=glob(*)' ## 🐳  Docker -I recommend the official [nvidia ngc pytorch container](https://ngc.nvidia.com/catalog/containers/nvidia:pytorch/tags). - +First you will need to [install Nvidia Container Toolkit](https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html) to enable GPU support.
To build the container from provided Dockerfile use: ```bash docker build -t . @@ -373,8 +375,7 @@ To mount the project to the container use: ```bash docker run -v $(pwd):/workspace/project --gpus all -it --rm ``` - -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. +Uncomment Apex in Dockerfile for mixed-precision support.


@@ -389,7 +390,7 @@ Have a question? Found a bug? Missing a specific feature? Ran into a problem? Fe ### How To Get Started - First, you should probably get familiar with [PyTorch Lightning](https://www.pytorchlightning.ai) -- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/), [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/) and [docs about instantiating objects with Hydra](https://hydra.cc/docs/patterns/instantiate_objects/overview) +- Next, go through [Hydra quick start guide](https://hydra.cc/docs/intro/) and [basic Hydra tutorial](https://hydra.cc/docs/tutorials/basic/your_first_app/simple_cli/)
@@ -426,7 +427,7 @@ It also specifies everything that shouldn't be managed by experiment configurati ```yaml # specify here default training configuration defaults: - - trainer: minimal.yaml + - trainer: default.yaml - model: mnist_model.yaml - datamodule: mnist_datamodule.yaml - callbacks: default.yaml # set this to null if you don't want to use callbacks @@ -455,7 +456,6 @@ print_config: True # disable python warnings if they annoy you ignore_warnings: True - ``` @@ -473,7 +473,7 @@ Experiment configurations allow you to overwrite parameters from main project co # python run.py experiment=example_simple defaults: - - override /trainer: minimal.yaml + - override /trainer: default.yaml - override /model: mnist_model.yaml - override /datamodule: mnist_datamodule.yaml - override /callbacks: default.yaml @@ -760,12 +760,12 @@ To execute them simply run: pytest # run tests from specific file -pytest tests/smoke_tests/test_commands.py +pytest tests/shell/test_basic_commands.py # 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. +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/shell](tests/shell) folder. You can easily modify the commands in the scripts for your use case. If even 1 epoch is too much for your model, then you can make it run for a couple of batches instead (by using the right trainer flags).

@@ -803,13 +803,10 @@ python run.py trainer.gpus=4 +trainer.accelerator="ddp" ### Extra Features List of extra utilities available in the template: -- loading environment variables from [.env](.env.template) file +- loading environment variables from [.env](.env.example) file - pretty printing config with [Rich](https://github.com/willmcgugan/rich) library - disabling python warnings -- easier access to debug mode -- forcing debug friendly configuration -- forcing multi-gpu friendly configuration -- method for logging hyperparameters to loggers +- debug mode You can easily remove any of those by modifying [run.py](run.py) and [src/train.py](src/train.py). @@ -840,10 +837,9 @@ Example installation: wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh bash Miniconda3-latest-Linux-x86_64.sh ``` -Create environment from file provided in the template: +Create environment using bash script provided in the template: ```yaml -conda env create -f conda_env_gpu.yaml -n myenv -conda activate myenv +bash bash/setup_conda.sh ``` @@ -861,7 +857,7 @@ Next, install hooks from [.pre-commit-config.yaml](.pre-commit-config.yaml): pre-commit install ``` After that your code will be automatically reformatted on every new commit.
-Currently template contains configurations of **Black** (python code formatting) and **Isort** (python import sorting). You can exclude chosen files from automatic formatting, by modifying [.pre-commit-config.yaml](.pre-commit-config.yaml).
+Currently template contains configurations of **black** (python code formatting), **isort** (python import sorting), **flake8** (python code analysis) and **prettier** (yaml formating).
To reformat all files in the project use command: ```yaml @@ -875,7 +871,7 @@ pre-commit run -a System specific variables (e.g. absolute paths to datasets) should not be under version control or it will result in conflict between different users. Your private keys also shouldn't be versioned since you don't want them to be leaked.
-Template contains `.env.template` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore). +Template contains `.env.example` file, which serves as an example. Create a new file called `.env` (this name is excluded from version control in .gitignore). You should use it for storing environment variables like this: ```yaml MY_VAR=/home/user/my_system_path @@ -1045,6 +1041,13 @@ from project_name.datamodules.mnist_datamodule import MNISTDataModule ``` + +
@@ -1112,7 +1115,7 @@ from omegaconf import OmegaConf # you can place this snippet in your datamodule __init__() resolver_name = "datamodule" -OmegaConf.register_resolver( +OmegaConf.register_new_resolver( resolver_name, lambda name: getattr(self, name), use_cache=False @@ -1160,14 +1163,12 @@ This template was inspired by: -
+