doloresgarcia / weaver-core

Streamlined neural network training.
MIT License
1 stars 0 forks source link

Weaver

Weaver aims at providing a streamlined yet flexible machine learning R&D framework for high energy physics (HEP) applications. It puts particular emphases on:

Compared to its predecessor NNTools, Weaver simplifies the data processing pipeline by running all the pre-processing on-the-fly, without the necessity of creating an intermediate transformed dataset (though it still supports that). The neural network training now uses the more widely adopted PyTorch instead of Apache MXNet.

Set up your environment

The Weaver package requires Python 3.7+ and a number of packages like numpy, scikit-learn, PyTorch, etc. To run the neural network training, a Nvidia GPU with CUDA support is needed.

To manage the Python environment, we recommend using Miniconda. Below are the instructions to set up Miniconda and install the required packages. This needs to be done only once.

Install Miniconda (if you don't already have it)

wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh
# Follow the instructions to finish the installation

# Make sure to choose `yes` for the following one to let the installer initialize Miniconda3
# > Do you wish the installer to initialize Miniconda3
# > by running conda init? [yes|no]

# disable auto activation of the base environment
conda config --set auto_activate_base false

Verify the installation is successful by running conda info and check if the paths are pointing to your Miniconda installation.

If you cannot run conda command, check if you need to add the conda path to your PATH variable in your bashrc/zshrc file, e.g.,

export PATH="$HOME/miniconda3/bin:$PATH"

Set up a conda environment and install the packages

# create a new conda environment
conda create -n weaver python=3.7

# activate the environment
conda activate weaver

# install pytorch, follow instructions for your OS/CUDA version at:
# https://pytorch.org/get-started
# pip install torch

# install weaver, this will install also all the dependencies except for PyTorch
pip install weaver-core

Alternatively, if you want to install weaver-core in editable/development mode:

git clone git@github.com:hqucms/weaver-core.git
cd weaver-core
pip install -e .

Prepare your configuration files

To train a neural network using Weaver, you need to prepare:

Data configuration file

The data configuration file is a YAML format file describing how to process the input data. It needs the following sections:

An example of the data configuration file is data/ak15_points_pf_sv.yaml. For more details, check utils/data/config.py and utils/dataset.py.

Model configuration file

The model configuration file specifies the neural network model and the loss function. It needs to implement the get_model function (required) and the get_loss fucntion (optional, default is torch.nn.CrossEntropyLoss()) in the following signatures:

def get_model(data_config, **kwargs):
    model = ... # instance of PyTorch Module
    model_info = {
        'input_names':...,
        'input_shapes':...,
        'output_names':...,
        'dynamic_axes':...,
        }
    return model, model_info

# `get_loss` is optional
# if not provided, fallback to use `torch.nn.CrossEntropyLoss()`
def get_loss(data_config, **kwargs):
    loss_func = ...
    return loss_func

An example of the model configuration file is networks/particle_net_pf_sv.py.

Start running!

The weaver command is the top-level entry to run for training a neural net, getting prediction from trained models, and exporting trained models to ONNX for production. The corresponding script file is weaver/train.py. To check all the command-line options for weaver, run weaver -h. Examples for training, inference and model exportation are shown below:

Training

weaver --data-train '/path/to/train_files/*/*/*/*/output_*.root' \
 --data-test '/path/to/train_files/*/*/*/*/output_*.root' \
 --data-config data/ak15_points_pf_sv.yaml \
 --network-config networks/particle_net_pf_sv.py \
 --model-prefix /path/to/models/prefix \
 --gpus 0,1,2,3 --batch-size 512 --start-lr 5e-3 --num-epochs 20 --optimizer ranger \
 --log logs/train.log

Note:

Prediction/Inference

Once you have a trained model, you can load it to run prediction and test its performance, e.g.,

weaver --predict --data-test '/path/to/test_files/*/*/*/*/output_*.root' \
 --data-config data/ak15_points_pf_sv.yaml \
 --network-config networks/particle_net_pf_sv.py \
 --model-prefix /path/to/models/prefix_best_epoch_state.pt \
 --gpus 0,1,2,3 --batch-size 512 \
 --predict-output /path/to/output.root

Note:

Model exportation

When you are satisfied with the trained model, you could export it from PyTorch to ONNX format for inference (e.g., using ONNXRuntime):

weaver -c data/ak15_points_pf_sv.yaml -n networks/particle_net_pf_sv.py -m /path/to/models/prefix_best_epoch_state.pt --export-onnx model.onnx

More about data loading and processing

To cope with large datasets, the data loader in Weaver does not read all input files into memory, but rather load the input events incrementally. The implementation follows the PyTorch iterable-style datasets interface. To speed up the data loading process, multi-process data loading is also implemented.

[Note] For small dataset that actually fits into the memory, use --in-memory to load the whole dataset (and perform the preprocessing) only once and keep it in memory for the entire run.

The data loader in Weaver operates in different ways for training and prediction/inference.

Training mode

For training, properly mixing events of different types (e.g., signal/background processes, different kinematic phase space, etc.) and random shuffling are often helpful for improving the performance and stability of the training.

To achieve this efficiently, Weaver divides all input files randomly into N groups and will load them concurrently with N worker threads (N is set by --num-workers). Then, two data loading strategies are available at the worker thread level:

[Note] If the dataset is stored on EOS and the size is not very large, it may be more efficient to transfer the files to the local storage of the worker node when submitting batch jobs. This can be done on-the-fly by adding the --copy-inputs option.

Prediction/Inference mode

Contrary to training, for prediction/inference, the events are not mixed/shuffled. Instead, the order of the events are preserved, exactly as in the input files. Therefore, only the "file-based" strategy described above is supported, and the --fetch-step is fixed to 1.

For more details of the data loader, please check utils/dataset.py.

Performance consideration

Loading data from disk can often become a bottleneck. Here are a few tips to get better data loading performance:

f.SetCompressionAlgorithm(ROOT::kLZ4);
f.SetCompressionLevel(4);