bensemble 0.2.1__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. {bensemble-0.2.1 → bensemble-0.3.0}/PKG-INFO +80 -64
  2. bensemble-0.3.0/README.md +231 -0
  3. bensemble-0.3.0/bensemble/__init__.py +28 -0
  4. bensemble-0.3.0/bensemble/calibration/scaling.py +162 -0
  5. bensemble-0.3.0/bensemble/core/ensemble.py +109 -0
  6. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/core/member.py +38 -20
  7. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/core/types.py +8 -4
  8. bensemble-0.3.0/bensemble/diversity/__init__.py +3 -0
  9. bensemble-0.3.0/bensemble/diversity/dropout.py +28 -0
  10. bensemble-0.3.0/bensemble/layers/__init__.py +4 -0
  11. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/layers/base.py +2 -1
  12. bensemble-0.3.0/bensemble/layers/conv.py +135 -0
  13. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/layers/linear.py +18 -14
  14. bensemble-0.3.0/bensemble/losses.py +189 -0
  15. bensemble-0.3.0/bensemble/methods/__init__.py +9 -0
  16. bensemble-0.3.0/bensemble/methods/laplace_approximation.py +500 -0
  17. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/methods/probabilistic_backpropagation.py +91 -52
  18. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/metrics.py +10 -5
  19. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/search/bayesian.py +29 -21
  20. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/search/nes.py +12 -14
  21. bensemble-0.3.0/bensemble/search/selection.py +140 -0
  22. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/search/space.py +1 -1
  23. bensemble-0.3.0/bensemble/uncertainty/__init__.py +6 -0
  24. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/uncertainty/decomposition.py +15 -9
  25. bensemble-0.3.0/bensemble/utils.py +273 -0
  26. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble.egg-info/PKG-INFO +80 -64
  27. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble.egg-info/SOURCES.txt +5 -2
  28. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble.egg-info/requires.txt +9 -0
  29. {bensemble-0.2.1 → bensemble-0.3.0}/pyproject.toml +12 -3
  30. bensemble-0.3.0/tests/test_examples.py +104 -0
  31. bensemble-0.3.0/tests/test_losses.py +166 -0
  32. bensemble-0.3.0/tests/test_renyi_loss.py +225 -0
  33. {bensemble-0.2.1 → bensemble-0.3.0}/tests/test_utils.py +4 -2
  34. bensemble-0.3.0/tests/test_weight_sampling.py +204 -0
  35. bensemble-0.2.1/README.md +0 -223
  36. bensemble-0.2.1/bensemble/__init__.py +0 -24
  37. bensemble-0.2.1/bensemble/calibration/scaling.py +0 -126
  38. bensemble-0.2.1/bensemble/core/base.py +0 -76
  39. bensemble-0.2.1/bensemble/core/ensemble.py +0 -57
  40. bensemble-0.2.1/bensemble/diversity/dropout.py +0 -13
  41. bensemble-0.2.1/bensemble/layers/__init__.py +0 -3
  42. bensemble-0.2.1/bensemble/layers/conv.py +0 -102
  43. bensemble-0.2.1/bensemble/losses.py +0 -81
  44. bensemble-0.2.1/bensemble/methods/__init__.py +0 -12
  45. bensemble-0.2.1/bensemble/methods/laplace_approximation.py +0 -483
  46. bensemble-0.2.1/bensemble/search/selection.py +0 -128
  47. bensemble-0.2.1/bensemble/uncertainty/__init__.py +0 -0
  48. bensemble-0.2.1/bensemble/utils.py +0 -100
  49. bensemble-0.2.1/tests/test_losses.py +0 -81
  50. {bensemble-0.2.1 → bensemble-0.3.0}/LICENSE +0 -0
  51. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/calibration/__init__.py +0 -0
  52. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/core/__init__.py +0 -0
  53. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble/search/__init__.py +5 -5
  54. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble.egg-info/dependency_links.txt +0 -0
  55. {bensemble-0.2.1 → bensemble-0.3.0}/bensemble.egg-info/top_level.txt +0 -0
  56. {bensemble-0.2.1 → bensemble-0.3.0}/setup.cfg +0 -0
  57. {bensemble-0.2.1 → bensemble-0.3.0}/tests/test_metrics.py +0 -0
@@ -1,12 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: bensemble
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: Library with implementations of various ensembling methods.
5
- Author: Dmitrii Vasilenko, Fedor Sobolevsky, Muhammadsharif Nabiev, Vadim Kasyuk
5
+ Author: Dmitrii Vasilenko, Fedor Sobolevsky, Muhammadsharif Nabiev, Vadim Kasiuk
6
6
  License: MIT
7
7
  Project-URL: Homepage, https://github.com/intsystems/bensemble
