bensemble 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,259 @@
1
+ import copy
2
+ from typing import Any, Dict, List, Optional, Tuple
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+
8
+ from core.base import BaseBayesianEnsemble
9
+
10
+
11
+ class VariationalRenyi(BaseBayesianEnsemble):
12
+ """
13
+ Variational Rényi Bound (VR) Bayesian method.
14
+ Поддерживает регрессию и классификацию.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ model: nn.Module,
20
+ alpha: float = 1.0,
21
+ prior_sigma: float = 1.0,
22
+ initial_rho: float = -2.0,
23
+ **kwargs
24
+ ):
25
+ """
26
+ Args:
27
+ model: детерминированная PyTorch модель
28
+ alpha: параметр Rényi (α=1 → стандартный VI)
29
+ prior_sigma: σ априорного распределения весов
30
+ initial_rho: инициализация rho для вариационных весов
31
+ """
32
+ # сохраняем шаблон модели для сэмплирования
33
+ self.model_template = copy.deepcopy(model)
34
+
35
+ self.alpha = alpha
36
+ self.prior_sigma = prior_sigma
37
+ self.initial_rho = initial_rho
38
+
39
+ # bayesian_model: deep-copy и преобразуем слои
40
+ bayesian_model = self._make_bayesian(copy.deepcopy(model))
41
+ self.bayesian_model = bayesian_model
42
+
43
+ super().__init__(bayesian_model, **kwargs)
44
+ self.optimizer = None
45
+
46
+ def _make_bayesian(self, model: nn.Module) -> nn.Module:
47
+ """Добавляем mu/rho для всех линейных слоёв"""
48
+ for module in model.modules():
49
+ if isinstance(module, nn.Linear):
50
+ module.weight_mu = nn.Parameter(module.weight.data.clone())
51
+ module.weight_rho = nn.Parameter(
52
+ torch.full_like(module.weight.data, self.initial_rho)
53
+ )
54
+ if module.bias is not None:
55
+ module.bias_mu = nn.Parameter(module.bias.data.clone())
56
+ module.bias_rho = nn.Parameter(
57
+ torch.full_like(module.bias.data, self.initial_rho)
58
+ )
59
+ # удаляем старые параметры, чтобы не мешали
60
+ del module._parameters["weight"]
61
+ if module.bias is not None:
62
+ del module._parameters["bias"]
63
+ return model
64
+
65
+ def _reparameterize(self, mu: torch.Tensor, rho: torch.Tensor) -> torch.Tensor:
66
+ """Softplus reparametrization для sigma = softplus(rho)"""
67
+ sigma = torch.log1p(torch.exp(rho))
68
+ sigma = torch.clamp(sigma, min=0.01, max=1.0) # верхняя граница увеличена
69
+ eps = torch.randn_like(sigma)
70
+ return mu + sigma * eps
71
+
72
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
73
+ """Прямой проход с репараметризацией"""
74
+ for module in self.bayesian_model.modules():
75
+ if hasattr(module, "weight_mu"):
76
+ module.weight = self._reparameterize(
77
+ module.weight_mu, module.weight_rho
78
+ )
79
+ if hasattr(module, "bias_mu") and module.bias_mu is not None:
80
+ module.bias = self._reparameterize(module.bias_mu, module.bias_rho)
81
+ return self.bayesian_model(x)
82
+
83
+ def _compute_log_weights(
84
+ self, batch_X: torch.Tensor, batch_y: torch.Tensor
85
+ ) -> torch.Tensor:
86
+ """Вычисление log_weight для VR bound"""
87
+ output = self.forward(batch_X)
88
+ if output.dim() == 1 or output.shape[1] == 1: # регрессия
89
+ likelihood_sigma = 0.1 # подбирается под шум данных
90
+ log_likelihood = torch.distributions.Normal(
91
+ output.squeeze(), likelihood_sigma
92
+ ).log_prob(batch_y.squeeze())
93
+ else: # классификация
94
+ log_likelihood = -F.cross_entropy(output, batch_y, reduction="none")
95
+
96
+ # log prior
97
+ log_prior = 0.0
98
+ for module in self.bayesian_model.modules():
99
+ if hasattr(module, "weight_mu"):
100
+ log_prior += (
101
+ torch.distributions.Normal(0, self.prior_sigma)
102
+ .log_prob(module.weight)
103
+ .sum()
104
+ )
105
+ if hasattr(module, "bias_mu") and module.bias_mu is not None:
106
+ log_prior += (
107
+ torch.distributions.Normal(0, self.prior_sigma)
108
+ .log_prob(module.bias)
109
+ .sum()
110
+ )
111
+
112
+ # log variational
113
+ log_variational = 0.0
114
+ for module in self.bayesian_model.modules():
115
+ if hasattr(module, "weight_mu"):
116
+ sigma_w = torch.log1p(torch.exp(module.weight_rho))
117
+ log_variational += (
118
+ torch.distributions.Normal(module.weight_mu, sigma_w)
119
+ .log_prob(module.weight)
120
+ .sum()
121
+ )
122
+ if hasattr(module, "bias_mu") and module.bias_mu is not None:
123
+ sigma_b = torch.log1p(torch.exp(module.bias_rho))
124
+ log_variational += (
125
+ torch.distributions.Normal(module.bias_mu, sigma_b)
126
+ .log_prob(module.bias)
127
+ .sum()
128
+ )
129
+
130
+ return log_likelihood.sum() + log_prior - log_variational
131
+
132
+ def fit(
133
+ self,
134
+ train_loader: torch.utils.data.DataLoader,
135
+ val_loader: Optional[torch.utils.data.DataLoader] = None,
136
+ num_epochs: int = 100,
137
+ lr: float = 5e-4,
138
+ n_samples: int = 10,
139
+ grad_clip: Optional[float] = 5.0,
140
+ **kwargs
141
+ ) -> Dict[str, List[float]]:
142
+
143
+ self.optimizer = torch.optim.Adam(self.bayesian_model.parameters(), lr=lr)
144
+ history = {"train_loss": [], "val_loss": []}
145
+
146
+ for epoch in range(num_epochs):
147
+ self.bayesian_model.train()
148
+ train_loss = 0.0
149
+
150
+ for batch_X, batch_y in train_loader:
151
+ self.optimizer.zero_grad()
152
+ log_weights = []
153
+ for _ in range(n_samples):
154
+ log_w = self._compute_log_weights(batch_X, batch_y)
155
+ log_weights.append(log_w.unsqueeze(-1))
156
+ log_weights = torch.cat(log_weights, dim=-1)
157
+
158
+ # VR bound
159
+ if self.alpha == 1.0:
160
+ loss = -log_weights.mean()
161
+ else:
162
+ loss = -(1 / (1 - self.alpha)) * torch.logsumexp(
163
+ (1 - self.alpha) * log_weights, dim=-1
164
+ )
165
+ loss += torch.log(torch.tensor(n_samples, dtype=torch.float))
166
+ loss = loss.mean()
167
+
168
+ loss.backward()
169
+
170
+ # gradient clipping
171
+ if grad_clip is not None:
172
+ for p in self.bayesian_model.parameters():
173
+ if p.grad is not None:
174
+ p.grad.data.clamp_(-grad_clip, grad_clip)
175
+ self.optimizer.step()
176
+ train_loss += loss.item()
177
+
178
+ history["train_loss"].append(train_loss / len(train_loader))
179
+
180
+ if val_loader is not None:
181
+ val_loss = self._validate(val_loader, n_samples)
182
+ history["val_loss"].append(val_loss)
183
+
184
+ self.is_fitted = True
185
+ return history
186
+
187
+ def _validate(
188
+ self, val_loader: torch.utils.data.DataLoader, n_samples: int
189
+ ) -> float:
190
+ self.bayesian_model.eval()
191
+ val_loss = 0.0
192
+ with torch.no_grad():
193
+ for batch_X, batch_y in val_loader:
194
+ log_weights = []
195
+ for _ in range(n_samples):
196
+ log_w = self._compute_log_weights(batch_X, batch_y)
197
+ log_weights.append(log_w.unsqueeze(-1))
198
+ log_weights = torch.cat(log_weights, dim=-1)
199
+
200
+ if self.alpha == 1.0:
201
+ loss = -log_weights.mean()
202
+ else:
203
+ loss = -(1 / (1 - self.alpha)) * torch.logsumexp(
204
+ (1 - self.alpha) * log_weights, dim=-1
205
+ )
206
+ loss += torch.log(torch.tensor(n_samples, dtype=torch.float))
207
+ loss = loss.mean()
208
+ val_loss += loss.item()
209
+ return val_loss / len(val_loader)
210
+
211
+ def predict(
212
+ self, X: torch.Tensor, n_samples: int = 100
213
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
214
+ if not self.is_fitted:
215
+ raise RuntimeError("Model not fitted. Call fit() first.")
216
+
217
+ self.bayesian_model.eval()
218
+ predictions = []
219
+ with torch.no_grad():
220
+ for _ in range(n_samples):
221
+ predictions.append(self.forward(X).unsqueeze(0))
222
+ predictions = torch.cat(predictions, dim=0)
223
+ mean_pred = predictions.mean(dim=0)
224
+ return mean_pred, predictions
225
+
226
+ def sample_models(self, n_models: int = 10) -> List[nn.Module]:
227
+ models = []
228
+ for _ in range(n_models):
229
+ models.append(self._sample_single_model())
230
+ return models
231
+
232
+ def _sample_single_model(self) -> nn.Module:
233
+ model_copy = copy.deepcopy(self.model_template)
234
+ model_copy = self._make_bayesian(model_copy)
235
+
236
+ with torch.no_grad():
237
+ for orig, copy_module in zip(
238
+ self.bayesian_model.modules(), model_copy.modules()
239
+ ):
240
+ if hasattr(orig, "weight_mu"):
241
+ w_sample = self._reparameterize(orig.weight_mu, orig.weight_rho)
242
+ setattr(copy_module, "weight", w_sample)
243
+
244
+ if hasattr(orig, "bias_mu") and orig.bias_mu is not None:
245
+ b_sample = self._reparameterize(orig.bias_mu, orig.bias_rho)
246
+ setattr(copy_module, "bias", b_sample)
247
+
248
+ return model_copy
249
+
250
+ def _get_ensemble_state(self) -> Dict[str, Any]:
251
+ return {
252
+ "optimizer_state": self.optimizer.state_dict() if self.optimizer else None,
253
+ "alpha": self.alpha,
254
+ }
255
+
256
+ def _set_ensemble_state(self, state: Dict[str, Any]):
257
+ if self.optimizer and state["optimizer_state"]:
258
+ self.optimizer.load_state_dict(state["optimizer_state"])
259
+ self.alpha = state.get("alpha", 1.0)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Intelligent Systems, Phystech.edu
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.1
2
+ Name: bensemble
3
+ Version: 0.1.0
4
+ Summary: Bayesian ensemble methods for neural networks
5
+ Home-page: https://github.com/intsystems/bensemble
6
+ Author: Соболевский Федор, Набиев Мухаммадшариф, Василенко Дмитрий, Касюк Вадим
7
+ Author-email: kasukvadim@mail.ru
8
+ License: MIT
9
+ Project-URL: Bug Tracker, https://github.com/intsystems/bensemble/issues
10
+ Project-URL: Documentation, https://github.com/intsystems/bensemble#readme
11
+ Project-URL: Source, https://github.com/intsystems/bensemble
12
+ Keywords: bayesian neural network ensemble variational inference renyi
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Intended Audience :: Science/Research
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: torch==2.9.1
22
+ Requires-Dist: numpy==2.2.6
23
+ Requires-Dist: scikit-learn==1.7.2
24
+ Requires-Dist: matplotlib==3.10.7
25
+ Requires-Dist: scipy==1.15.3
26
+ Provides-Extra: dev
27
+ Requires-Dist: black; extra == "dev"
28
+ Requires-Dist: isort; extra == "dev"
29
+ Requires-Dist: nbqa; extra == "dev"
30
+ Requires-Dist: pytest; extra == "dev"
31
+ Requires-Dist: mypy; extra == "dev"
32
+ Requires-Dist: autopep8; extra == "dev"
33
+
34
+ |test| |codecov| |docs|
35
+
36
+ .. |test| image:: https://github.com/intsystems/ProjectTemplate/workflows/test/badge.svg
37
+ :target: https://github.com/intsystems/ProjectTemplate/tree/master
38
+ :alt: Test status
39
+
40
+ .. |codecov| image:: https://img.shields.io/codecov/c/github/intsystems/ProjectTemplate/master
41
+ :target: https://app.codecov.io/gh/intsystems/ProjectTemplate
42
+ :alt: Test coverage
43
+
44
+ .. |docs| image:: https://github.com/intsystems/ProjectTemplate/workflows/docs/badge.svg
45
+ :target: https://intsystems.github.io/ProjectTemplate/
46
+ :alt: Docs status
47
+
48
+
49
+ .. class:: center
50
+
51
+ :Название исследуемой задачи: Bayesian ensembling
52
+ :Тип научной работы: Учебный проект по курсу байесовского мультимоделирования
53
+ :Автор: Соболевский Федор, Набиев Мухаммадшариф, Василенко Дмитрий, Касюк Вадим
54
+ :Научный руководитель: к. ф.-м. н. Бахтеев Олег Юрьевич
55
+ :Научный консультант(при наличии): степень, Фамилия Имя Отчество
56
+
57
+ Abstract: Comparative Analysis of Bayesian Deep Learning Methods for Multimodel Ensembling
58
+ ========
59
+
60
+ Bayesian methods provide a principled framework for uncertainty quantification in deep learning, which is crucial for safety-critical applications. This project presents a comprehensive comparative study of four prominent variational inference algorithms for Bayesian neural networks: the baseline Evidence Lower Bound (ELBO) with local reparameterization trick, hyperparameter optimization, and pruning; Renyi divergence as a generalization of ELBO offering tunable mode-seeking/covering behavior; scalable Laplace approximation for efficient posterior estimation; and Bayes by Backpropagation as an alternative variational inference scheme.
61
+
62
+ We implement these methods in a unified framework and evaluate them on benchmark classification and regression tasks using metrics including predictive accuracy, negative log-likelihood, expected calibration error, and out-of-distribution detection performance. Our results demonstrate the trade-offs between computational efficiency, uncertainty quantification quality, and model performance across different methods. Specifically, we show how Renyi divergence with α < 1 provides improved uncertainty calibration compared to standard ELBO, while scalable Laplace approximation offers competitive performance with reduced computational overhead. The study provides practical guidance for selecting appropriate Bayesian inference methods based on application requirements and computational constraints.
63
+
64
+ Keywords: Bayesian Deep Learning, Variational Inference, Uncertainty Quantification, Renyi Divergence, Laplace Approximation, Neural Networks Ensembling
65
+
66
+ Bayesian Multimodeling Project
67
+ ==============================
68
+
69
+ A comprehensive comparative study of Bayesian deep learning methods for neural network ensembling and uncertainty quantification.
70
+
71
+ Project documentation can be found here: https://intsystems.github.io/bensemble/
72
+
73
+ Blog post draft: https://github.com/intsystems/bensemble/blob/master/paper/blogpost_draft/blog_post_draft.pdf
74
+
75
+ Techreport draft: https://github.com/intsystems/bensemble/blob/master/paper/techreport_draft/bensemble_Tech_Report_draft.pdf
76
+
77
+ Benchmark notebook: https://github.com/intsystems/bensemble/blob/master/notebooks/benchmark.ipynb
78
+
79
+ Demos
80
+ --------------------
81
+ Practical Variational Inference: https://github.com/intsystems/bensemble/blob/master/notebooks/pvi_demo.ipynb
82
+
83
+ Kronecker-Factored Laplace Approximation: https://github.com/intsystems/bensemble/blob/master/notebooks/laplace_demo.ipynb
84
+
85
+ Variational Inference with Renyi Divergence: https://github.com/intsystems/bensemble/blob/master/notebooks/variatinal_renyi_demo.ipynb
86
+
87
+ Bayes by Backprop: https://github.com/intsystems/bensemble/blob/master/notebooks/pbp_probabilistic_backpropagation_test.ipynb
@@ -0,0 +1,15 @@
1
+ bensemble/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ bensemble/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ bensemble/core/base.py,sha256=FFZRIZiUElioS_xTmnEd-ClGIMLOw0_paH_w-WKeINs,2889
4
+ bensemble/core/utils.py,sha256=HdbfgPc5IoTTjSWSW2fQ7NBEdlu_yOb9syRNOTlE1R4,1776
5
+ bensemble/methods/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ bensemble/methods/laplace_approximation.py,sha256=PMEPHBrn7IOmgH9TBcigxvYR90YAVven263OQqWMEOE,17710
7
+ bensemble/methods/prob_back_prop.py,sha256=x6g48Aos9faDcpVN9kdCwF7sAOxEykTt8nNYcYkfBxE,10605
8
+ bensemble/methods/probabilistic_backpropagation.py,sha256=UShCMJCL2OCUCVLskWIVRJ5YXMPmKpyLsS80l0Yjffg,16476
9
+ bensemble/methods/variational_inference.py,sha256=kPfGHafMegB6b-KZKZJkm7yMZijxNHfGSvYSVSONGyQ,7998
10
+ bensemble/methods/variational_renyi.py,sha256=6DaeDJUw7S2P2_aogk-lMHrAC9z-WBcSAtAcRrGjzzI,10402
11
+ bensemble-0.1.0.dist-info/LICENSE,sha256=CvPanZp9SnDljaUDuTdn6V6rsk0BBf-Ey_7T7ALQVPw,1090
12
+ bensemble-0.1.0.dist-info/METADATA,sha256=Xiz81w__FipXwqpEwHMiegyA2qEFZy62ZaHToTkYcic,5414
13
+ bensemble-0.1.0.dist-info/WHEEL,sha256=tZoeGjtWxWRfdplE7E3d45VPlLNQnvbKiYnx7gwAy8A,92
14
+ bensemble-0.1.0.dist-info/top_level.txt,sha256=8jH1t7jNBvYOn_ODY6fKcXFSXZVq0RR8v2IjXw4EUo8,10
15
+ bensemble-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.45.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ bensemble