A versatile framework for 3D machine learning built on Pytorch Lightning and Hydra.
Please see the Project Guidelines section before diving into the code!
# clone project
git clone https://github.com/CCInc/3d-ml.git --recurse-submodules && cd 3d-ml
# Create a fresh conda environment
conda activate base
conda create -n 3dml -y python=3.9
conda activate 3dml
# For GPU support see https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html for CUDA toolkit installation instructions
nvcc --version # To make sure you have the CUDA toolkit installed. Your PyTorch CUDA version must match your nvcc version.
# Install pytorch
# Pick a compatible combination of pytorch and cuda version from https://pytorch.org/
# Below is an example for CUDA 11.3
conda install pytorch==1.12.1 torchvision==0.13.1 cudatoolkit=11.3 -c pytorch -y
# Install pyg
conda install pyg pytorch-scatter -c pyg -y
# install other requirements
pip install -r requirements.txt
# install openpoints
./install_openpoints.sh
# clone project with submodules
git clone https://github.com/CCInc/3d-ml.git --recurse-submodules && cd 3d-ml
# (optional) create virtual environment with virtualenv
python -m virtualenv env_3d
source env_3d/bin/activate
# Install pytorch
# Pick a compatible combination of pytorch and cuda version from https://pytorch.org/
# Below is an example for CUDA 11.6
pip install torch torchvision --extra-index-url https://download.pytorch.org/whl/cu116
# Install pytorch geo with pip
# Below is an example for CUDA 11.6 and torch 1.13
pip install pyg-lib torch-scatter torch-sparse -f https://data.pyg.org/whl/torch-1.13.0+cu116.html
pip install torch-geometric
# Install additional requirements
pip install -r requirements.txt
# If using virtual environments remove the "--user" argument for the last two setup.py commands
# in the file install_openpoints.sh.
./install_openpoints.sh
Train with specific model, and dataset
python src/train.py model=cls_pointnet++ data=cls_modelnet2048
Train model with chosen experiment configuration from configs/experiment/
python src/train.py experiment=cls_modelnet_pointnet++
Override any config parameter from command line
python train.py trainer.max_epochs=20 model.optimizer.lr=1e-4
Note: You can also add new parameters with
+
sign.
python train.py +model.new_param="owo"
Train on CPU, GPU, multi-GPU and TPU
# train on CPU
python train.py trainer=cpu
# train on 1 GPU
python train.py trainer=gpu
# train on TPU
python train.py +trainer.tpu_cores=8
# train with DDP (Distributed Data Parallel) (4 GPUs)
python train.py trainer=ddp trainer.devices=4
# train with DDP (Distributed Data Parallel) (8 GPUs, 2 nodes)
python train.py trainer=ddp trainer.devices=4 trainer.num_nodes=2
# simulate DDP on CPU processes
python train.py trainer=ddp_sim trainer.devices=2
# accelerate training on mac
python train.py trainer=mps
Warning: Currently there are problems with DDP mode, read this issue to learn more.
Train with mixed precision
# train with pytorch native automatic mixed precision (AMP)
python train.py trainer=gpu +trainer.precision=16
Train model with any logger available in PyTorch Lightning, like W&B or Tensorboard
# set project and entity names in `configs/logger/wandb`
wandb:
project: "your_project_name"
entity: "your_wandb_team_name"
# train model with Weights&Biases (link to wandb dashboard should appear in the terminal)
python train.py logger=wandb
Note: Lightning provides convenient integrations with most popular logging frameworks. Learn more here.
Note: Using wandb requires you to setup account first. After that just complete the config as below.
Note: Click here to see example wandb dashboard generated with this template.
Train model with chosen experiment config
python train.py experiment=example
Note: Experiment configs are placed in configs/experiment/.
Attach some callbacks to run
python train.py callbacks=default
Note: Callbacks can be used for things such as as model checkpointing, early stopping and many more.
Note: Callbacks configs are placed in configs/callbacks/.
Use different tricks available in Pytorch Lightning
# gradient clipping may be enabled to avoid exploding gradients
python train.py +trainer.gradient_clip_val=0.5
# run validation loop 4 times during a training epoch
python train.py +trainer.val_check_interval=0.25
# accumulate gradients
python train.py +trainer.accumulate_grad_batches=10
# terminate training after 12 hours
python train.py +trainer.max_time="00:12:00:00"
Note: PyTorch Lightning provides about 40+ useful trainer flags.
Easily debug
# runs 1 epoch in default debugging mode
# changes logging directory to `logs/debugs/...`
# sets level of all command line loggers to 'DEBUG'
# enforces debug-friendly configuration
python train.py debug=default
# run 1 train, val and test loop, using only 1 batch
python train.py debug=fdr
# print execution time profiling
python train.py debug=profiler
# try overfitting to 1 batch
python train.py debug=overfit
# raise exception if there are any numerical anomalies in tensors, like NaN or +/-inf
python train.py +trainer.detect_anomaly=true
# log second gradient norm of the model
python train.py +trainer.track_grad_norm=2
# use only 20% of the data
python train.py +trainer.limit_train_batches=0.2 \
+trainer.limit_val_batches=0.2 +trainer.limit_test_batches=0.2
Note: Visit configs/debug/ for different debugging configs.
Resume training from checkpoint
python train.py ckpt_path="/path/to/ckpt/name.ckpt"
Note: Checkpoint can be either path or URL.
Note: Currently loading ckpt doesn't resume logger experiment, but it will be supported in future Lightning release.
Evaluate checkpoint on test dataset
python eval.py ckpt_path="/path/to/ckpt/name.ckpt"
Note: Checkpoint can be either path or URL.
Create a sweep over hyperparameters
# this will run 6 experiments one after the other,
# each with different combination of batch_size and learning rate
python train.py -m datamodule.batch_size=32,64,128 model.lr=0.001,0.0005
Note: Hydra composes configs lazily at job launch time. If you change code or configs after launching a job/sweep, the final composed configs might be impacted.
Create a sweep over hyperparameters with Optuna
# this will run hyperparameter search defined in `configs/hparams_search/mnist_optuna.yaml`
# over chosen experiment config
python train.py -m hparams_search=mnist_optuna experiment=example
Note: Using Optuna Sweeper doesn't require you to add any boilerplate to your code, everything is defined in a single config file.
Warning: Optuna sweeps are not failure-resistant (if one job crashes then the whole sweep crashes).
Execute all experiments from folder
python train.py -m 'experiment=glob(*)'
Note: Hydra provides special syntax for controlling behavior of multiruns. Learn more here. The command above executes all experiments from configs/experiment/.
Execute run for multiple different seeds
python train.py -m seed=1,2,3,4,5 trainer.deterministic=True logger=csv tags=["benchmark"]
Note:
trainer.deterministic=True
makes pytorch more deterministic but impacts the performance.
Execute sweep on a remote AWS cluster
Note: This should be achievable with simple config using Ray AWS launcher for Hydra. Example is not implemented in this template.
Use Hydra tab completion
Note: Hydra allows you to autocomplete config argument overrides in shell as you write them, by pressing
tab
key. Read the docs.
Apply pre-commit hooks
pre-commit run -a
Note: Apply pre-commit hooks to do things like auto-formatting code and configs, performing code analysis or removing output from jupyter notebooks. See # Best Practices for more.
Run tests
# run all tests
pytest
# run tests from specific file
pytest tests/test_train.py
# run all tests except the ones marked as slow
pytest -k "not slow"
Use tags
Each experiment should be tagged in order to easily filter them across files or in logger UI:
python train.py tags=["mnist", "experiment_X"]
If no tags are provided, you will be asked to input them from command line:
>>> python train.py tags=[]
[2022-07-11 15:40:09,358][src.utils.utils][INFO] - Enforcing tags! <cfg.extras.enforce_tags=True>
[2022-07-11 15:40:09,359][src.utils.rich_utils][WARNING] - No tags provided in config. Prompting user to input tags...
Enter a list of comma separated tags (dev):
If no tags are provided for multirun, an error will be raised:
>>> python train.py -m +x=1,2,3 tags=[]
ValueError: Specify tags before launching a multirun!
Note: Appending lists from command line is currently not supported in hydra :(
This project is based on a plugin architecture and is to remain as lightweight as possible, serving merely as a connector between different downstream libraries. The main functions this framework is to serve is as follows:
- Provide experiment configuration control with Hydra config
- Provide consistent data augmentation and preprocessing steps across multiple datasets and models
- Provide reference implementations of commonly used 3D datasets using PyL
- Provide experiment tracking across a wide array of tools, e.g. Wandb and Tensorboard
- Provide PyL wrappers for downstream libraries which provide model implementations and backends
Refer to the Hydra docs for overall best practices when using Hydra configs.
Relevant configuration parameters should be provided for every model/dataset to ensure easy reproducibility (e.g. batch sizes, learning rate, schedulers, optimizers).
Configuration and code should be completely decoupled. Parameters passed to code from a Hydra config should be in the form of primitives or dataclasses, not DictConfigs or generic key/value pairs. See, for example, the usage of the LrScheduler
dataclass to duct-type the configuration parameters in src/models/common.py. As as result, all code should be able to be run independently of Hydra. Configuration files should use hydra instantiation whenever possible to support this goal.
Dataset preprocessing should be as minimal as possible so that the user can have maximum flexbility in how to prepare the data for their specific model or usecase. For example, rather than hardcoding data augmentations within the dataset code, data augmentations should be specified in the configuration file. Datasets should be agnostic to models, and any specific model preparation should be left to the configuration.
All datasets should be implemented within LightningDataModule
s and inherit from Base3dDataModule
. This data module code should handle train/test/validation splits, downloading and storing the dataset, and initializing the underlying dataset classes.
Datasets should inherit from torch_geometric.data.Dataset
, which allows the trainer to grab the number of classes and the number of features directly from the dataset object.
The __getitem__
function of the dataset should return a torch_geometric.data.Data
object, with at least the keys pos
and y
. For proper collation, keys must be Tensor objects or primitives. For all tasks, the key pos
will be a floating point tensor of size (n, 3)
. For classification tasks, the key y
will be a single integer value. For segmentation tasks, the key y
will be stored as a tensor of integers of size (n)
.
Features such as RGB should be stored into dedicated keys in the Data
object. Then, these features can be added to the x
vector dynamically by using the AddFeatsByKey
transform.
Metrics should be implemented using the TorchMetrics library whenever possible. If a metric is not available, first try to add an implementation to the TorchMetrics repo.
Models should be implemented as much as possible via backend plugins, such as TorchSparse or OpenPoints. Then, construct a LightningModule
which inherits from BaseSegmentationModel
or BaseClassificationModel
to interface with that backend. The backend model should be constructed in the module's initializer, and the step
and forward
functions should be used to transform the data into the appropriate format to pass to the backend model, apply the criterion, and return the predictions and loss.
Have a question? Found a bug? Missing a specific feature? Feel free to file a new issue, discussion or PR with respective title and description.
Before making an issue, please verify that:
- The problem still exists on the current
main
branch. - Your python dependencies are updated to recent versions.
Suggestions for improvements are always welcome!
Before contributing, make sure you set up pre-commit:
pip install pre-commit
pre-commit install
pre-commit run -a
Location: configs/experiment
Experiment configs allow you to overwrite parameters from main config.
For example, you can use them to version control best hyperparameters for each combination of model and dataset.
Show example experiment config
# @package _global_
# to execute this experiment run:
# python train.py experiment=example
defaults:
- override /datamodule: mnist.yaml
- override /model: mnist.yaml
- override /callbacks: default.yaml
- override /trainer: default.yaml
# all parameters below will be merged with parameters from default configurations set above
# this allows you to overwrite only specified parameters
tags: ["mnist", "simple_dense_net"]
seed: 12345
trainer:
min_epochs: 10
max_epochs: 10
gradient_clip_val: 0.5
model:
optimizer:
lr: 0.002
net:
lin1_size: 128
lin2_size: 256
lin3_size: 64
datamodule:
batch_size: 64
logger:
wandb:
tags: ${tags}
group: "mnist"
Experiment design
Say you want to execute many runs to plot how accuracy changes in respect to batch size.
-
Execute the runs with some config parameter that allows you to identify them easily, like tags:
python train.py -m logger=csv datamodule.batch_size=16,32,64,128 tags=["batch_size_exp"]
-
Write a script or notebook that searches over the
logs/
folder and retrieves csv logs from runs containing given tags in config. Plot the results.
Hydra creates new output directory for every executed run.
Default logging structure:
├── logs
│ ├── task_name
│ │ ├── runs # Logs generated by single runs
│ │ │ ├── YYYY-MM-DD_HH-MM-SS # Datetime of the run
│ │ │ │ ├── .hydra # Hydra logs
│ │ │ │ ├── csv # Csv logs
│ │ │ │ ├── wandb # Weights&Biases logs
│ │ │ │ ├── checkpoints # Training checkpoints
│ │ │ │ └── ... # Any other thing saved during training
│ │ │ └── ...
│ │ │
│ │ └── multiruns # Logs generated by multiruns
│ │ ├── YYYY-MM-DD_HH-MM-SS # Datetime of the multirun
│ │ │ ├──1 # Multirun job number
│ │ │ ├──2
│ │ │ └── ...
│ │ └── ...
│ │
│ └── debugs # Logs generated when debugging config is attached
│ └── ...
You can change this structure by modifying paths in hydra configuration.
PyTorch Lightning supports many popular logging frameworks: Weights&Biases, Neptune, Comet, MLFlow, Tensorboard.
These tools help you keep track of hyperparameters and output metrics and allow you to compare and visualize results. To use one of them simply complete its configuration in configs/logger and run:
python train.py logger=logger_name
You can use many of them at once (see configs/logger/many_loggers.yaml for example).
You can also write your own logger.
Lightning provides convenient method for logging custom metrics from inside LightningModule. Read the docs or take a look at MNIST example.
Template comes with generic tests implemented with pytest
.
# run all tests
pytest
# run tests from specific file
pytest tests/test_train.py
# run all tests except the ones marked as slow
pytest -k "not slow"
Most of the implemented 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 execute them once in a while to speed up the development.
Currently, the tests cover cases like:
- running 1 train, val and test step
- running 1 epoch on 1% of data, saving ckpt and resuming for the second epoch
- running 2 epochs on 1% of data, with DDP simulated on CPU
And many others. You should be able to modify them easily for your use case.
There is also @RunIf
decorator implemented, that allows you to run tests only if certain conditions are met, e.g. GPU is available or system is not windows. See the examples.
You can define hyperparameter search by adding new config file to configs/hparams_search.
Show example hyperparameter search config
# @package _global_
defaults:
- override /hydra/sweeper: optuna
# choose metric which will be optimized by Optuna
# make sure this is the correct name of some metric logged in lightning module!
optimized_metric: "val/acc_best"
# here we define Optuna hyperparameter search
# it optimizes for value returned from function with @hydra.main decorator
hydra:
sweeper:
_target_: hydra_plugins.hydra_optuna_sweeper.optuna_sweeper.OptunaSweeper
# 'minimize' or 'maximize' the objective
direction: maximize
# total number of runs that will be executed
n_trials: 20
# choose Optuna hyperparameter sampler
# docs: https://optuna.readthedocs.io/en/stable/reference/samplers.html
sampler:
_target_: optuna.samplers.TPESampler
seed: 1234
n_startup_trials: 10 # number of random sampling runs before optimization starts
# define hyperparameter search space
params:
model.optimizer.lr: interval(0.0001, 0.1)
datamodule.batch_size: choice(32, 64, 128, 256)
model.net.lin1_size: choice(64, 128, 256)
model.net.lin2_size: choice(64, 128, 256)
model.net.lin3_size: choice(32, 64, 128, 256)
Next, execute it with: python train.py -m hparams_search=mnist_optuna
Using this approach doesn't require adding any boilerplate to code, everything is defined in a single config file. The only necessary thing is to return the optimized metric value from the launch file.
You can use different optimization frameworks integrated with Hydra, like Optuna, Ax or Nevergrad.
The optimization_results.yaml
will be available under logs/task_name/multirun
folder.
This approach doesn't support advanced techniques like prunning - for more sophisticated search, you should probably write a dedicated optimization task (without multirun feature).