Bensemble: Modular Bayesian Deep Learning & Ensembling
Bensemble is a PyTorch library for combining neural networks, estimating predictive uncertainty, and calibrating predictions.
Key Resources
| Resource | Description |
|---|---|
| 📘 Documentation | Full API reference and user guides. |
| 📝 Tech Report | In-depth technical details and theoretical background. |
| ✍️ Blog Post | Summary of the project and motivation. |
| 📊 Benchmarks | Comparison of methods on standard datasets. |
Features
- Combine independently trained PyTorch models or draw predictions from one model with MC dropout using
Ensemble. - Select ensembles with random search (NES-RS), evolutionary search (NES-RE), or Bayesian sampling (NES-BS).
- Split predictive uncertainty into aleatoric and epistemic components for classification and regression.
- Calibrate classifiers with temperature or vector scaling. Evaluate predictions with expected calibration error (ECE), Brier score, and negative log-likelihood.
Installation
pip install bensemble
With uv, run uv pip install bensemble.
Quick Start
Combine trained classifiers
models is a list of trained PyTorch classifiers that return logits for the same classes in the same order. x is a batch of inputs.
import torch
from bensemble.core.ensemble import Ensemble
from bensemble.uncertainty import decompose_classification_uncertainty
ensemble = Ensemble.from_models(models).eval()
with torch.no_grad():
member_probs = ensemble.predict_members(x).softmax(dim=-1) # [members, batch, classes]
probs = member_probs.mean(dim=0)
total, aleatoric, epistemic = decompose_classification_uncertainty(member_probs)
For a runnable example with training and calibration, see Getting Started.
Variational inference
Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
import torch
import torch.nn as nn
from bensemble.layers import BayesianLinear
from bensemble.losses import VariationalLoss, GaussianLikelihood
from bensemble.utils import get_total_kl, predict_with_uncertainty
# 1. Define Model using Bayesian Layers
model = nn.Sequential(
BayesianLinear(10, 50, prior_sigma=1.0),
nn.ReLU(),
BayesianLinear(50, 1, prior_sigma=1.0),
)
# 2. Define Objectives (Likelihood + Divergence)
likelihood = GaussianLikelihood()
criterion = VariationalLoss(likelihood, alpha=1.0)
optimizer = torch.optim.Adam(list(model.parameters()) + list(likelihood.parameters()), lr=0.01)
# 3. Standard PyTorch Training Loop
model.train()
for epoch in range(50): # Dummy loop
x, y = torch.randn(10, 10), torch.randn(10, 1)
optimizer.zero_grad()
loss = criterion(model(x), y, get_total_kl(model))
loss.backward()
optimizer.step()
# 4. Predict with Uncertainty
mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
For Rényi training (alpha != 1), use matched weight draws and log densities:
from bensemble.utils import sample_with_log_probs
criterion = VariationalLoss(likelihood, alpha=0.5)
optimizer.zero_grad()
predictions, log_p, log_q = sample_with_log_probs(model, x, num_samples=8)
loss = criterion(predictions, y, log_prior=log_p, log_posterior=log_q)
loss.backward()
optimizer.step()
A scalar KL is accepted only for the ordinary ELBO (alpha=1). See the
Rényi guide for the objective and
minibatch scaling.
Algorithms & Demos
Start with the examples guide: four ordered tutorials cover
ensembling, MC Dropout, variational inference, and Laplace; examples/search/
contains the three NES methods. All seven notebooks use synthetic data on CPU
and include instructions for running them from a fresh kernel.
| Method | Description |
|---|---|
| Deep Ensembles | Train independent classifiers, calibrate on held-out data, and decompose uncertainty. |
| Monte Carlo Dropout | Implicit ensembling by keeping dropout active at test time. |
| Neural Ensemble Search (NES-RS / NES-RE) | Search architectures and select an ensemble on a separate validation set. |
| NES via Bayesian Sampling | Select from independently trained candidates using a validation-loss posterior and SVGD-inspired refinement. |
| Variational Inference | Learn a Gaussian approximation with the Local Reparameterization Trick. |
| Variational Rényi | Train with matched weight draws and per-sample prior/posterior log densities. |
| Laplace Approximation | Estimate curvature around a trained network and sample an ensemble. |
| Probabilistic Backprop | Propagate moments using Assumed Density Filtering (ADF); see the algorithm guide. |
Structure
bensemble/
├── core/ # Base protocols, ensemble abstractions, and adapters
│ ├── ensemble.py # Central `Ensemble` class
│ ├── member.py # Adapters for explicit and stochastic models
│ └── types.py # Protocols: Predictor, KLProvider, PosteriorSource
│
├── layers/ # Bayesian Layers for Variational Inference
│ ├── base.py # BaseBayesianLayer: KL divergence, SNR-based pruning
│ ├── linear.py # Bayesian Linear layer
│ └── conv.py # Bayesian Convolution layer
│
├── methods/ # Standalone posterior-approximation engines
│ ├── laplace_approximation.py # Laplace with K-FAC curvature
│ └── probabilistic_backpropagation.py # PBP (ADF-based)
│
├── search/ # Neural Ensemble Search algorithms
│ ├── nes.py # NES-RS & NES-RE (RandomSearcher, EvolutionarySearcher)
│ ├── bayesian.py # NESBS (discrete, SVGD-inspired sampler)
│ ├── selection.py # Greedy forward selection, scoring criteria
│ └── space.py # SearchSpace protocol
│
├── diversity/ # Methods to induce ensemble variation
│ └── dropout.py # Monte Carlo Dropout wrapper
│
├── uncertainty/ # Uncertainty analysis
│ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
│
├── calibration/ # Post-hoc model calibration tools
│ └── scaling.py # Temperature Scaling and Vector Scaling
│
├── losses.py # VariationalLoss, GaussianLikelihood
├── utils.py # get_total_kl, predict_with_uncertainty, etc.
└── metrics.py # Scoring rules: ECE, NLL, Brier Score
Development Setup
If you want to contribute to bensemble or run tests, we recommend using uv.
# 1. Clone the repository
git clone https://github.com/intsystems/bensemble.git
cd bensemble
# 2. Create and activate virtual environment via uv
uv venv
source .venv/bin/activate # on Windows: .venv\Scripts\activate
# 3. Install in editable mode with dev dependencies
uv pip install -e ".[dev]"
Run Tests
pytest tests/
Linting
We use ruff to keep code clean:
ruff check .
ruff format .
Authors
Developed by:
License
This project is licensed under the MIT License - see the LICENSE file for details.
Metadata
Release files for bensemble 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bensemble-0.3.0.tar.gz | 45.6 kB | Without provenance | Details for bensemble-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bensemble-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for bensemble-0.3.0-py3-none-any.whl |
Total release size: 87.6 kB
Release files / bensemble-0.3.0.tar.gz
| Download URL | bensemble-0.3.0.tar.gz |
|---|---|
| Size | 45.6 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d9127d611b2800fa58854345c1d13773f9ad0b9377518cde80df3fcf1a02b1a3
|
|
BLAKE2b-256 checksum How to use checksums |
12aca8a2bd8ea58fc6877e63a1a4b3eb53c9bc68c8bd5ca81ecea661c73e4a7f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.19
|
Release files / bensemble-0.3.0-py3-none-any.whl
| Download URL | bensemble-0.3.0-py3-none-any.whl |
|---|---|
| Size | 42.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
a12cd6055dc45345ecfa1b8bf9450674b8434c8b43541faf6cd48a157bb7a2eb
|
|
BLAKE2b-256 checksum How to use checksums |
7b2061f488c0494fa60612532c591728d0d38450e70d277d073c70213ae3f150
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.19
|
Security for bensemble 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.