bensemble 0.2.0__tar.gz → 0.2.2__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.
- {bensemble-0.2.0 → bensemble-0.2.2}/PKG-INFO +1 -1
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/__init__.py +9 -5
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/layers/base.py +34 -0
- bensemble-0.2.2/bensemble/methods/__init__.py +10 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/methods/laplace_approximation.py +39 -170
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/methods/probabilistic_backpropagation.py +17 -26
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/utils.py +28 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble.egg-info/PKG-INFO +1 -1
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble.egg-info/SOURCES.txt +0 -1
- {bensemble-0.2.0 → bensemble-0.2.2}/pyproject.toml +1 -1
- bensemble-0.2.0/bensemble/core/base.py +0 -76
- bensemble-0.2.0/bensemble/methods/__init__.py +0 -12
- {bensemble-0.2.0 → bensemble-0.2.2}/LICENSE +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/README.md +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/calibration/__init__.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/calibration/scaling.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/core/__init__.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/core/ensemble.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/core/member.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/core/types.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/diversity/dropout.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/layers/__init__.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/layers/conv.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/layers/linear.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/losses.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/metrics.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/search/__init__.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/search/bayesian.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/search/nes.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/search/selection.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/search/space.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/uncertainty/__init__.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble/uncertainty/decomposition.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble.egg-info/dependency_links.txt +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble.egg-info/requires.txt +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/bensemble.egg-info/top_level.txt +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/setup.cfg +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/tests/test_losses.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/tests/test_metrics.py +0 -0
- {bensemble-0.2.0 → bensemble-0.2.2}/tests/test_utils.py +0 -0
|
@@ -2,22 +2,26 @@
|
|
|
2
2
|
bensemble: Bayesian ensemble methods for neural networks.
|
|
3
3
|
|
|
4
4
|
Modules:
|
|
5
|
-
- core:
|
|
6
|
-
- methods:
|
|
5
|
+
- core: core classes and utilities
|
|
6
|
+
- methods: implementation of variational and Bayesian ensemble methods
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
import importlib.metadata
|
|
10
10
|
|
|
11
|
+
try:
|
|
12
|
+
__version__ = importlib.metadata.version("bensemble")
|
|
13
|
+
except importlib.metadata.PackageNotFoundError:
|
|
14
|
+
__version__ = "unknown"
|
|
11
15
|
|
|
12
16
|
from .methods import (
|
|
13
17
|
LaplaceApproximation,
|
|
14
|
-
|
|
18
|
+
PBPEngine,
|
|
15
19
|
)
|
|
16
20
|
from .search import RandomSearcher, EvolutionarySearcher, SearchSpace
|
|
17
21
|
|
|
18
22
|
__all__ = [
|
|
19
23
|
"LaplaceApproximation",
|
|
20
|
-
"
|
|
24
|
+
"PBPEngine",
|
|
21
25
|
"RandomSearcher",
|
|
22
26
|
"EvolutionarySearcher",
|
|
23
27
|
"SearchSpace",
|
|
@@ -52,6 +52,40 @@ class BaseBayesianLayer(nn.Module):
|
|
|
52
52
|
snr_dict = self._get_snr_dict()
|
|
53
53
|
return {name: (val > threshold).float() for name, val in snr_dict.items()}
|
|
54
54
|
|
|
55
|
+
def apply_pruning(self, threshold: float = 0.83) -> float:
|
|
56
|
+
"""
|
|
57
|
+
Applies pruning in-place: zeros out the means and minimizes the variance
|
|
58
|
+
for weights that fall below the SNR threshold.
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
float: Sparsity of the layer (percentage of pruned weights, 0.0 to 1.0).
|
|
62
|
+
"""
|
|
63
|
+
masks = self.get_pruning_masks(threshold)
|
|
64
|
+
|
|
65
|
+
total_weights = 0
|
|
66
|
+
pruned_weights = 0
|
|
67
|
+
|
|
68
|
+
with torch.no_grad():
|
|
69
|
+
for name, param in self.named_parameters():
|
|
70
|
+
if name.endswith("_mu"):
|
|
71
|
+
mask = masks[name]
|
|
72
|
+
|
|
73
|
+
total_weights += mask.numel()
|
|
74
|
+
pruned_weights += (mask == 0.0).sum().item()
|
|
75
|
+
param.data *= mask
|
|
76
|
+
|
|
77
|
+
rho_name = name.replace("_mu", "_rho")
|
|
78
|
+
if hasattr(self, rho_name):
|
|
79
|
+
rho = getattr(self, rho_name)
|
|
80
|
+
rho.data = torch.where(
|
|
81
|
+
mask.bool(),
|
|
82
|
+
rho.data,
|
|
83
|
+
torch.tensor(-1e8, device=rho.device, dtype=rho.dtype),
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
sparsity = pruned_weights / total_weights if total_weights > 0 else 0.0
|
|
87
|
+
return sparsity
|
|
88
|
+
|
|
55
89
|
def _get_snr_dict(self) -> dict[str, torch.Tensor]:
|
|
56
90
|
"""Computes the Signal-to-Noise Ratio (SNR) for all Bayesian parameters.
|
|
57
91
|
|
|
@@ -1,39 +1,28 @@
|
|
|
1
1
|
import copy
|
|
2
|
-
from typing import Any, Dict, List
|
|
2
|
+
from typing import Any, Dict, List
|
|
3
3
|
|
|
4
4
|
import torch
|
|
5
5
|
import torch.nn as nn
|
|
6
6
|
import torch.nn.functional as F
|
|
7
7
|
from torch.utils.data import DataLoader
|
|
8
8
|
|
|
9
|
-
from
|
|
9
|
+
from bensemble.core.ensemble import Ensemble
|
|
10
10
|
|
|
11
11
|
|
|
12
|
-
class LaplaceApproximation
|
|
12
|
+
class LaplaceApproximation:
|
|
13
13
|
"""
|
|
14
14
|
Kronecker-factored Laplace approximation for neural networks.
|
|
15
|
-
|
|
16
|
-
Backwards-compatible with the old API:
|
|
17
|
-
fit(...)
|
|
18
|
-
compute_posterior(...)
|
|
19
|
-
sample_models(n_models=...)
|
|
20
|
-
predict(...)
|
|
21
|
-
|
|
22
|
-
Also compatible with posterior-source style APIs:
|
|
23
|
-
sample_models(n_members=...)
|
|
24
15
|
"""
|
|
25
16
|
|
|
26
17
|
def __init__(
|
|
27
18
|
self,
|
|
28
19
|
model: nn.Module,
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
verbose: bool = False,
|
|
20
|
+
likelihood: str = "regression",
|
|
21
|
+
prior_precision: float = 1.0,
|
|
32
22
|
damping: float = 1e-6,
|
|
33
23
|
regularization: str = "legacy",
|
|
24
|
+
verbose: bool = False,
|
|
34
25
|
):
|
|
35
|
-
super().__init__(model)
|
|
36
|
-
|
|
37
26
|
if likelihood not in ["classification", "regression"]:
|
|
38
27
|
raise ValueError(f"Unsupported likelihood: {likelihood}")
|
|
39
28
|
if regularization not in ["legacy", "paper"]:
|
|
@@ -44,15 +33,14 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
44
33
|
self.device = next(model.parameters()).device
|
|
45
34
|
|
|
46
35
|
self.likelihood = likelihood
|
|
47
|
-
self.
|
|
48
|
-
self.verbose = verbose
|
|
36
|
+
self.prior_precision = float(prior_precision)
|
|
49
37
|
self.damping = damping
|
|
50
38
|
self.regularization = regularization
|
|
39
|
+
self.verbose = verbose
|
|
51
40
|
|
|
52
41
|
self.kronecker_factors: Dict[str, Dict[str, torch.Tensor]] = {}
|
|
53
42
|
self.sampling_factors: Dict[str, Dict[str, Any]] = {}
|
|
54
43
|
self.dataset_size = 1
|
|
55
|
-
self.prior_precision = 1.0
|
|
56
44
|
|
|
57
45
|
self.hook_handles = []
|
|
58
46
|
self.activations: Dict[str, torch.Tensor] = {}
|
|
@@ -62,76 +50,24 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
62
50
|
self.verbose = not self.verbose
|
|
63
51
|
print("Verbose:", "on" if self.verbose else "off")
|
|
64
52
|
|
|
65
|
-
def
|
|
66
|
-
self,
|
|
67
|
-
train_loader: DataLoader,
|
|
68
|
-
val_loader: Optional[DataLoader] = None,
|
|
69
|
-
num_epochs: int = 100,
|
|
70
|
-
lr: float = 1e-3,
|
|
71
|
-
prior_precision: float = 1.0,
|
|
72
|
-
num_samples: int = 1000,
|
|
73
|
-
) -> Dict[str, List[float]]:
|
|
74
|
-
history: Dict[str, List[float]] = {}
|
|
75
|
-
|
|
76
|
-
if not self.pretrained:
|
|
77
|
-
if self.verbose:
|
|
78
|
-
print("Training model...")
|
|
79
|
-
|
|
80
|
-
optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
|
|
81
|
-
history["train_loss"] = []
|
|
82
|
-
|
|
83
|
-
for epoch in range(num_epochs):
|
|
84
|
-
self.model.train()
|
|
85
|
-
train_loss = 0.0
|
|
86
|
-
|
|
87
|
-
for batch_x, batch_y in train_loader:
|
|
88
|
-
batch_x = batch_x.to(self.device)
|
|
89
|
-
batch_y = batch_y.to(self.device)
|
|
90
|
-
|
|
91
|
-
optimizer.zero_grad(set_to_none=True)
|
|
92
|
-
output = self.model(batch_x)
|
|
93
|
-
|
|
94
|
-
if self.likelihood == "classification":
|
|
95
|
-
loss = F.cross_entropy(output, batch_y.long())
|
|
96
|
-
else:
|
|
97
|
-
batch_y = batch_y.to(output.dtype)
|
|
98
|
-
if batch_y.shape != output.shape:
|
|
99
|
-
batch_y = batch_y.view_as(output)
|
|
100
|
-
loss = F.mse_loss(output, batch_y)
|
|
101
|
-
|
|
102
|
-
loss.backward()
|
|
103
|
-
optimizer.step()
|
|
104
|
-
train_loss += loss.item()
|
|
105
|
-
|
|
106
|
-
total_loss = train_loss / max(1, len(train_loader))
|
|
107
|
-
history["train_loss"].append(total_loss)
|
|
108
|
-
|
|
109
|
-
if self.verbose:
|
|
110
|
-
print(f"Epoch {epoch}: training loss = {total_loss:.4f}")
|
|
111
|
-
|
|
112
|
-
self.pretrained = True
|
|
113
|
-
|
|
114
|
-
self.compute_posterior(train_loader, prior_precision, num_samples)
|
|
115
|
-
return history
|
|
116
|
-
|
|
117
|
-
def compute_posterior(
|
|
53
|
+
def compute_curvature(
|
|
118
54
|
self,
|
|
119
55
|
train_loader: DataLoader,
|
|
120
|
-
prior_precision: float = 1.0,
|
|
121
56
|
num_samples: int = 1000,
|
|
122
57
|
) -> None:
|
|
123
|
-
|
|
58
|
+
"""
|
|
59
|
+
Estimates the Kronecker factors of the Hessian using the training data.
|
|
60
|
+
This must be called before sampling models.
|
|
61
|
+
"""
|
|
124
62
|
self.dataset_size = len(train_loader.dataset)
|
|
125
63
|
|
|
126
64
|
if self.verbose:
|
|
127
65
|
print("Registering hooks...")
|
|
128
|
-
|
|
129
66
|
self._register_hooks()
|
|
130
67
|
|
|
131
68
|
try:
|
|
132
69
|
if self.verbose:
|
|
133
70
|
print("Estimating Kronecker factors...")
|
|
134
|
-
|
|
135
71
|
self._estimate_kronecker_factors(train_loader, num_samples)
|
|
136
72
|
finally:
|
|
137
73
|
if self.verbose:
|
|
@@ -141,7 +77,7 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
141
77
|
self.is_fitted = True
|
|
142
78
|
|
|
143
79
|
if self.verbose:
|
|
144
|
-
print("
|
|
80
|
+
print("Curvature computation completed!")
|
|
145
81
|
|
|
146
82
|
def _register_hooks(self) -> None:
|
|
147
83
|
self._remove_hooks()
|
|
@@ -154,6 +90,7 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
154
90
|
if x.dim() > 2:
|
|
155
91
|
x = x.flatten(start_dim=1)
|
|
156
92
|
self.activations[layer_name] = x.detach()
|
|
93
|
+
|
|
157
94
|
return forward_hook
|
|
158
95
|
|
|
159
96
|
for name, module in self.model.named_modules():
|
|
@@ -202,9 +139,7 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
202
139
|
return hessians
|
|
203
140
|
|
|
204
141
|
current_hessian = (
|
|
205
|
-
hessian_final.mean(0)
|
|
206
|
-
if hessian_final.dim() == 3
|
|
207
|
-
else hessian_final
|
|
142
|
+
hessian_final.mean(0) if hessian_final.dim() == 3 else hessian_final
|
|
208
143
|
)
|
|
209
144
|
|
|
210
145
|
final_layer_name, _ = linear_layers[-1]
|
|
@@ -232,9 +167,6 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
232
167
|
accumulators: Dict[str, Dict[str, Any]] = {}
|
|
233
168
|
sample_count = 0
|
|
234
169
|
|
|
235
|
-
if self.verbose:
|
|
236
|
-
print(f"Processing up to {num_samples} samples...")
|
|
237
|
-
|
|
238
170
|
for batch_idx, (data, target) in enumerate(train_loader):
|
|
239
171
|
if sample_count >= num_samples:
|
|
240
172
|
break
|
|
@@ -269,16 +201,10 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
269
201
|
|
|
270
202
|
accumulators[name] = {
|
|
271
203
|
"Q_sum": torch.zeros(
|
|
272
|
-
in_dim,
|
|
273
|
-
in_dim,
|
|
274
|
-
device=self.device,
|
|
275
|
-
dtype=a.dtype,
|
|
204
|
+
in_dim, in_dim, device=self.device, dtype=a.dtype
|
|
276
205
|
),
|
|
277
206
|
"H_sum": torch.zeros(
|
|
278
|
-
out_dim,
|
|
279
|
-
out_dim,
|
|
280
|
-
device=self.device,
|
|
281
|
-
dtype=h.dtype,
|
|
207
|
+
out_dim, out_dim, device=self.device, dtype=h.dtype
|
|
282
208
|
),
|
|
283
209
|
"count": 0,
|
|
284
210
|
"in_dim": in_dim,
|
|
@@ -297,9 +223,6 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
297
223
|
if sample_count % 1000 == 0 and self.verbose:
|
|
298
224
|
print(f"Processed {sample_count} samples...")
|
|
299
225
|
|
|
300
|
-
if self.verbose:
|
|
301
|
-
print("Computing final Kronecker factors...")
|
|
302
|
-
|
|
303
226
|
with torch.no_grad():
|
|
304
227
|
self.kronecker_factors.clear()
|
|
305
228
|
self.sampling_factors.clear()
|
|
@@ -324,8 +247,8 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
324
247
|
q_reg = n * q + tau * eye_q
|
|
325
248
|
h_reg = n * h + tau * eye_h
|
|
326
249
|
else:
|
|
327
|
-
q_reg = (n
|
|
328
|
-
h_reg = (n
|
|
250
|
+
q_reg = (n**0.5) * q + (tau**0.5) * eye_q
|
|
251
|
+
h_reg = (n**0.5) * h + (tau**0.5) * eye_h
|
|
329
252
|
|
|
330
253
|
q_reg = self._stabilize_spd(q_reg)
|
|
331
254
|
h_reg = self._stabilize_spd(h_reg)
|
|
@@ -335,14 +258,6 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
335
258
|
"H": h_reg.detach().clone(),
|
|
336
259
|
}
|
|
337
260
|
|
|
338
|
-
if self.verbose:
|
|
339
|
-
print(f"Layer {name}:")
|
|
340
|
-
print(f" Q shape: {q_reg.shape}, H shape: {h_reg.shape}")
|
|
341
|
-
print(f" Q norm: {torch.norm(q_reg).item():.6f}")
|
|
342
|
-
print(f" H norm: {torch.norm(h_reg).item():.6f}")
|
|
343
|
-
print(f" cond(Q): {torch.linalg.cond(q_reg).item():.2e}")
|
|
344
|
-
print(f" cond(H): {torch.linalg.cond(h_reg).item():.2e}")
|
|
345
|
-
|
|
346
261
|
q_cov = torch.linalg.inv(q_reg)
|
|
347
262
|
h_cov = torch.linalg.inv(h_reg)
|
|
348
263
|
|
|
@@ -362,16 +277,15 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
362
277
|
return eigvecs @ torch.diag(torch.sqrt(eigvals)) @ eigvecs.T
|
|
363
278
|
|
|
364
279
|
def sample_models(
|
|
365
|
-
self,
|
|
366
|
-
n_models: int = 10,
|
|
367
|
-
temperature: float = 1.0,
|
|
368
|
-
n_members: Optional[int] = None,
|
|
280
|
+
self, n_models: int = 10, temperature: float = 1.0
|
|
369
281
|
) -> List[nn.Module]:
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
282
|
+
"""
|
|
283
|
+
Samples models from the approximated posterior.
|
|
284
|
+
"""
|
|
373
285
|
if not self.is_fitted:
|
|
374
|
-
raise RuntimeError(
|
|
286
|
+
raise RuntimeError(
|
|
287
|
+
"Laplace curvature not computed. Call compute_curvature() first."
|
|
288
|
+
)
|
|
375
289
|
|
|
376
290
|
samples = []
|
|
377
291
|
modules = dict(self.model.named_modules())
|
|
@@ -387,7 +301,9 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
387
301
|
l_h = factors["L_V"].to(device=self.device, dtype=mean_weight.dtype)
|
|
388
302
|
|
|
389
303
|
weight_shape = factors["weight_shape"]
|
|
390
|
-
z = torch.randn(
|
|
304
|
+
z = torch.randn(
|
|
305
|
+
weight_shape, device=self.device, dtype=mean_weight.dtype
|
|
306
|
+
)
|
|
391
307
|
|
|
392
308
|
sampled_weight = mean_weight + temperature * (l_h @ z @ l_q.T)
|
|
393
309
|
sampled_state[f"{name}.weight"] = sampled_weight.detach().cpu()
|
|
@@ -403,75 +319,28 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
403
319
|
|
|
404
320
|
return samples
|
|
405
321
|
|
|
406
|
-
def
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
temperature: float = 1.0,
|
|
411
|
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
412
|
-
X = X.to(self.device)
|
|
413
|
-
predictions = []
|
|
414
|
-
|
|
415
|
-
for sampled_model in self.sample_models(
|
|
416
|
-
n_models=n_samples,
|
|
417
|
-
temperature=temperature,
|
|
418
|
-
):
|
|
419
|
-
sampled_model.eval()
|
|
420
|
-
with torch.no_grad():
|
|
421
|
-
predictions.append(sampled_model(X))
|
|
422
|
-
|
|
423
|
-
predictions = torch.stack(predictions, dim=0)
|
|
424
|
-
|
|
425
|
-
if self.likelihood == "classification":
|
|
426
|
-
probs = F.softmax(predictions, dim=-1)
|
|
427
|
-
mean_probs = probs.mean(dim=0)
|
|
428
|
-
uncertainty = -(
|
|
429
|
-
mean_probs * torch.log(mean_probs.clamp_min(1e-8))
|
|
430
|
-
).sum(dim=-1)
|
|
431
|
-
return mean_probs, uncertainty
|
|
432
|
-
|
|
433
|
-
mean = predictions.mean(dim=0)
|
|
434
|
-
variance = predictions.var(dim=0, unbiased=False)
|
|
435
|
-
return mean, variance
|
|
436
|
-
|
|
437
|
-
def build_ensemble(self, n_members: int = 10, **kwargs):
|
|
438
|
-
from ..core.ensemble import Ensemble
|
|
439
|
-
|
|
440
|
-
return Ensemble.from_posterior(self, n_members=n_members, **kwargs)
|
|
322
|
+
def build_ensemble(self, n_members: int = 10, temperature: float = 1.0) -> Ensemble:
|
|
323
|
+
return Ensemble.from_posterior(
|
|
324
|
+
self, n_members=n_members, temperature=temperature
|
|
325
|
+
)
|
|
441
326
|
|
|
442
327
|
def _get_ensemble_state(self) -> Dict[str, Any]:
|
|
443
328
|
return {
|
|
444
|
-
"
|
|
329
|
+
"model_state": self.model.state_dict(),
|
|
445
330
|
"is_fitted": self.is_fitted,
|
|
446
|
-
"device": self.device,
|
|
447
331
|
"likelihood": self.likelihood,
|
|
448
|
-
"pretrained": self.pretrained,
|
|
449
|
-
"kronecker_factors": self.kronecker_factors,
|
|
450
332
|
"sampling_factors": self.sampling_factors,
|
|
451
333
|
"dataset_size": self.dataset_size,
|
|
452
334
|
"prior_precision": self.prior_precision,
|
|
453
|
-
"damping": self.damping,
|
|
454
|
-
"regularization": self.regularization,
|
|
455
|
-
"verbose": self.verbose,
|
|
456
335
|
}
|
|
457
336
|
|
|
458
337
|
def _set_ensemble_state(self, state: Dict[str, Any]):
|
|
459
|
-
|
|
460
|
-
self.likelihood = state["likelihood"]
|
|
461
|
-
else:
|
|
462
|
-
raise ValueError(f"Unsupported likelihood: {state['likelihood']}")
|
|
463
|
-
|
|
464
|
-
self.model = state["model"]
|
|
338
|
+
self.model.load_state_dict(state["model_state"])
|
|
465
339
|
self.is_fitted = state["is_fitted"]
|
|
466
|
-
self.
|
|
467
|
-
self.pretrained = state["pretrained"]
|
|
468
|
-
self.kronecker_factors = state["kronecker_factors"]
|
|
340
|
+
self.likelihood = state["likelihood"]
|
|
469
341
|
self.sampling_factors = state["sampling_factors"]
|
|
470
342
|
self.dataset_size = state["dataset_size"]
|
|
471
|
-
self.prior_precision = state
|
|
472
|
-
self.damping = state.get("damping", 1e-6)
|
|
473
|
-
self.regularization = state.get("regularization", "legacy")
|
|
474
|
-
self.verbose = state.get("verbose", False)
|
|
343
|
+
self.prior_precision = state["prior_precision"]
|
|
475
344
|
self.hook_handles = []
|
|
476
345
|
|
|
477
346
|
def _stabilize_spd(self, matrix: torch.Tensor) -> torch.Tensor:
|
|
@@ -480,4 +349,4 @@ class LaplaceApproximation(BaseBayesianEnsemble):
|
|
|
480
349
|
|
|
481
350
|
@staticmethod
|
|
482
351
|
def _symmetrize(matrix: torch.Tensor) -> torch.Tensor:
|
|
483
|
-
return 0.5 * (matrix + matrix.T)
|
|
352
|
+
return 0.5 * (matrix + matrix.T)
|
|
@@ -3,8 +3,9 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
|
3
3
|
|
|
4
4
|
import torch
|
|
5
5
|
import torch.nn as nn
|
|
6
|
+
from torch.utils.data import DataLoader
|
|
6
7
|
|
|
7
|
-
from
|
|
8
|
+
from bensemble.core.ensemble import Ensemble
|
|
8
9
|
from ..utils import standard_normal_cdf, standard_normal_pdf
|
|
9
10
|
|
|
10
11
|
|
|
@@ -118,9 +119,9 @@ class PBPNet(nn.Module):
|
|
|
118
119
|
return mz, vz
|
|
119
120
|
|
|
120
121
|
|
|
121
|
-
class
|
|
122
|
+
class PBPEngine:
|
|
122
123
|
"""
|
|
123
|
-
Probabilistic Backpropagation (PBP) for Bayesian regression
|
|
124
|
+
Probabilistic Backpropagation (PBP) Engine for Bayesian regression.
|
|
124
125
|
"""
|
|
125
126
|
|
|
126
127
|
def __init__(
|
|
@@ -136,19 +137,18 @@ class ProbabilisticBackpropagation(BaseBayesianEnsemble):
|
|
|
136
137
|
):
|
|
137
138
|
if model is None:
|
|
138
139
|
if layer_sizes is None:
|
|
139
|
-
raise ValueError(
|
|
140
|
-
"Specify either a ready PBP model or layer_sizes to construct it."
|
|
141
|
-
)
|
|
140
|
+
raise ValueError("Specify either a ready PBP model or layer_sizes.")
|
|
142
141
|
model = PBPNet(layer_sizes, dtype=dtype, device=device)
|
|
142
|
+
|
|
143
143
|
self.device = device or torch.device("cpu")
|
|
144
144
|
self.dtype = dtype
|
|
145
|
-
|
|
145
|
+
self.model = model.to(self.device)
|
|
146
|
+
self.is_fitted = False
|
|
146
147
|
|
|
147
148
|
self.alpha_g = torch.tensor(noise_alpha, dtype=self.dtype, device=self.device)
|
|
148
149
|
self.beta_g = torch.tensor(noise_beta, dtype=self.dtype, device=self.device)
|
|
149
150
|
self.alpha_l = torch.tensor(weight_alpha, dtype=self.dtype, device=self.device)
|
|
150
151
|
self.beta_l = torch.tensor(weight_beta, dtype=self.dtype, device=self.device)
|
|
151
|
-
# Initialize weights to match the stated Gaussian prior (before 1/sqrt(d) scaling).
|
|
152
152
|
self._init_from_prior()
|
|
153
153
|
|
|
154
154
|
def _init_from_prior(self) -> None:
|
|
@@ -365,8 +365,8 @@ class ProbabilisticBackpropagation(BaseBayesianEnsemble):
|
|
|
365
365
|
|
|
366
366
|
def fit(
|
|
367
367
|
self,
|
|
368
|
-
train_loader:
|
|
369
|
-
val_loader: Optional[
|
|
368
|
+
train_loader: DataLoader,
|
|
369
|
+
val_loader: Optional[DataLoader] = None,
|
|
370
370
|
num_epochs: int = 100,
|
|
371
371
|
step_clip: Optional[float] = 2.0,
|
|
372
372
|
prior_refresh: int = 1,
|
|
@@ -453,26 +453,14 @@ class ProbabilisticBackpropagation(BaseBayesianEnsemble):
|
|
|
453
453
|
var = torch.clamp(noise_var + vz, min=1e-12)
|
|
454
454
|
return mz, var
|
|
455
455
|
|
|
456
|
-
def predict(
|
|
457
|
-
self, X: torch.Tensor, n_samples: int = 100
|
|
458
|
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
459
|
-
if not self.is_fitted:
|
|
460
|
-
raise RuntimeError("Model not fitted. Call fit() first.")
|
|
461
|
-
|
|
462
|
-
mean, var = self._predictive_mean_var(
|
|
463
|
-
X.to(device=self.device, dtype=self.dtype)
|
|
464
|
-
)
|
|
465
|
-
std = torch.sqrt(torch.clamp(var, min=1e-12))
|
|
466
|
-
samples = mean.unsqueeze(0) + std.unsqueeze(0) * torch.randn(
|
|
467
|
-
(n_samples,) + mean.shape, device=self.device, dtype=self.dtype
|
|
468
|
-
)
|
|
469
|
-
return mean.detach(), samples.detach()
|
|
470
|
-
|
|
471
456
|
def noise_variance(self) -> torch.Tensor:
|
|
472
457
|
alpha = torch.clamp(self.alpha_g, min=1.0 + 1e-6)
|
|
473
458
|
return self.beta_g / (alpha - 1.0)
|
|
474
459
|
|
|
475
|
-
def sample_models(self, n_models: int = 10) -> List[nn.Module]:
|
|
460
|
+
def sample_models(self, n_models: int = 10, **kwargs) -> List[nn.Module]:
|
|
461
|
+
if not self.is_fitted:
|
|
462
|
+
raise RuntimeError("PBPEngine not fitted. Call fit() first.")
|
|
463
|
+
|
|
476
464
|
models = []
|
|
477
465
|
for _ in range(n_models):
|
|
478
466
|
model_copy = self._sample_single_model()
|
|
@@ -504,6 +492,9 @@ class ProbabilisticBackpropagation(BaseBayesianEnsemble):
|
|
|
504
492
|
model.eval()
|
|
505
493
|
return model
|
|
506
494
|
|
|
495
|
+
def build_ensemble(self, n_members: int = 10) -> Ensemble:
|
|
496
|
+
return Ensemble.from_posterior(self, n_members=n_members)
|
|
497
|
+
|
|
507
498
|
def _get_ensemble_state(self) -> Dict[str, Any]:
|
|
508
499
|
return {
|
|
509
500
|
"alpha_g": self.alpha_g,
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from bensemble.layers.conv import BayesianConv2d
|
|
2
2
|
from bensemble.layers import BayesianLinear
|
|
3
|
+
from bensemble.layers.base import BaseBayesianLayer
|
|
3
4
|
import math
|
|
4
5
|
|
|
5
6
|
import torch
|
|
@@ -68,3 +69,30 @@ def predict_with_uncertainty(model: nn.Module, x: torch.Tensor, num_samples: int
|
|
|
68
69
|
model.train(was_training)
|
|
69
70
|
|
|
70
71
|
return mean, std
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def prune_model(model: torch.nn.Module, threshold: float = 0.83) -> float:
|
|
75
|
+
"""
|
|
76
|
+
Applies Graves' SNR-based pruning to all Bayesian layers in the model.
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
model (nn.Module): The trained Bayesian model.
|
|
80
|
+
threshold (float): SNR threshold. Defaults to 0.83.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
float: Overall sparsity of the model (percentage of pruned weights).
|
|
84
|
+
"""
|
|
85
|
+
total_weights = 0
|
|
86
|
+
total_pruned = 0
|
|
87
|
+
|
|
88
|
+
for module in model.modules():
|
|
89
|
+
if isinstance(module, BaseBayesianLayer):
|
|
90
|
+
masks = module.get_pruning_masks(threshold)
|
|
91
|
+
for mask in masks.values():
|
|
92
|
+
total_weights += mask.numel()
|
|
93
|
+
total_pruned += (mask == 0.0).sum().item()
|
|
94
|
+
|
|
95
|
+
module.apply_pruning(threshold)
|
|
96
|
+
|
|
97
|
+
overall_sparsity = total_pruned / total_weights if total_weights > 0 else 0.0
|
|
98
|
+
return overall_sparsity
|
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
import abc
|
|
2
|
-
from typing import Any, Dict, List, Optional, Tuple
|
|
3
|
-
|
|
4
|
-
import torch
|
|
5
|
-
import torch.nn as nn
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
# TODO: remove this, new class is in layers/base.py
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
class BaseBayesianEnsemble(abc.ABC):
|
|
12
|
-
"""Базовый класс для всех методов байесовского ансамблирования"""
|
|
13
|
-
|
|
14
|
-
"""The base class for all Bayesian ensembling methods"""
|
|
15
|
-
|
|
16
|
-
def __init__(self, model: nn.Module, **kwargs):
|
|
17
|
-
self.model = model
|
|
18
|
-
self.is_fitted = False
|
|
19
|
-
self.ensemble = []
|
|
20
|
-
|
|
21
|
-
@abc.abstractmethod
|
|
22
|
-
def fit(
|
|
23
|
-
self,
|
|
24
|
-
train_loader: torch.utils.data.DataLoader,
|
|
25
|
-
val_loader: Optional[torch.utils.data.DataLoader] = None,
|
|
26
|
-
**kwargs,
|
|
27
|
-
) -> Dict[str, List[float]]:
|
|
28
|
-
"""Обучение ансамбля"""
|
|
29
|
-
"""Ensemble training"""
|
|
30
|
-
...
|
|
31
|
-
|
|
32
|
-
@abc.abstractmethod
|
|
33
|
-
def predict(
|
|
34
|
-
self, X: torch.Tensor, n_samples: int = 100
|
|
35
|
-
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
36
|
-
"""Предсказание с оценкой неопределенности"""
|
|
37
|
-
"""Prediction with uncertainty estimation"""
|
|
38
|
-
...
|
|
39
|
-
|
|
40
|
-
@abc.abstractmethod
|
|
41
|
-
def sample_models(self, n_models: int = 10) -> List[nn.Module]:
|
|
42
|
-
"""Сэмплирование моделей из апостериорного распределения"""
|
|
43
|
-
"""Sampling models from a posteriori distribution"""
|
|
44
|
-
...
|
|
45
|
-
|
|
46
|
-
def save(self, path: str):
|
|
47
|
-
"""Сохранение обученного ансамбля"""
|
|
48
|
-
"""Saving a trained ensemble"""
|
|
49
|
-
torch.save(
|
|
50
|
-
{
|
|
51
|
-
"model_state_dict": self.model.state_dict(),
|
|
52
|
-
"ensemble_state": self._get_ensemble_state(),
|
|
53
|
-
"is_fitted": self.is_fitted,
|
|
54
|
-
},
|
|
55
|
-
path,
|
|
56
|
-
)
|
|
57
|
-
|
|
58
|
-
def load(self, path: str):
|
|
59
|
-
"""Загрузка обученного ансамбля"""
|
|
60
|
-
"""Loading a trained ensemble"""
|
|
61
|
-
checkpoint = torch.load(path)
|
|
62
|
-
self.model.load_state_dict(checkpoint["model_state_dict"])
|
|
63
|
-
self._set_ensemble_state(checkpoint["ensemble_state"])
|
|
64
|
-
self.is_fitted = checkpoint["is_fitted"]
|
|
65
|
-
|
|
66
|
-
@abc.abstractmethod
|
|
67
|
-
def _get_ensemble_state(self) -> Dict[str, Any]:
|
|
68
|
-
"""Получение внутреннего состояния ансамбля"""
|
|
69
|
-
"""Getting the internal state of the ensemble"""
|
|
70
|
-
...
|
|
71
|
-
|
|
72
|
-
@abc.abstractmethod
|
|
73
|
-
def _set_ensemble_state(self, state: Dict[str, Any]):
|
|
74
|
-
"""Установка внутреннего состояния ансамбля"""
|
|
75
|
-
"""Setting the internal state of the ensemble"""
|
|
76
|
-
...
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|