8
8
  Project-URL: Bug_Tracker, https://github.com/intsystems/bensemble/issues
9
- Project-URL: Documentation, https://github.com/intsystems/bensemble#readme
9
+ Project-URL: Documentation, https://intsystems.github.io/bensemble/
10
10
  Project-URL: Source, https://github.com/intsystems/bensemble
11
11
  Keywords: bayesian,neural network,ensemble,variational inference,renyi
12
12
  Classifier: Programming Language :: Python :: 3
@@ -37,6 +37,14 @@ Requires-Dist: mkdocstrings[python]; extra == "docs"
37
37
  Requires-Dist: mkdocs-minify-plugin; extra == "docs"
38
38
  Requires-Dist: pymdown-extensions; extra == "docs"
39
39
  Requires-Dist: python-markdown-math; extra == "docs"
40
+ Provides-Extra: benchmarks
41
+ Requires-Dist: torchvision>=0.20; extra == "benchmarks"
42
+ Requires-Dist: tqdm; extra == "benchmarks"
43
+ Requires-Dist: pandas; extra == "benchmarks"
44
+ Requires-Dist: tabulate; extra == "benchmarks"
45
+ Requires-Dist: seaborn; extra == "benchmarks"
46
+ Requires-Dist: scikit-learn; extra == "benchmarks"
47
+ Requires-Dist: ucimlrepo; extra == "benchmarks"
40
48
  Dynamic: license-file
41
49
 
42
50
  # Bensemble: Modular Bayesian Deep Learning & Ensembling
