TopoNNOps is a comprehensive and highly flexible framework for training, evaluating, and optimising neural networks for the real-time identification and retention of beauty hadrons during Run 3 of the LHCb experiment. The framework is designed for maximum flexibility, supporting both standard unconstrained and advanced (monotonic) Lipschitz-constrained architectures. It is built with modularity in mind, leveraging hydra for configuration management and MLflow for experiment tracking, making it an ideal tool for both rapid prototyping and large-scale hyperparameter optimisation.
This document provides a detailed walkthrough of the entire codebase, its functionalities, and how to get started with training and experimentation.
- Features
- Quickstart
- Getting Started
- Project Structure and Modularity
- File-by-File Codebase Breakdown
- Configuration Deep Dive
- Model Architectures
- Training and Experimentation
- Contributing
- License
- Multiple Model Architectures: Choose between standard unconstrained networks or Lipschitz-constrained networks for robust and stable predictions.
- Monotonicity Constraints: Enforce feature-specific monotonicity, a crucial requirement for certain physics-motivated applications.
- Flexible Configuration: Utilise
hydrafor easy and modular configuration of models, optimizers, and training parameters via YAML files. - Comprehensive Experiment Tracking: Integrated with
MLflowto log parameters, metrics, and artifacts, enabling reproducible research and easy comparison of experiments. - Advanced Training Loop: The
Trainerclass includes support for mixed-precision training, gradient clipping, learning rate scheduling, and early stopping. - Rich Visualization: Automatically generate performance dashboards, including ROC curves, confusion matrices, and learning curves, logged directly to MLflow.
- Distributed Training: Supports multi-GPU training using
torch.distributedfor accelerated experimentation.
-
Install dependencies:
pip install -r requirements.txt
-
Set up MLflow:
bash setup_mlflow_remote.sh
-
Run an experiment:
The following command trains a
ThreeBodytrigger model with alambda_discoof2.0.python main.py \ +use_distributed=False \ training.lambda_disco=2.0 \ trigger=ThreeBody \ paths.train_data=/ceph/submit/data/user/b/blaised/hlt2topo_sp_maxstats/scratch/ThreeBody/imbalanced/train.pkl \ paths.test_data=/ceph/submit/data/user/b/blaised/hlt2topo_sp_maxstats/scratch/ThreeBody/imbalanced/test.pklYou can find more examples in
experiment.sh.
This project requires Python 3.8+ and PyTorch. Install all dependencies using:
```bash
pip install -r requirements.txt
For Lipschitz-constrained networks with monotonicity constraints, you'll also need the monotonicnetworks package:
pip install monotonicnetworksThe quickest way to get started is to run one of the pre-configured experiments. The experiment.sh script provides an excellent example of how to launch multiple training runs with different hyperparameters.
To run a single training instance, you can execute the main script directly:
python main.pyThis will use the default configuration specified in config/config.yaml. You can easily override any configuration parameter from the command line:
python main.py model.layer_dims=[128,64,32] training.batch_size=512Before running, ensure the MLflow tracking server is running. You can set this up using the provided script:
bash setup_mlflow_remote.shThe project is designed to be highly modular, with a clear separation of concerns. This is primarily achieved through the use of hydra for configuration and a well-defined project structure. The core idea is that the code defines the how (e.g., how to build a model, how to run a training loop), while the configuration files define the what (e.g., what model to build, what hyperparameters to use).
This modularity allows for easy experimentation and extension. For example, to try a new model architecture, you only need to add a new class in models.py and a corresponding configuration file in config/model/. No changes are needed to the core training logic.
TopoNNOps/
├── config/ # Hydra configuration files
│ ├── config.yaml # Main configuration entrypoint
│ ├── features.yml # Feature definitions and monotonicity constraints
│ └── ...
├── data.py # Data loading, preprocessing, and sampling
├── main.py # Main training script and entrypoint
├── models.py # Neural network architectures
├── trainer.py # The core training and evaluation loop
├── loss.py # Custom loss functions
├── requirements.txt # Project dependencies
├── experiment.sh # Example script for running experiments
├── setup_mlflow_remote.sh # Script to start the MLflow server
├── visualization.py # Performance visualization tools
└── ...
This section provides a detailed description of each file in the project, explaining its purpose and functionality.
-
main.py: The main entrypoint for the training pipeline. It useshydrato parse the configuration, sets up the data module, model, optimizer, and criterion, and then launches the training process. It also handles the setup for both single-GPU and distributed multi-GPU training. -
trainer.py: Contains theTrainerclass, which encapsulates the entire training and evaluation loop. It handles everything from the training step (including mixed-precision and gradient clipping) to evaluation, metric calculation, and logging to MLflow. It also orchestrates the generation of visualizations. -
loss.py: Defines custom loss functions used in the project, such asFocalLoss,DisCoLoss, andMoDeLossWrapper, providing more advanced options beyond standard binary cross-entropy.
-
config/config.yaml: The mainhydraconfiguration file. It sets the defaults for the model, optimizer, and other parameters, and includes the MLflow configuration. This is the central place to define your experiment's setup. -
config/model/*.yaml: These files define the specific architectures for the different models. For example,lipschitz.yamlcontains the parameters for theLipschitzNetmodel. -
config/optimizer/adam.yaml: Defines the parameters for the Adam optimizer. -
config/features.yml: A crucial file that defines the input features for the models, their transformations, and any monotonicity constraints. This allows for easy experimentation with different feature sets.
-
data.py: Implements theLHCbMCModule, which is responsible for all aspects of data handling. This includes loading the raw data, applying preprocessing and transformations, handling the signal-to-background ratio, and creating theDataLoaderinstances for training and testing. -
preprocessing.py: Contains theDataPreprocessorclass, which handles the actual feature transformations, such as scaling and clipping.
models.py: Defines the neural network architectures.UnconstrainedNet: A standard, fully-customizable feed-forward neural network.LipschitzNet: A modern implementation of a Lipschitz-constrained network using themonotonicnetworkslibrary, with support for monotonicity constraints.LipschitzLegacyNet: A legacy implementation of a Lipschitz-constrained network for backward compatibility.
-
model_persistence.py: A utility for saving and loading models. -
pyproject.toml: Project metadata and dependencies. -
requirements.txt: A list of all Python dependencies for the project. -
setup_mlflow_remote.sh: A shell script to easily set up and run an MLflow tracking server. -
experiment.sh: An example script demonstrating how to run a series of experiments with different hyperparameters, showcasing the power of thehydracommand-line override functionality.
-
visualization.py: Contains theModelPerformanceclass, which generates a comprehensive performance dashboard including ROC curves, confusion matrices, and learning curves. These visualizations are automatically logged to MLflow. -
plot_tools.py: Provides helper functions and tools for creating plots. -
evals.ipynb&evals.py: A Jupyter notebook and a Python script, respectively, for performing more detailed evaluations of trained models. -
physics.ipynb: A notebook for conducting physics-specific analysis and studies. -
stress_test_lipschitz.py: A script designed to stress-test the Lipschitz-constrained models under various conditions.
This project uses hydra for managing configurations. This allows for a clean separation of the code from the configuration and makes it easy to run experiments with different settings.
The main configuration is in config/config.yaml. You can define different model architectures, optimizers, and training parameters in separate YAML files (e.g., config/model/lipschitz.yaml) and then compose them in the main config.
One of the most powerful features of hydra is the ability to override any configuration parameter from the command line. For example, to change the learning rate and number of epochs, you can run:
python main.py optimizer.lr=0.005 training.num_epochs=50This is the main entrypoint for the configuration. It defines the overall structure of the experiment.
defaults: This section is used to compose the configuration from other files. For example,model: lipschitz_monotonictellshydrato load thelipschitz_monotonic.yamlfile from theconfig/modeldirectory.mlflow: Configures the MLflow integration, including the experiment name and tracking URI.trigger: Specifies the trigger type (e.g.,TwoBody,ThreeBody), which determines which set of features to use fromfeatures.yml.features_config_path: The path to the feature configuration file.metrics: Configures the metrics to be computed during evaluation.training: Defines the main training parameters, such as the number of epochs, batch size, loss function, and more.scheduler: Configures the learning rate scheduler.paths: Defines the paths to the training and test data, and where to save the models.
These files define the hyperparameters for the different model architectures.
identifier: A string that identifies the model architecture. This is used bymain.pyto select the correct model class.layer_dims: A list of integers defining the number of neurons in each hidden layer.lip_const: The Lipschitz constant for Lipschitz-constrained models.monotonic: A boolean flag to enable or disable monotonicity constraints.activation_fn: The activation function to use.- Other parameters: Each file can contain other parameters specific to the model architecture, such as
dropout_rate,batch_norm, etc.
This file configures the Adam optimizer.
name: The name of the optimizer (e.g.,adam).lr: The learning rate.weight_decay: The L2 regularization factor.beta1,beta2: The exponential decay rates for the moment estimates.
These files are crucial for defining the input to the models.
features: A dictionary where the keys are the trigger types (e.g.,TwoBody) and the values are dictionaries of feature names and their monotonicity constraints (0 for no constraint, 1 for monotonically increasing).spectators: A dictionary defining the spectator variables for which a flat efficiency is desired.transforms: A dictionary defining the preprocessing transformations to be applied to each feature (e.g.,gev,log).
MLflow is used for tracking experiments. The Trainer class automatically logs the following to your MLflow server:
- Parameters: All configuration parameters from your
hydraconfig. - Metrics: Training and evaluation loss, as well as any other metrics you configure (e.g., AUC, accuracy).
- Artifacts:
- The trained model.
- A
model_metadata.jsonfile with details about the features and architecture. - Performance visualization plots.
- Checkpoints of the best performing model.
To view your experiments, start the MLflow UI after running the setup_mlflow_remote.sh script:
mlflow uiA flexible and customizable standard neural network. Key features include:
- Customizable Architecture: Define the number of layers and their dimensions.
- Activation Functions: Choose from a variety of activation functions (ReLU, LeakyReLU, etc.).
- Regularization: Optional batch normalization, dropout, and L1 regularization.
- Residual Connections: Option to add residual connections between layers.
A neural network with a guaranteed Lipschitz constant, which helps in creating more robust and stable models. This implementation uses the modern monotonicnetworks library.
- Global Lipschitz Constant: Enforces a global Lipschitz constant on the network.
- GroupSort Activation: Uses the GroupSort activation function, which is essential for maintaining the Lipschitz property.
- Monotonicity Constraints: Can enforce feature-specific monotonicity constraints, which is critical for ensuring that the model's output changes in a predictable way with respect to certain input features.
A legacy implementation of the Lipschitz-constrained network, maintained for reproducibility and comparison with previous results.
The trainer.py module is the heart of the training pipeline. The Trainer class provides a comprehensive training loop with:
- Mixed Precision Training: For faster training on modern GPUs.
- Gradient Clipping: To prevent exploding gradients.
- Learning Rate Scheduling: To adjust the learning rate during training.
- Early Stopping: To stop training when the performance on the validation set stops improving.
- Detailed Logging: Logs a wide range of metrics to MLflow, including parameter statistics (gradients and weights) for debugging and monitoring training stability.
The experiment.sh script provides a template for running multiple experiments. It demonstrates how to vary a single hyperparameter (training.lambda_disco in this case) across multiple runs. This can be easily adapted to perform more complex hyperparameter scans.
Each run will be logged as a separate experiment in MLflow, allowing you to easily compare their performance and find the optimal set of hyperparameters for your task.
Contributions are welcome! If you'd like to contribute, please feel free to fork the repository and submit a pull request. When making changes, please ensure that you update tests as appropriate.
This project is licensed under the MIT License. See the LICENSE file for details.