@@ -47,8 +55,9 @@ Dynamic: license-file
47
55
  [![Docs](https://img.shields.io/badge/docs-online-blue.svg)](https://intsystems.github.io/bensemble/)
48
56
  [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
49
57
  [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
58
+ [![JOSS](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d/status.svg)](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d)
50
59
 
51
- **Bensemble** is a production-ready, lightweight library for Bayesian Deep Learning and Neural Network Ensembling.
60
+ **Bensemble** is a PyTorch library for combining neural networks, estimating predictive uncertainty, and calibrating predictions.
52
61
 
53
62
  ---
54
63
 
@@ -59,80 +68,57 @@ Dynamic: license-file
59
68
  | 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
60
69
  | 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
61
70
  | ✍️ **[Blog Post](https://github.com/intsystems/bensemble/blob/master/blog/bensemble-blogpost.md)** | Summary of the project and motivation. |
62
- | 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/notebooks/benchmark.ipynb)** | Comparison of methods on standard datasets. |
71
+ | 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/benchmarks)** | Comparison of methods on standard datasets. |
63
72
 
64
73
  ---
65
74
 
66
75
  ## Features
67
76
 
68
- - **PyTorch-Native**: No hidden training loops. Use standard PyTorch to train your models, and use Bensemble for inference, ensembling, and analytics.
69
- - **Unified Ensembling API**: Seamlessly combine explicit models (Deep Ensembles, NAS) and implicit methods (MC Dropout) via a single `Ensemble` interface.
70
- - **Neural Ensemble Search (NES)**: Algorithms to automatically search for diverse architectures using NNI and Stein Variational Gradient Descent (SVGD).
71
- - **Uncertainty Analytics**: Principled decomposition of predictive uncertainty into *aleatoric* (data noise) and *epistemic* (model ignorance) components.
72
- - **Model Calibration & Metrics**: Evaluate models using Expected Calibration Error (ECE), Brier Score, and NLL. Fix overconfident networks post-hoc with Temperature and Vector Scaling.
77
+ - Combine independently trained PyTorch models or draw predictions from one model with MC dropout using `Ensemble`.
78
+ - Select ensembles with random search (NES-RS), evolutionary search (NES-RE), or Bayesian sampling (NES-BS).
79
+ - Split predictive uncertainty into aleatoric and epistemic components for classification and regression.
80
+ - Calibrate classifiers with temperature or vector scaling. Evaluate predictions with expected calibration error (ECE), Brier score, and negative log-likelihood.
73
81
 
74
82
  ---
75
83
 
76
84
  ## Installation
77
85
 
78
- You can install `bensemble` using pip:
79
-
80
86
  ```bash
81
87
  pip install bensemble
82
88
  ```
83
89
 
84
- Or, using [uv](https://github.com/astral-sh/uv) for lightning-fast installation:
85
-
86
- ```bash
87
- uv pip install bensemble
88
- ```
90
+ With [uv](https://github.com/astral-sh/uv), run `uv pip install bensemble`.
89
91
 
90
92
  ---
91
93
 
92
94
  ## Quick Start
93
95
 
94
- ### Example 1: Ensembling, Calibration & Uncertainty
96
+ ### Combine trained classifiers
95
97
 
96
- Easily ensemble standard PyTorch models, calibrate them, and decompose their uncertainty to detect Out-Of-Distribution data.
98
+ `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.
97
99
 
98
100
  ```python
99
101
  import torch
100
- import torch.nn as nn
102
+
101
103
  from bensemble.core.ensemble import Ensemble
102
- from bensemble.calibration.scaling import TemperatureScaling
103
104
  from bensemble.uncertainty import decompose_classification_uncertainty
104
- from bensemble.metrics import expected_calibration_error
105
-
106
- # 1. Create a Deep Ensemble from standard trained PyTorch models
107
- models = [nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 3)) for _ in range(5)]
108
- ensemble = Ensemble.from_models(models)
109
-
110
- # 2. Calibrate the ensemble using a hold-out validation set
111
- val_logits, val_labels = torch.randn(100, 3), torch.randint(0, 3, (100,))
112
- scaler = TemperatureScaling(init_temp=1.5).fit(val_logits, val_labels)
113
-
114
- # 3. Predict on test data
115
- test_x = torch.randn(10, 10)
116
- # Returns shape: [5 models, 10 batch_size, 3 classes]
117
- logits = scaler(ensemble.predict_members(test_x))
118
- probs = torch.softmax(logits, dim=-1)
119
105
 
120
- # 4. Decompose Uncertainty & Evaluate
121
- total, aleatoric, epistemic = decompose_classification_uncertainty(probs)
122
- ece = expected_calibration_error(probs.mean(dim=0), val_labels[:10])
123
-
124
- print(f"Calibration Error (ECE): {ece:.4f}")
125
- print(f"Epistemic Uncertainty (OOD awareness): {epistemic.mean().item():.4f}")
106
+ ensemble = Ensemble.from_models(models).eval()
107
+ with torch.no_grad():
108
+ member_probs = ensemble.predict_members(x).softmax(dim=-1) # [members, batch, classes]
109
+ probs = member_probs.mean(dim=0)
110
+ total, aleatoric, epistemic = decompose_classification_uncertainty(member_probs)
126
111
  ```
127
112
 
128
- ### Example 2: Variational Inference
113
+ For a runnable example with training and calibration, see [Getting Started](https://intsystems.github.io/bensemble/getting-started/).
114
+
115
+ ### Variational inference
129
116
 
130
117
  Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
131
118
 
132
119
  ```python
133
120
  import torch
134
121
  import torch.nn as nn
135
- from torch.utils.data import DataLoader, TensorDataset
136
122
 
137
123
  from bensemble.layers import BayesianLinear
138
124
  from bensemble.losses import VariationalLoss, GaussianLikelihood
@@ -165,22 +151,42 @@ mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
165
151
  print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
166
152
  ```
167
153
 
154
+ For Rényi training (`alpha != 1`), use matched weight draws and log densities:
155
+
156
+ ```python
157
+ from bensemble.utils import sample_with_log_probs
158
+
159
+ criterion = VariationalLoss(likelihood, alpha=0.5)
160
+ optimizer.zero_grad()
161
+ predictions, log_p, log_q = sample_with_log_probs(model, x, num_samples=8)
162
+ loss = criterion(predictions, y, log_prior=log_p, log_posterior=log_q)
163
+ loss.backward()
164
+ optimizer.step()
165
+ ```
166
+
167
+ A scalar KL is accepted only for the ordinary ELBO (`alpha=1`). See the
168
+ [Rényi guide](docs/docs/algorithms/variational-renyi.md) for the objective and
169
+ minibatch scaling.
170
+
168
171
  ---
169
172
 
170
173
  ## Algorithms & Demos
171
174
 
172
- We implement a wide range of Bayesian and Ensembling approaches. Check out the interactive demos in the `notebooks/` directory:
175
+ Start with the [examples guide](examples/README.md): four ordered tutorials cover
176
+ ensembling, MC Dropout, variational inference, and Laplace; `examples/search/`
177
+ contains the three NES methods. All seven notebooks use synthetic data on CPU
178
+ and include instructions for running them from a fresh kernel.
173
179
 
174
180
  | Method | Description |
175
181
  | :--- | :--- |
176
- | **Deep Ensembles** | Naive yet powerful ensembling of independent networks with explicit uncertainty decomposition. |
177
- | **Monte Carlo Dropout** | Implicit ensembling by keeping dropout active at test time. |
178
- | **Neural Ensemble Search (NES)** | Automatically searches for diverse architectures (NES-RS/NES-RE) using NNI. |
179
- | **NES via Bayesian Sampling** | Extracts diverse subnetworks from a Supernet using Stein Variational Gradient Descent (SVGD). |
180
- | **Variational Inference** | Approximates posterior using Gaussian distributions with the *Local Reparameterization Trick*. |
181
- | **Variational Rényi** | Generalization of VI minimizing $\alpha$-divergence (VR-VI) for better robustness. |
182
- | **Laplace Approximation** | Fits a Gaussian around the MAP estimate using Kronecker-Factored Curvature (K-FAC). |
183
- | **Probabilistic Backprop** | Propagates moments through the network using Assumed Density Filtering (ADF). |
182
+ | **[Deep Ensembles](examples/01_ensemble_basics.ipynb)** | Train independent classifiers, calibrate on held-out data, and decompose uncertainty. |
183
+ | **[Monte Carlo Dropout](examples/02_mc_dropout.ipynb)** | Implicit ensembling by keeping dropout active at test time. |
184
+ | **Neural Ensemble Search ([NES-RS](examples/search/nes_rs.ipynb) / [NES-RE](examples/search/nes_re.ipynb))** | Search architectures and select an ensemble on a separate validation set. |
185
+ | **[NES via Bayesian Sampling](examples/search/nes_bayesian_sampling.ipynb)** | Select from independently trained candidates using a validation-loss posterior and SVGD-inspired refinement. |
186
+ | **[Variational Inference](examples/03_variational_inference.ipynb)** | Learn a Gaussian approximation with the *Local Reparameterization Trick*. |
187
+ | **[Variational Rényi](examples/03_variational_inference.ipynb)** | Train with matched weight draws and per-sample prior/posterior log densities. |
188
+ | **[Laplace Approximation](examples/04_laplace.ipynb)** | Estimate curvature around a trained network and sample an ensemble. |
189
+ | **[Probabilistic Backprop](docs/docs/algorithms/pbp.md)** | Propagate moments using Assumed Density Filtering (ADF); see the algorithm guide. |
184
190
 
185
191
  ---
186
192
 
@@ -190,26 +196,36 @@ We implement a wide range of Bayesian and Ensembling approaches. Check out the i
190
196
  bensemble/
191
197
  ├── core/ # Base protocols, ensemble abstractions, and adapters
192
198
  │ ├── ensemble.py # Central `Ensemble` class
193
- │ └── member.py # Adapters for explicit and stochastic models
199
+ │ ├── member.py # Adapters for explicit and stochastic models
200
+ │ └── types.py # Protocols: Predictor, KLProvider, PosteriorSource
194
201
  │
195
202
  ├── layers/ # Bayesian Layers for Variational Inference
203
+ │ ├── base.py # BaseBayesianLayer: KL divergence, SNR-based pruning
196
204
  │ ├── linear.py # Bayesian Linear layer
197
205
  │ └── conv.py # Bayesian Convolution layer
198
206
  │
207
+ ├── methods/ # Standalone posterior-approximation engines
208
+ │ ├── laplace_approximation.py # Laplace with K-FAC curvature
209
+ │ └── probabilistic_backpropagation.py # PBP (ADF-based)
210
+ │
199
211
  ├── search/ # Neural Ensemble Search algorithms
200
- │ ├── nes.py # NES-RS & NES-RE
201
- │ └── bayesian.py # NES via Bayesian Sampling
212
+ │ ├── nes.py # NES-RS & NES-RE (RandomSearcher, EvolutionarySearcher)
213
+ │ ├── bayesian.py # NESBS (discrete, SVGD-inspired sampler)
214
+ │ ├── selection.py # Greedy forward selection, scoring criteria
215
+ │ └── space.py # SearchSpace protocol
202
216
  │
203
- ├── diversity/ # Methods to induce ensemble variation
204
- │ └── dropout.py # Monte Carlo Dropout wrapper
217
+ ├── diversity/ # Methods to induce ensemble variation
218
+ │ └── dropout.py # Monte Carlo Dropout wrapper
205
219
  │
206
- ├── uncertainty/ # Uncertainty analysis
207
- │ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
220
+ ├── uncertainty/ # Uncertainty analysis
221
+ │ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
208
222
  │
209
- ├── calibration/ # Post-hoc model calibration tools
210
- │ └── scaling.py # Temperature Scaling and Vector Scaling
223
+ ├── calibration/ # Post-hoc model calibration tools
224
+ │ └── scaling.py # Temperature Scaling and Vector Scaling
211
225
  │
212
- └── metrics.py # Scoring rules: ECE, NLL, Brier Score
226
+ ├── losses.py # VariationalLoss, GaussianLikelihood
227
+ ├── utils.py # get_total_kl, predict_with_uncertainty, etc.
228
+ └── metrics.py # Scoring rules: ECE, NLL, Brier Score
213
229
  ```
214
230
 
215
231
  ---
@@ -255,7 +271,7 @@ Developed by:
255
271
  - [**Dmitrii Vasilenko**](https://github.com/Dimundel)
256
272
  - [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
257
273
  - [**Fedor Sobolevsky**](https://github.com/TeoSable)
258
- - [**Vadim Kasyuk**](https://github.com/KasiukVadim)
274
+ - [**Vadim Kasiuk**](https://github.com/KasiukVadim)
259
275
 
260
276
  ---
261
277
 
@@ -0,0 +1,231 @@
1
+ # Bensemble: Modular Bayesian Deep Learning & Ensembling
2
+
3
+ [![Python](https://img.shields.io/badge/python-3.10%20|%203.11%20|%203.12%20|%203.13-blue.svg)](https://www.python.org/)
4
+ [![Tests](https://github.com/intsystems/bensemble/actions/workflows/test.yml/badge.svg)](https://github.com/intsystems/bensemble/actions)
5
+ [![Codecov](https://codecov.io/gh/intsystems/bensemble/branch/master/graph/badge.svg)](https://codecov.io/gh/intsystems/bensemble)
6
+ [![Docs](https://img.shields.io/badge/docs-online-blue.svg)](https://intsystems.github.io/bensemble/)
7
+ [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
8
+ [![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
9
+ [![JOSS](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d/status.svg)](https://joss.theoj.org/papers/0d7c1f90dc95cc1a9c913a29e7922a4d)
10
+
11
+ **Bensemble** is a PyTorch library for combining neural networks, estimating predictive uncertainty, and calibrating predictions.
12
+
13
+ ---
14
+
15
+ ## Key Resources
16
+
17
+ | Resource | Description |
18
+ | :--- | :--- |
19
+ | 📘 **[Documentation](https://intsystems.github.io/bensemble/)** | Full API reference and user guides. |
20
+ | 📝 **[Tech Report](https://github.com/intsystems/bensemble/blob/master/paper/bensemble_tech_report.pdf)** | In-depth technical details and theoretical background. |
21
+ | ✍️ **[Blog Post](https://github.com/intsystems/bensemble/blob/master/blog/bensemble-blogpost.md)** | Summary of the project and motivation. |
22
+ | 📊 **[Benchmarks](https://github.com/intsystems/bensemble/blob/master/benchmarks)** | Comparison of methods on standard datasets. |
23
+
24
+ ---
25
+
26
+ ## Features
27
+
28
+ - Combine independently trained PyTorch models or draw predictions from one model with MC dropout using `Ensemble`.
29
+ - Select ensembles with random search (NES-RS), evolutionary search (NES-RE), or Bayesian sampling (NES-BS).
30
+ - Split predictive uncertainty into aleatoric and epistemic components for classification and regression.
31
+ - Calibrate classifiers with temperature or vector scaling. Evaluate predictions with expected calibration error (ECE), Brier score, and negative log-likelihood.
32
+
33
+ ---
34
+
35
+ ## Installation
36
+
37
+ ```bash
38
+ pip install bensemble
39
+ ```
40
+
41
+ With [uv](https://github.com/astral-sh/uv), run `uv pip install bensemble`.
42
+
43
+ ---
44
+
45
+ ## Quick Start
46
+
47
+ ### Combine trained classifiers
48
+
49
+ `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.
50
+
51
+ ```python
52
+ import torch
53
+
54
+ from bensemble.core.ensemble import Ensemble
55
+ from bensemble.uncertainty import decompose_classification_uncertainty
56
+
57
+ ensemble = Ensemble.from_models(models).eval()
58
+ with torch.no_grad():
59
+ member_probs = ensemble.predict_members(x).softmax(dim=-1) # [members, batch, classes]
60
+ probs = member_probs.mean(dim=0)
61
+ total, aleatoric, epistemic = decompose_classification_uncertainty(member_probs)
62
+ ```
63
+
64
+ For a runnable example with training and calibration, see [Getting Started](https://intsystems.github.io/bensemble/getting-started/).
65
+
66
+ ### Variational inference
67
+
68
+ Build a Bayesian Neural Network from scratch using our custom layers with the Local Reparameterization Trick.
69
+
70
+ ```python
71
+ import torch
72
+ import torch.nn as nn
73
+
74
+ from bensemble.layers import BayesianLinear
75
+ from bensemble.losses import VariationalLoss, GaussianLikelihood
76
+ from bensemble.utils import get_total_kl, predict_with_uncertainty
77
+
78
+ # 1. Define Model using Bayesian Layers
79
+ model = nn.Sequential(
80
+ BayesianLinear(10, 50, prior_sigma=1.0),
81
+ nn.ReLU(),
82
+ BayesianLinear(50, 1, prior_sigma=1.0),
83
+ )
84
+
85
+ # 2. Define Objectives (Likelihood + Divergence)
86
+ likelihood = GaussianLikelihood()
87
+ criterion = VariationalLoss(likelihood, alpha=1.0)
88
+
89
+ optimizer = torch.optim.Adam(list(model.parameters()) + list(likelihood.parameters()), lr=0.01)
90
+
91
+ # 3. Standard PyTorch Training Loop
92
+ model.train()
93
+ for epoch in range(50): # Dummy loop
94
+ x, y = torch.randn(10, 10), torch.randn(10, 1)
95
+ optimizer.zero_grad()
96
+ loss = criterion(model(x), y, get_total_kl(model))
97
+ loss.backward()
98
+ optimizer.step()
99
+
100
+ # 4. Predict with Uncertainty
101
+ mean, std = predict_with_uncertainty(model, torch.randn(5, 10), num_samples=100)
102
+ print(f"Prediction: {mean[0].item():.2f} ± {std[0].item():.2f}")
103
+ ```
104
+
105
+ For Rényi training (`alpha != 1`), use matched weight draws and log densities:
106
+
107
+ ```python
108
+ from bensemble.utils import sample_with_log_probs
109
+
110
+ criterion = VariationalLoss(likelihood, alpha=0.5)
111
+ optimizer.zero_grad()
112
+ predictions, log_p, log_q = sample_with_log_probs(model, x, num_samples=8)
113
+ loss = criterion(predictions, y, log_prior=log_p, log_posterior=log_q)
114
+ loss.backward()
115
+ optimizer.step()
116
+ ```
117
+
118
+ A scalar KL is accepted only for the ordinary ELBO (`alpha=1`). See the
119
+ [Rényi guide](docs/docs/algorithms/variational-renyi.md) for the objective and
120
+ minibatch scaling.
121
+
122
+ ---
123
+
124
+ ## Algorithms & Demos
125
+
126
+ Start with the [examples guide](examples/README.md): four ordered tutorials cover
127
+ ensembling, MC Dropout, variational inference, and Laplace; `examples/search/`
128
+ contains the three NES methods. All seven notebooks use synthetic data on CPU
129
+ and include instructions for running them from a fresh kernel.
130
+
131
+ | Method | Description |
132
+ | :--- | :--- |
133
+ | **[Deep Ensembles](examples/01_ensemble_basics.ipynb)** | Train independent classifiers, calibrate on held-out data, and decompose uncertainty. |
134
+ | **[Monte Carlo Dropout](examples/02_mc_dropout.ipynb)** | Implicit ensembling by keeping dropout active at test time. |
135
+ | **Neural Ensemble Search ([NES-RS](examples/search/nes_rs.ipynb) / [NES-RE](examples/search/nes_re.ipynb))** | Search architectures and select an ensemble on a separate validation set. |
136
+ | **[NES via Bayesian Sampling](examples/search/nes_bayesian_sampling.ipynb)** | Select from independently trained candidates using a validation-loss posterior and SVGD-inspired refinement. |
137
+ | **[Variational Inference](examples/03_variational_inference.ipynb)** | Learn a Gaussian approximation with the *Local Reparameterization Trick*. |
138
+ | **[Variational Rényi](examples/03_variational_inference.ipynb)** | Train with matched weight draws and per-sample prior/posterior log densities. |
139
+ | **[Laplace Approximation](examples/04_laplace.ipynb)** | Estimate curvature around a trained network and sample an ensemble. |
140
+ | **[Probabilistic Backprop](docs/docs/algorithms/pbp.md)** | Propagate moments using Assumed Density Filtering (ADF); see the algorithm guide. |
141
+
142
+ ---
143
+
144
+ ## Structure
145
+
146
+ ```text
147
+ bensemble/
148
+ ├── core/ # Base protocols, ensemble abstractions, and adapters
149
+ │ ├── ensemble.py # Central `Ensemble` class
150
+ │ ├── member.py # Adapters for explicit and stochastic models
151
+ │ └── types.py # Protocols: Predictor, KLProvider, PosteriorSource
152
+ │
153
+ ├── layers/ # Bayesian Layers for Variational Inference
154
+ │ ├── base.py # BaseBayesianLayer: KL divergence, SNR-based pruning
155
+ │ ├── linear.py # Bayesian Linear layer
156
+ │ └── conv.py # Bayesian Convolution layer
157
+ │
158
+ ├── methods/ # Standalone posterior-approximation engines
159
+ │ ├── laplace_approximation.py # Laplace with K-FAC curvature
160
+ │ └── probabilistic_backpropagation.py # PBP (ADF-based)
161
+ │
162
+ ├── search/ # Neural Ensemble Search algorithms
163
+ │ ├── nes.py # NES-RS & NES-RE (RandomSearcher, EvolutionarySearcher)
164
+ │ ├── bayesian.py # NESBS (discrete, SVGD-inspired sampler)
165
+ │ ├── selection.py # Greedy forward selection, scoring criteria
166
+ │ └── space.py # SearchSpace protocol
167
+ │
168
+ ├── diversity/ # Methods to induce ensemble variation
169
+ │ └── dropout.py # Monte Carlo Dropout wrapper
170
+ │
171
+ ├── uncertainty/ # Uncertainty analysis
172
+ │ └── decomposition.py # Separation of Aleatoric and Epistemic uncertainty
173
+ │
174
+ ├── calibration/ # Post-hoc model calibration tools
175
+ │ └── scaling.py # Temperature Scaling and Vector Scaling
176
+ │
177
+ ├── losses.py # VariationalLoss, GaussianLikelihood
178
+ ├── utils.py # get_total_kl, predict_with_uncertainty, etc.
179
+ └── metrics.py # Scoring rules: ECE, NLL, Brier Score
180
+ ```
181
+
182
+ ---
183
+
184
+ ## Development Setup
185
+
186
+ If you want to contribute to `bensemble` or run tests, we recommend using **uv**.
187
+
188
+ ```bash
189
+ # 1. Clone the repository
190
+ git clone https://github.com/intsystems/bensemble.git
191
+ cd bensemble
192
+
193
+ # 2. Create and activate virtual environment via uv
194
+ uv venv
195
+ source .venv/bin/activate # on Windows: .venv\Scripts\activate
196
+
197
+ # 3. Install in editable mode with dev dependencies
198
+ uv pip install -e ".[dev]"
199
+ ```
200
+
201
+ ### Run Tests
202
+
203
+ ```bash
204
+ pytest tests/
205
+ ```
206
+
207
+ ### Linting
208
+
209
+ We use `ruff` to keep code clean:
210
+
211
+ ```bash
212
+ ruff check .
213
+ ruff format .
214
+ ```
215
+
216
+ ---
217
+
218
+ ## Authors
219
+
220
+ Developed by:
221
+
222
+ - [**Dmitrii Vasilenko**](https://github.com/Dimundel)
223
+ - [**Muhammadsharif Nabiev**](https://github.com/mikhmed-nabiev)
224
+ - [**Fedor Sobolevsky**](https://github.com/TeoSable)
225
+ - [**Vadim Kasiuk**](https://github.com/KasiukVadim)
226
+
227
+ ---
228
+
229
+ ## License
230
+
231
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -0,0 +1,28 @@
1
+ """
2
+ bensemble: Bayesian ensemble methods for neural networks.
3
+
4
+ Modules:
5
+ - core: core classes and utilities
6
+ - methods: implementation of variational and Bayesian ensemble methods
7
+ """
8
+
9
+ import importlib.metadata
10
+
11
+ try:
12
+ __version__ = importlib.metadata.version("bensemble")
13
+ except importlib.metadata.PackageNotFoundError:
14
+ __version__ = "unknown"
15
+
16
+ from .methods import (
17
+ LaplaceApproximation,
18
+ PBPEngine,
19
+ )
20
+ from .search import EvolutionarySearcher, RandomSearcher, SearchSpace
21
+
22
+ __all__ = [
23
+ "EvolutionarySearcher",
24
+ "LaplaceApproximation",
25
+ "PBPEngine",
26
+ "RandomSearcher",
27
+ "SearchSpace",
28
+ ]
@@ -0,0 +1,162 @@
1
+ """Post-hoc calibration for classifiers.
2
+
3
+ Both scalers recalibrate class logits against integer class labels; neither
4
+ has a regression counterpart.
5
+ """
6
+
7
+ import torch
8
+ import torch.nn.functional as F
9
+ from torch import nn, optim
10
+
11
+
12
+ def _fit_calibrator(
13
+ module: nn.Module,
14
+ params: list[nn.Parameter],
15
+ logits: torch.Tensor,
16
+ labels: torch.Tensor,
17
+ max_iter: int,
18
+ optimizer: optim.Optimizer | None,
19
+ ) -> None:
20
+ """Fits a calibration module by minimizing the negative log-likelihood.
21
+
22
+ Args:
23
+ module: Calibration module mapping logits to calibrated logits.
24
+ params: Parameters to optimize, used to build the default optimizer.
25
+ logits: Unscaled logits of shape (N, num_classes).
26
+ labels: Ground truth class indices of shape (N,).
27
+ max_iter: Maximum number of optimizer iterations.
28
+ optimizer: Optimizer over `params`, or None to use the default L-BFGS.
29
+ """
30
+ logits = logits.detach()
31
+
32
+ if optimizer is None:
33
+ optimizer = optim.LBFGS(
34
+ params,
35
+ lr=1.0,
36
+ max_iter=max_iter,
37
+ line_search_fn="strong_wolfe",
38
+ )
39
+
40
+ def eval_loss():
41
+ optimizer.zero_grad()
42
+ loss = F.cross_entropy(module(logits), labels)
43
+ loss.backward()
44
+ return loss
45
+
46
+ if isinstance(optimizer, optim.LBFGS):
47
+ optimizer.step(eval_loss)
48
+ else:
49
+ for _ in range(max_iter):
50
+ optimizer.step(eval_loss)
51
+
52
+
53
+ class TemperatureScaling(nn.Module):
54
+ """Temperature Scaling for classifier calibration.
55
+
56
+ Divides logits by a single learnable scalar parameter T (temperature).
57
+ This softens probabilities and calibrates confidence without changing
58
+ classification accuracy (argmax remains identical).
59
+ """
60
+
61
+ def __init__(self, init_temp: float = 1.5):
62
+ """Initializes the TemperatureScaling module.
63
+
64
+ Args:
65
+ init_temp: Initial value for the temperature scalar. Defaults to 1.5.
66
+ """
67
+ super().__init__()
68
+ self.temperature = nn.Parameter(torch.ones(1) * init_temp)
69
+
70
+ def forward(self, logits: torch.Tensor) -> torch.Tensor:
71
+ """Applies temperature scaling to the input logits.
72
+
73
+ Args:
74
+ logits: Raw uncalibrated logits of shape (batch_size, num_classes).
75
+
76
+ Returns:
77
+ torch.Tensor: Scaled logits of shape (batch_size, num_classes).
78
+ """
79
+ return logits / self.temperature
80
+
81
+ def fit(
82
+ self,
83
+ logits: torch.Tensor,
84
+ labels: torch.Tensor,
85
+ max_iter: int = 50,
86
+ optimizer: optim.Optimizer | None = None,
87
+ ) -> "TemperatureScaling":
88
+ """Finds the optimal temperature T using a validation set.
89
+
90
+ Optimizes the negative log-likelihood.
91
+
92
+ Args:
93
+ logits: Unscaled logits from a hold-out validation set of shape
94
+ (N, num_classes).
95
+ labels: Ground truth class indices of shape (N,).
96
+ max_iter: Maximum number of optimizer iterations. Defaults to 50.
97
+ optimizer: Optimizer over this module's parameters. Defaults to
98
+ L-BFGS with a strong Wolfe line search. L-BFGS runs up to
99
+ `max_iter` iterations within a single step, while any other
100
+ optimizer is stepped `max_iter` times.
101
+
102
+ Returns:
103
+ TemperatureScaling: The fitted instance itself.
104
+ """
105
+ _fit_calibrator(self, [self.temperature], logits, labels, max_iter, optimizer)
106
+ return self
107
+
108
+
109
+ class VectorScaling(nn.Module):
110
+ """Vector Scaling for multi-class calibration (extension of Platt Scaling).
111
+
112
+ Applies a per-class affine transformation to uncalibrated logits:
113
+ calibrated_logits = logits * a + b
114
+ """
115
+
116
+ def __init__(self, num_classes: int):
117
+ """Initializes the VectorScaling module.
118
+
119
+ Args:
120
+ num_classes: Number of classes in the classification task.
121
+ """
122
+ super().__init__()
123
+ self.a = nn.Parameter(torch.ones(num_classes))
124
+ self.b = nn.Parameter(torch.zeros(num_classes))
125
+
126
+ def forward(self, logits: torch.Tensor) -> torch.Tensor:
127
+ """Applies learned affine transformation to the input logits.
128
+
129
+ Args:
130
+ logits: Raw uncalibrated logits of shape (batch_size, num_classes).
131
+
132
+ Returns:
133
+ torch.Tensor: Calibrated logits of shape (batch_size, num_classes).
134
+ """
135
+ return logits * self.a + self.b
136
+
137
+ def fit(
138
+ self,
139
+ logits: torch.Tensor,
140
+ labels: torch.Tensor,
141
+ max_iter: int = 50,
142
+ optimizer: optim.Optimizer | None = None,
143
+ ) -> "VectorScaling":
144
+ """Finds optimal scaling vectors 'a' and 'b' using a validation set.
145
+
146
+ Optimizes the negative log-likelihood.
147
+
148
+ Args:
149
+ logits: Unscaled logits from a hold-out validation set of shape
150
+ (N, num_classes).
151
+ labels: Ground truth class indices of shape (N,).
152
+ max_iter: Maximum number of optimizer iterations. Defaults to 50.
153
+ optimizer: Optimizer over this module's parameters. Defaults to
154
+ L-BFGS with a strong Wolfe line search. L-BFGS runs up to
155
+ `max_iter` iterations within a single step, while any other
156
+ optimizer is stepped `max_iter` times.
157
+
158
+ Returns:
159
+ VectorScaling: The fitted instance itself.
160
+ """
161
+ _fit_calibrator(self, [self.a, self.b], logits, labels, max_iter, optimizer)
162
+ return self