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.
- bensemble/__init__.py +0 -0
- bensemble/core/__init__.py +0 -0
- bensemble/core/base.py +73 -0
- bensemble/core/utils.py +50 -0
- bensemble/methods/__init__.py +0 -0
- bensemble/methods/laplace_approximation.py +470 -0
- bensemble/methods/prob_back_prop.py +268 -0
- bensemble/methods/probabilistic_backpropagation.py +460 -0
- bensemble/methods/variational_inference.py +240 -0
- bensemble/methods/variational_renyi.py +259 -0
- bensemble-0.1.0.dist-info/LICENSE +21 -0
- bensemble-0.1.0.dist-info/METADATA +87 -0
- bensemble-0.1.0.dist-info/RECORD +15 -0
- bensemble-0.1.0.dist-info/WHEEL +5 -0
- bensemble-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,460 @@
|
|
|
1
|
+
import math
|
|
2
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
|
|
7
|
+
from ..core.base import BaseBayesianEnsemble
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def phi(x: torch.Tensor) -> torch.Tensor:
|
|
11
|
+
return torch.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def Phi(x: torch.Tensor) -> torch.Tensor:
|
|
15
|
+
return 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def relu_moments(
|
|
19
|
+
m: torch.Tensor, v: torch.Tensor, eps: float = 1e-12
|
|
20
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
21
|
+
v = torch.clamp(v, min=eps)
|
|
22
|
+
sigma = torch.sqrt(v)
|
|
23
|
+
alpha = m / sigma
|
|
24
|
+
alpha_eval = torch.clamp(alpha, min=-10.0, max=10.0)
|
|
25
|
+
pdf = phi(alpha_eval)
|
|
26
|
+
cdf = Phi(alpha_eval)
|
|
27
|
+
mean = sigma * pdf + m * cdf
|
|
28
|
+
second_moment = (v + m * m) * cdf + m * sigma * pdf
|
|
29
|
+
var = torch.clamp(second_moment - mean * mean, min=eps)
|
|
30
|
+
return mean, var
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProbLinear(nn.Module):
|
|
34
|
+
"""Линейный слой с параметрами среднего и дисперсии для PBP."""
|
|
35
|
+
|
|
36
|
+
def __init__(
|
|
37
|
+
self,
|
|
38
|
+
in_features: int,
|
|
39
|
+
out_features: int,
|
|
40
|
+
dtype: torch.dtype = torch.float64,
|
|
41
|
+
device: Optional[torch.device] = None,
|
|
42
|
+
):
|
|
43
|
+
super().__init__()
|
|
44
|
+
self.in_features = in_features
|
|
45
|
+
self.out_features = out_features
|
|
46
|
+
self.dtype = dtype
|
|
47
|
+
self.device = device or torch.device("cpu")
|
|
48
|
+
d = self.in_features + 1 # +1 для bias
|
|
49
|
+
h = self.out_features
|
|
50
|
+
scale = 1.0 / math.sqrt(d)
|
|
51
|
+
self.m = nn.Parameter(
|
|
52
|
+
scale * torch.randn(h, d, dtype=self.dtype, device=self.device)
|
|
53
|
+
)
|
|
54
|
+
self.v = nn.Parameter(
|
|
55
|
+
0.5 * torch.ones(h, d, dtype=self.dtype, device=self.device)
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class PBPNet(nn.Module):
|
|
60
|
+
"""Сеть на основе ProbLinear с аналитическим распространением моментов."""
|
|
61
|
+
|
|
62
|
+
def __init__(
|
|
63
|
+
self,
|
|
64
|
+
layer_sizes: List[int],
|
|
65
|
+
dtype: torch.dtype = torch.float64,
|
|
66
|
+
device: Optional[torch.device] = None,
|
|
67
|
+
):
|
|
68
|
+
super().__init__()
|
|
69
|
+
self.layers: List[ProbLinear] = nn.ModuleList()
|
|
70
|
+
for i in range(len(layer_sizes) - 1):
|
|
71
|
+
self.layers.append(
|
|
72
|
+
ProbLinear(
|
|
73
|
+
layer_sizes[i], layer_sizes[i + 1], dtype=dtype, device=device
|
|
74
|
+
)
|
|
75
|
+
)
|
|
76
|
+
self.dtype = dtype
|
|
77
|
+
self.device = device or torch.device("cpu")
|
|
78
|
+
|
|
79
|
+
def forward_moments(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
80
|
+
x = x.to(device=self.device, dtype=self.dtype)
|
|
81
|
+
assert x.dim() == 2 and x.shape[0] >= 1
|
|
82
|
+
batch = x.shape[0]
|
|
83
|
+
|
|
84
|
+
mz = torch.cat(
|
|
85
|
+
[x, torch.ones(batch, 1, device=self.device, dtype=self.dtype)], dim=1
|
|
86
|
+
) # (B, D+1)
|
|
87
|
+
vz = torch.zeros_like(mz)
|
|
88
|
+
|
|
89
|
+
for li, layer in enumerate(self.layers):
|
|
90
|
+
d = layer.in_features + 1
|
|
91
|
+
scale = 1.0 / math.sqrt(d)
|
|
92
|
+
|
|
93
|
+
ma = (mz @ layer.m.t()) * scale # (B, H)
|
|
94
|
+
term1 = vz @ (layer.m**2).t()
|
|
95
|
+
term2 = (mz**2) @ layer.v.t()
|
|
96
|
+
term3 = vz @ layer.v.t()
|
|
97
|
+
va = (term1 + term2 + term3) * (scale**2)
|
|
98
|
+
|
|
99
|
+
is_last = li == len(self.layers) - 1
|
|
100
|
+
if not is_last:
|
|
101
|
+
mb, vb = relu_moments(ma, va)
|
|
102
|
+
mz = torch.cat(
|
|
103
|
+
[mb, torch.ones(batch, 1, device=self.device, dtype=self.dtype)],
|
|
104
|
+
dim=1,
|
|
105
|
+
)
|
|
106
|
+
vz = torch.cat(
|
|
107
|
+
[vb, torch.zeros(batch, 1, device=self.device, dtype=self.dtype)],
|
|
108
|
+
dim=1,
|
|
109
|
+
)
|
|
110
|
+
else:
|
|
111
|
+
mz = ma
|
|
112
|
+
vz = va
|
|
113
|
+
|
|
114
|
+
return mz, vz
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class ProbabilisticBackpropagation(BaseBayesianEnsemble):
|
|
118
|
+
"""
|
|
119
|
+
Probabilistic Backpropagation (PBP) for Bayesian regression with moment matching.
|
|
120
|
+
Основано на демо ноутбуке pbp_demo.ipynb.
|
|
121
|
+
"""
|
|
122
|
+
|
|
123
|
+
def __init__(
|
|
124
|
+
self,
|
|
125
|
+
model: Optional[nn.Module] = None,
|
|
126
|
+
layer_sizes: Optional[List[int]] = None,
|
|
127
|
+
noise_alpha: float = 6.0,
|
|
128
|
+
noise_beta: float = 6.0,
|
|
129
|
+
weight_alpha: float = 6.0,
|
|
130
|
+
weight_beta: float = 6.0,
|
|
131
|
+
dtype: torch.dtype = torch.float64,
|
|
132
|
+
device: Optional[torch.device] = None,
|
|
133
|
+
):
|
|
134
|
+
if model is None:
|
|
135
|
+
if layer_sizes is None:
|
|
136
|
+
raise ValueError(
|
|
137
|
+
"Specify either a ready PBP model or layer_sizes to construct it."
|
|
138
|
+
)
|
|
139
|
+
model = PBPNet(layer_sizes, dtype=dtype, device=device)
|
|
140
|
+
self.device = device or torch.device("cpu")
|
|
141
|
+
self.dtype = dtype
|
|
142
|
+
super().__init__(model.to(self.device))
|
|
143
|
+
|
|
144
|
+
self.alpha_g = torch.tensor(noise_alpha, dtype=self.dtype, device=self.device)
|
|
145
|
+
self.beta_g = torch.tensor(noise_beta, dtype=self.dtype, device=self.device)
|
|
146
|
+
self.alpha_l = torch.tensor(weight_alpha, dtype=self.dtype, device=self.device)
|
|
147
|
+
self.beta_l = torch.tensor(weight_beta, dtype=self.dtype, device=self.device)
|
|
148
|
+
|
|
149
|
+
def _logZ_gaussian_likelihood(
|
|
150
|
+
self,
|
|
151
|
+
y: torch.Tensor,
|
|
152
|
+
mz: torch.Tensor,
|
|
153
|
+
vz: torch.Tensor,
|
|
154
|
+
alpha_g: torch.Tensor,
|
|
155
|
+
beta_g: torch.Tensor,
|
|
156
|
+
eps: float = 1e-12,
|
|
157
|
+
) -> torch.Tensor:
|
|
158
|
+
alpha_g = torch.clamp(alpha_g, min=1.0 + 1e-6)
|
|
159
|
+
sigma2_eff = beta_g / (alpha_g - 1.0) + vz
|
|
160
|
+
sigma2_eff = torch.clamp(sigma2_eff, min=eps)
|
|
161
|
+
diff = y.reshape_as(mz) - mz
|
|
162
|
+
return (
|
|
163
|
+
-0.5 * (diff * diff) / sigma2_eff
|
|
164
|
+
- 0.5 * torch.log(2.0 * math.pi * sigma2_eff)
|
|
165
|
+
).squeeze(-1)
|
|
166
|
+
|
|
167
|
+
def _gamma_adf_update_from_Z(
|
|
168
|
+
self,
|
|
169
|
+
logZ: torch.Tensor,
|
|
170
|
+
logZ1: torch.Tensor,
|
|
171
|
+
logZ2: torch.Tensor,
|
|
172
|
+
alpha_old: torch.Tensor,
|
|
173
|
+
beta_old: torch.Tensor,
|
|
174
|
+
clamp_eps: float = 1e-9,
|
|
175
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
176
|
+
r1 = torch.exp(logZ1 - logZ)
|
|
177
|
+
r2 = torch.exp(logZ2 - logZ)
|
|
178
|
+
|
|
179
|
+
term_alpha = (r2 / (r1 * r1)) * ((alpha_old + 1.0) / alpha_old)
|
|
180
|
+
denom_alpha = torch.clamp(term_alpha - 1.0, min=1e-12)
|
|
181
|
+
alpha_new = 1.0 / denom_alpha
|
|
182
|
+
|
|
183
|
+
termA = r2 / r1 * ((alpha_old + 1.0) / beta_old)
|
|
184
|
+
termB = r1 * (alpha_old / beta_old)
|
|
185
|
+
denom_beta = torch.clamp(termA - termB, min=clamp_eps)
|
|
186
|
+
beta_new = 1.0 / denom_beta
|
|
187
|
+
|
|
188
|
+
alpha_new = torch.clamp(alpha_new, min=1.0 + 1e-6, max=1e6)
|
|
189
|
+
beta_new = torch.clamp(beta_new, min=clamp_eps, max=1e9)
|
|
190
|
+
return alpha_new.detach(), beta_new.detach()
|
|
191
|
+
|
|
192
|
+
def _single_datapoint_adf_step(
|
|
193
|
+
self, x: torch.Tensor, y: torch.Tensor, step_clip: Optional[float] = 1.0
|
|
194
|
+
) -> None:
|
|
195
|
+
for layer in self.model.layers:
|
|
196
|
+
layer.m.requires_grad_(True)
|
|
197
|
+
layer.v.requires_grad_(True)
|
|
198
|
+
|
|
199
|
+
mz, vz = self.model.forward_moments(x.reshape(1, -1))
|
|
200
|
+
logZ = self._logZ_gaussian_likelihood(
|
|
201
|
+
y.reshape(1, -1), mz, vz, self.alpha_g, self.beta_g
|
|
202
|
+
).mean()
|
|
203
|
+
logZ1 = self._logZ_gaussian_likelihood(
|
|
204
|
+
y.reshape(1, -1), mz, vz, self.alpha_g + 1.0, self.beta_g
|
|
205
|
+
).mean()
|
|
206
|
+
logZ2 = self._logZ_gaussian_likelihood(
|
|
207
|
+
y.reshape(1, -1), mz, vz, self.alpha_g + 2.0, self.beta_g
|
|
208
|
+
).mean()
|
|
209
|
+
|
|
210
|
+
for p in self.model.parameters():
|
|
211
|
+
if p.grad is not None:
|
|
212
|
+
p.grad.zero_()
|
|
213
|
+
logZ.backward()
|
|
214
|
+
|
|
215
|
+
for layer in self.model.layers:
|
|
216
|
+
gm = layer.m.grad
|
|
217
|
+
gv = layer.v.grad
|
|
218
|
+
|
|
219
|
+
if step_clip is not None:
|
|
220
|
+
gm = torch.clamp(gm, min=-step_clip, max=step_clip)
|
|
221
|
+
gv = torch.clamp(gv, min=-step_clip, max=step_clip)
|
|
222
|
+
|
|
223
|
+
m = layer.m
|
|
224
|
+
v = torch.clamp(layer.v, min=1e-10, max=1e3)
|
|
225
|
+
|
|
226
|
+
m_new = m + v * gm
|
|
227
|
+
v_new = v - (v * v) * (gm * gm - 2.0 * gv)
|
|
228
|
+
v_new = torch.clamp(v_new, min=1e-10, max=1e3)
|
|
229
|
+
|
|
230
|
+
with torch.no_grad():
|
|
231
|
+
layer.m.copy_(m_new.detach())
|
|
232
|
+
layer.v.copy_(v_new.detach())
|
|
233
|
+
|
|
234
|
+
self.alpha_g, self.beta_g = self._gamma_adf_update_from_Z(
|
|
235
|
+
logZ.detach(), logZ1.detach(), logZ2.detach(), self.alpha_g, self.beta_g
|
|
236
|
+
)
|
|
237
|
+
|
|
238
|
+
for layer in self.model.layers:
|
|
239
|
+
layer.m.grad = None
|
|
240
|
+
layer.v.grad = None
|
|
241
|
+
|
|
242
|
+
def _prior_refresh_epoch(self, n_refresh: int = 1) -> None:
|
|
243
|
+
alpha_l = torch.clamp(self.alpha_l, min=1.0 + 1e-6)
|
|
244
|
+
beta_l = self.beta_l
|
|
245
|
+
for _ in range(n_refresh):
|
|
246
|
+
s2 = beta_l / (alpha_l - 1.0)
|
|
247
|
+
s2_1 = beta_l / (alpha_l)
|
|
248
|
+
s2_2 = beta_l / (alpha_l + 1.0)
|
|
249
|
+
|
|
250
|
+
Z_acc = 0.0
|
|
251
|
+
Z1_acc = 0.0
|
|
252
|
+
Z2_acc = 0.0
|
|
253
|
+
n_tot = 0
|
|
254
|
+
|
|
255
|
+
for layer in self.model.layers:
|
|
256
|
+
m = layer.m
|
|
257
|
+
v = torch.clamp(layer.v, min=1e-12)
|
|
258
|
+
|
|
259
|
+
m_tmp = m.detach().clone().requires_grad_(True)
|
|
260
|
+
v_tmp = v.detach().clone().requires_grad_(True)
|
|
261
|
+
|
|
262
|
+
sigma2 = s2 + v_tmp
|
|
263
|
+
lp = -0.5 * (m_tmp**2) / sigma2 - 0.5 * torch.log(
|
|
264
|
+
2.0 * math.pi * sigma2
|
|
265
|
+
)
|
|
266
|
+
logZ_prior = lp.sum()
|
|
267
|
+
|
|
268
|
+
for p in (m_tmp, v_tmp):
|
|
269
|
+
if p.grad is not None:
|
|
270
|
+
p.grad.zero_()
|
|
271
|
+
logZ_prior.backward()
|
|
272
|
+
|
|
273
|
+
gm = m_tmp.grad
|
|
274
|
+
gv = v_tmp.grad
|
|
275
|
+
|
|
276
|
+
m_new = m + v * gm
|
|
277
|
+
v_new = v - (v * v) * (gm * gm - 2.0 * gv)
|
|
278
|
+
v_new = torch.clamp(v_new, min=1e-12, max=1e3)
|
|
279
|
+
|
|
280
|
+
with torch.no_grad():
|
|
281
|
+
layer.m.copy_(m_new.detach())
|
|
282
|
+
layer.v.copy_(v_new.detach())
|
|
283
|
+
|
|
284
|
+
def sum_logZ_given_s2(s2_local: torch.Tensor) -> torch.Tensor:
|
|
285
|
+
sigma2_local = s2_local + v
|
|
286
|
+
lp_local = -0.5 * (m**2) / sigma2_local - 0.5 * torch.log(
|
|
287
|
+
2.0 * math.pi * sigma2_local
|
|
288
|
+
)
|
|
289
|
+
return lp_local.sum()
|
|
290
|
+
|
|
291
|
+
Z_acc += sum_logZ_given_s2(s2).detach()
|
|
292
|
+
Z1_acc += sum_logZ_given_s2(s2_1).detach()
|
|
293
|
+
Z2_acc += sum_logZ_given_s2(s2_2).detach()
|
|
294
|
+
n_tot += m.numel()
|
|
295
|
+
|
|
296
|
+
denom = max(n_tot, 1)
|
|
297
|
+
logZ_avg = Z_acc / denom
|
|
298
|
+
logZ1_avg = Z1_acc / denom
|
|
299
|
+
logZ2_avg = Z2_acc / denom
|
|
300
|
+
|
|
301
|
+
alpha_l, beta_l = self._gamma_adf_update_from_Z(
|
|
302
|
+
logZ_avg, logZ1_avg, logZ2_avg, alpha_l, beta_l
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
self.alpha_l = alpha_l.detach()
|
|
306
|
+
self.beta_l = beta_l.detach()
|
|
307
|
+
|
|
308
|
+
def _collect_dataset(
|
|
309
|
+
self, loader: torch.utils.data.DataLoader
|
|
310
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
311
|
+
xs = []
|
|
312
|
+
ys = []
|
|
313
|
+
for batch_X, batch_y in loader:
|
|
314
|
+
xs.append(batch_X)
|
|
315
|
+
ys.append(batch_y)
|
|
316
|
+
X_full = torch.cat(xs, dim=0).to(device=self.device, dtype=self.dtype)
|
|
317
|
+
y_full = torch.cat(ys, dim=0).to(device=self.device, dtype=self.dtype)
|
|
318
|
+
return X_full, y_full
|
|
319
|
+
|
|
320
|
+
def fit(
|
|
321
|
+
self,
|
|
322
|
+
train_loader: torch.utils.data.DataLoader,
|
|
323
|
+
val_loader: Optional[torch.utils.data.DataLoader] = None,
|
|
324
|
+
num_epochs: int = 100,
|
|
325
|
+
step_clip: Optional[float] = 2.0,
|
|
326
|
+
prior_refresh: int = 1,
|
|
327
|
+
**kwargs
|
|
328
|
+
) -> Dict[str, List[float]]:
|
|
329
|
+
|
|
330
|
+
history: Dict[str, List[float]] = {"train_rmse": [], "train_nlpd": []}
|
|
331
|
+
if val_loader is not None:
|
|
332
|
+
history["val_rmse"] = []
|
|
333
|
+
history["val_nlpd"] = []
|
|
334
|
+
|
|
335
|
+
for epoch in range(num_epochs):
|
|
336
|
+
X_full, y_full = self._collect_dataset(train_loader)
|
|
337
|
+
order = torch.randperm(X_full.shape[0], device=self.device)
|
|
338
|
+
for idx in order.tolist():
|
|
339
|
+
x = X_full[idx]
|
|
340
|
+
y = y_full[idx]
|
|
341
|
+
self._single_datapoint_adf_step(x, y, step_clip)
|
|
342
|
+
|
|
343
|
+
if prior_refresh > 0:
|
|
344
|
+
self._prior_refresh_epoch(n_refresh=prior_refresh)
|
|
345
|
+
|
|
346
|
+
train_rmse, train_nlpd = self._evaluate_loader(train_loader)
|
|
347
|
+
history["train_rmse"].append(train_rmse)
|
|
348
|
+
history["train_nlpd"].append(train_nlpd)
|
|
349
|
+
|
|
350
|
+
if val_loader is not None:
|
|
351
|
+
val_rmse, val_nlpd = self._evaluate_loader(val_loader)
|
|
352
|
+
history["val_rmse"].append(val_rmse)
|
|
353
|
+
history["val_nlpd"].append(val_nlpd)
|
|
354
|
+
|
|
355
|
+
self.is_fitted = True
|
|
356
|
+
return history
|
|
357
|
+
|
|
358
|
+
def _evaluate_loader(
|
|
359
|
+
self, loader: torch.utils.data.DataLoader
|
|
360
|
+
) -> Tuple[float, float]:
|
|
361
|
+
preds = []
|
|
362
|
+
targets = []
|
|
363
|
+
nlpd_sum = 0.0
|
|
364
|
+
count = 0
|
|
365
|
+
with torch.no_grad():
|
|
366
|
+
for batch_X, batch_y in loader:
|
|
367
|
+
batch_X = batch_X.to(device=self.device, dtype=self.dtype)
|
|
368
|
+
batch_y = batch_y.to(device=self.device, dtype=self.dtype).view(
|
|
369
|
+
batch_X.shape[0], -1
|
|
370
|
+
)
|
|
371
|
+
mean, var = self._predictive_mean_var(batch_X)
|
|
372
|
+
diff = batch_y - mean
|
|
373
|
+
nlpd_batch = (
|
|
374
|
+
0.5 * torch.log(2.0 * math.pi * var) + 0.5 * (diff * diff) / var
|
|
375
|
+
)
|
|
376
|
+
nlpd_sum += nlpd_batch.sum().item()
|
|
377
|
+
count += batch_y.numel()
|
|
378
|
+
preds.append(mean.detach().cpu())
|
|
379
|
+
targets.append(batch_y.detach().cpu())
|
|
380
|
+
|
|
381
|
+
preds_all = torch.cat(preds, dim=0)
|
|
382
|
+
targets_all = torch.cat(targets, dim=0)
|
|
383
|
+
rmse = torch.sqrt(torch.mean((preds_all - targets_all) ** 2)).item()
|
|
384
|
+
nlpd = nlpd_sum / max(count, 1)
|
|
385
|
+
return rmse, nlpd
|
|
386
|
+
|
|
387
|
+
def _predictive_mean_var(
|
|
388
|
+
self, X: torch.Tensor
|
|
389
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
390
|
+
mz, vz = self.model.forward_moments(X)
|
|
391
|
+
alpha = torch.clamp(self.alpha_g, min=1.0 + 1e-6)
|
|
392
|
+
noise_var = self.beta_g / (alpha - 1.0)
|
|
393
|
+
var = torch.clamp(noise_var + vz, min=1e-12)
|
|
394
|
+
return mz, var
|
|
395
|
+
|
|
396
|
+
def predict(
|
|
397
|
+
self, X: torch.Tensor, n_samples: int = 100
|
|
398
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
399
|
+
if not self.is_fitted:
|
|
400
|
+
raise RuntimeError("Model not fitted. Call fit() first.")
|
|
401
|
+
|
|
402
|
+
mean, var = self._predictive_mean_var(
|
|
403
|
+
X.to(device=self.device, dtype=self.dtype)
|
|
404
|
+
)
|
|
405
|
+
std = torch.sqrt(torch.clamp(var, min=1e-12))
|
|
406
|
+
samples = mean.unsqueeze(0) + std.unsqueeze(0) * torch.randn(
|
|
407
|
+
(n_samples,) + mean.shape, device=self.device, dtype=self.dtype
|
|
408
|
+
)
|
|
409
|
+
return mean.detach(), samples.detach()
|
|
410
|
+
|
|
411
|
+
def noise_variance(self) -> torch.Tensor:
|
|
412
|
+
alpha = torch.clamp(self.alpha_g, min=1.0 + 1e-6)
|
|
413
|
+
return self.beta_g / (alpha - 1.0)
|
|
414
|
+
|
|
415
|
+
def sample_models(self, n_models: int = 10) -> List[nn.Module]:
|
|
416
|
+
models = []
|
|
417
|
+
for _ in range(n_models):
|
|
418
|
+
model_copy = self._sample_single_model()
|
|
419
|
+
models.append(model_copy)
|
|
420
|
+
return models
|
|
421
|
+
|
|
422
|
+
def _sample_single_model(self) -> nn.Module:
|
|
423
|
+
layers: List[nn.Module] = []
|
|
424
|
+
for li, layer in enumerate(self.model.layers):
|
|
425
|
+
d = layer.in_features + 1
|
|
426
|
+
scale = 1.0 / math.sqrt(d)
|
|
427
|
+
weight_full = (
|
|
428
|
+
torch.normal(
|
|
429
|
+
layer.m.detach(),
|
|
430
|
+
torch.sqrt(torch.clamp(layer.v.detach(), min=1e-12)),
|
|
431
|
+
)
|
|
432
|
+
* scale
|
|
433
|
+
)
|
|
434
|
+
weight = weight_full[:, : layer.in_features]
|
|
435
|
+
bias = weight_full[:, layer.in_features]
|
|
436
|
+
linear = nn.Linear(layer.in_features, layer.out_features)
|
|
437
|
+
linear = linear.to(device=self.device, dtype=self.dtype)
|
|
438
|
+
linear.weight.data = weight.to(device=self.device, dtype=self.dtype)
|
|
439
|
+
linear.bias.data = bias.to(device=self.device, dtype=self.dtype)
|
|
440
|
+
layers.append(linear)
|
|
441
|
+
if li < len(self.model.layers) - 1:
|
|
442
|
+
layers.append(nn.ReLU())
|
|
443
|
+
model = nn.Sequential(*layers)
|
|
444
|
+
model.eval()
|
|
445
|
+
return model
|
|
446
|
+
|
|
447
|
+
def _get_ensemble_state(self) -> Dict[str, Any]:
|
|
448
|
+
return {
|
|
449
|
+
"alpha_g": self.alpha_g,
|
|
450
|
+
"beta_g": self.beta_g,
|
|
451
|
+
"alpha_l": self.alpha_l,
|
|
452
|
+
"beta_l": self.beta_l,
|
|
453
|
+
"dtype": self.dtype,
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
def _set_ensemble_state(self, state: Dict[str, Any]):
|
|
457
|
+
self.alpha_g = state.get("alpha_g", self.alpha_g).to(self.device)
|
|
458
|
+
self.beta_g = state.get("beta_g", self.beta_g).to(self.device)
|
|
459
|
+
self.alpha_l = state.get("alpha_l", self.alpha_l).to(self.device)
|
|
460
|
+
self.beta_l = state.get("beta_l", self.beta_l).to(self.device)
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import copy
|
|
2
|
+
from typing import List, Optional, Tuple
|
|
3
|
+
|
|
4
|
+
import torch
|
|
5
|
+
import torch.nn as nn
|
|
6
|
+
import torch.nn.functional as F
|
|
7
|
+
import torch.optim as optim
|
|
8
|
+
|
|
9
|
+
from ..core.base import BaseBayesianEnsemble
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class BayesianLinear(nn.Module):
|
|
13
|
+
def __init__(self, in_features, out_features, prior_sigma=1.0):
|
|
14
|
+
super().__init__()
|
|
15
|
+
self.in_features = in_features
|
|
16
|
+
self.out_features = out_features
|
|
17
|
+
self.prior_sigma = prior_sigma
|
|
18
|
+
|
|
19
|
+
# Флаг режима: True = сэмплируем шум (обучение/MC), False = используем среднее
|
|
20
|
+
self.sampling = True
|
|
21
|
+
|
|
22
|
+
# Инициализация параметров
|
|
23
|
+
self.w_mu = nn.Parameter(torch.randn(out_features, in_features) * 0.1)
|
|
24
|
+
self.w_rho = nn.Parameter(torch.ones(out_features, in_features) * -3.0)
|
|
25
|
+
|
|
26
|
+
self.b_mu = nn.Parameter(torch.zeros(out_features))
|
|
27
|
+
self.b_rho = nn.Parameter(torch.ones(out_features) * -3.0)
|
|
28
|
+
|
|
29
|
+
def forward(self, x):
|
|
30
|
+
w_sigma = F.softplus(self.w_rho)
|
|
31
|
+
b_sigma = F.softplus(self.b_rho)
|
|
32
|
+
|
|
33
|
+
gamma = F.linear(x, self.w_mu)
|
|
34
|
+
|
|
35
|
+
if self.sampling:
|
|
36
|
+
# Local Reparameterization Trick
|
|
37
|
+
delta = F.linear(x.pow(2), w_sigma.pow(2)) + b_sigma.pow(2)
|
|
38
|
+
eps = torch.randn_like(gamma)
|
|
39
|
+
out = gamma + eps * torch.sqrt(delta + 1e-8)
|
|
40
|
+
return out + self.b_mu
|
|
41
|
+
else:
|
|
42
|
+
return gamma + self.b_mu
|
|
43
|
+
|
|
44
|
+
def kl_divergence(self):
|
|
45
|
+
w_sigma = F.softplus(self.w_rho)
|
|
46
|
+
b_sigma = F.softplus(self.b_rho)
|
|
47
|
+
|
|
48
|
+
def kl_term(mu, sigma):
|
|
49
|
+
var_q = sigma.pow(2)
|
|
50
|
+
var_p = self.prior_sigma**2
|
|
51
|
+
return (
|
|
52
|
+
torch.log(self.prior_sigma / sigma)
|
|
53
|
+
+ (var_q + mu.pow(2)) / (2 * var_p)
|
|
54
|
+
- 0.5
|
|
55
|
+
).sum()
|
|
56
|
+
|
|
57
|
+
return kl_term(self.w_mu, w_sigma) + kl_term(self.b_mu, b_sigma)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class GaussianLikelihood(nn.Module):
|
|
61
|
+
def __init__(self, init_log_sigma=-2.0):
|
|
62
|
+
super().__init__()
|
|
63
|
+
self.log_sigma = nn.Parameter(torch.tensor([init_log_sigma]))
|
|
64
|
+
|
|
65
|
+
def forward(self, preds, target):
|
|
66
|
+
sigma = F.softplus(self.log_sigma) + 1e-3
|
|
67
|
+
mse_term = 0.5 * (target - preds) ** 2 / sigma**2
|
|
68
|
+
return (mse_term + torch.log(sigma)).sum()
|
|
69
|
+
|
|
70
|
+
def get_noise_sigma(self):
|
|
71
|
+
return (F.softplus(self.log_sigma) + 1e-3).item()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class VariationalEnsemble(BaseBayesianEnsemble):
|
|
75
|
+
def __init__(
|
|
76
|
+
self,
|
|
77
|
+
model: nn.Module,
|
|
78
|
+
likelihood: Optional[nn.Module] = None,
|
|
79
|
+
learning_rate: float = 1e-3,
|
|
80
|
+
prior_sigma: float = 1.0,
|
|
81
|
+
auto_convert: bool = True,
|
|
82
|
+
**kwargs,
|
|
83
|
+
):
|
|
84
|
+
self.prior_sigma = prior_sigma
|
|
85
|
+
self.learning_rate = learning_rate
|
|
86
|
+
self.likelihood = likelihood if likelihood else GaussianLikelihood()
|
|
87
|
+
self.optimizer = None
|
|
88
|
+
|
|
89
|
+
if auto_convert:
|
|
90
|
+
model = self._make_bayesian(model)
|
|
91
|
+
|
|
92
|
+
super().__init__(model, **kwargs)
|
|
93
|
+
|
|
94
|
+
def _set_sampling_mode(self, active: bool):
|
|
95
|
+
"""Переключает флаг sampling во всех слоях BayesianLinear"""
|
|
96
|
+
for module in self.model.modules():
|
|
97
|
+
if isinstance(module, BayesianLinear):
|
|
98
|
+
module.sampling = active
|
|
99
|
+
|
|
100
|
+
def fit(
|
|
101
|
+
self,
|
|
102
|
+
train_loader,
|
|
103
|
+
val_loader=None,
|
|
104
|
+
epochs=100,
|
|
105
|
+
kl_weight=0.1,
|
|
106
|
+
verbose=True,
|
|
107
|
+
**kwargs,
|
|
108
|
+
):
|
|
109
|
+
device = next(self.model.parameters()).device
|
|
110
|
+
if kwargs.get("device"):
|
|
111
|
+
device = torch.device(kwargs["device"])
|
|
112
|
+
|
|
113
|
+
self.model.to(device)
|
|
114
|
+
self.likelihood.to(device)
|
|
115
|
+
|
|
116
|
+
params = list(self.model.parameters()) + list(self.likelihood.parameters())
|
|
117
|
+
self.optimizer = optim.Adam(params, lr=self.learning_rate)
|
|
118
|
+
|
|
119
|
+
history = {"train_loss": [], "nll": [], "kl": []}
|
|
120
|
+
|
|
121
|
+
for epoch in range(epochs):
|
|
122
|
+
self.model.train()
|
|
123
|
+
# включаем сэмплирование для обучения
|
|
124
|
+
self._set_sampling_mode(True)
|
|
125
|
+
|
|
126
|
+
total_loss = 0
|
|
127
|
+
|
|
128
|
+
for X, y in train_loader:
|
|
129
|
+
X, y = X.to(device), y.to(device)
|
|
130
|
+
self.optimizer.zero_grad()
|
|
131
|
+
|
|
132
|
+
# Вызов теперь без аргумента sample=True
|
|
133
|
+
preds = self.model(X)
|
|
134
|
+
|
|
135
|
+
nll = self.likelihood(preds, y)
|
|
136
|
+
kl = self._compute_recursive_kl(self.model)
|
|
137
|
+
loss = nll + kl_weight * kl
|
|
138
|
+
|
|
139
|
+
loss.backward()
|
|
140
|
+
self.optimizer.step()
|
|
141
|
+
total_loss += loss.item()
|
|
142
|
+
|
|
143
|
+
avg_loss = total_loss / len(train_loader)
|
|
144
|
+
history["train_loss"].append(avg_loss)
|
|
145
|
+
|
|
146
|
+
if verbose and (epoch + 1) % 100 == 0:
|
|
147
|
+
print(
|
|
148
|
+
f"Epoch {epoch + 1}/{epochs} | Loss: {avg_loss:.4f} | Sigma: {self.likelihood.get_noise_sigma():.4f}"
|
|
149
|
+
)
|
|
150
|
+
|
|
151
|
+
self.is_fitted = True
|
|
152
|
+
return history
|
|
153
|
+
|
|
154
|
+
def predict(
|
|
155
|
+
self, X: torch.Tensor, n_samples: int = 100
|
|
156
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
157
|
+
if not self.is_fitted:
|
|
158
|
+
raise RuntimeError("Model is not fitted yet.")
|
|
159
|
+
|
|
160
|
+
device = next(self.model.parameters()).device
|
|
161
|
+
X = X.to(device)
|
|
162
|
+
self.model.eval()
|
|
163
|
+
|
|
164
|
+
self._set_sampling_mode(True)
|
|
165
|
+
|
|
166
|
+
sampled_preds = []
|
|
167
|
+
noise_sigma = self.likelihood.get_noise_sigma()
|
|
168
|
+
|
|
169
|
+
with torch.no_grad():
|
|
170
|
+
for _ in range(n_samples):
|
|
171
|
+
preds = self.model(X)
|
|
172
|
+
|
|
173
|
+
eps = torch.randn_like(preds) * noise_sigma
|
|
174
|
+
sampled_preds.append(preds + eps)
|
|
175
|
+
|
|
176
|
+
stack = torch.stack(sampled_preds)
|
|
177
|
+
mean = stack.mean(dim=0)
|
|
178
|
+
std = stack.std(dim=0)
|
|
179
|
+
return mean.cpu(), std.cpu()
|
|
180
|
+
|
|
181
|
+
def sample_models(self, n_models: int = 10) -> List[nn.Module]:
|
|
182
|
+
if not self.is_fitted:
|
|
183
|
+
raise RuntimeError("Model is not fitted yet.")
|
|
184
|
+
|
|
185
|
+
models = []
|
|
186
|
+
for _ in range(n_models):
|
|
187
|
+
model_sample = copy.deepcopy(self.model)
|
|
188
|
+
model_sample.eval()
|
|
189
|
+
|
|
190
|
+
for module in model_sample.modules():
|
|
191
|
+
if isinstance(module, BayesianLinear):
|
|
192
|
+
w_sigma = F.softplus(module.w_rho)
|
|
193
|
+
b_sigma = F.softplus(module.b_rho)
|
|
194
|
+
|
|
195
|
+
# Генерируем фиксированные веса
|
|
196
|
+
w_sample = module.w_mu + w_sigma * torch.randn_like(module.w_mu)
|
|
197
|
+
b_sample = module.b_mu + b_sigma * torch.randn_like(module.b_mu)
|
|
198
|
+
|
|
199
|
+
module.w_mu.data = w_sample
|
|
200
|
+
module.b_mu.data = b_sample
|
|
201
|
+
|
|
202
|
+
# Отключаем сэмплирование внутри слоя навсегда
|
|
203
|
+
module.sampling = False
|
|
204
|
+
|
|
205
|
+
models.append(model_sample)
|
|
206
|
+
return models
|
|
207
|
+
|
|
208
|
+
def _compute_recursive_kl(self, module):
|
|
209
|
+
kl = 0
|
|
210
|
+
for child in module.children():
|
|
211
|
+
if hasattr(child, "kl_divergence"):
|
|
212
|
+
kl += child.kl_divergence()
|
|
213
|
+
else:
|
|
214
|
+
kl += self._compute_recursive_kl(child)
|
|
215
|
+
return kl
|
|
216
|
+
|
|
217
|
+
def _make_bayesian(self, model: nn.Module) -> nn.Module:
|
|
218
|
+
def replace_layers(module):
|
|
219
|
+
for name, child in module.named_children():
|
|
220
|
+
if isinstance(child, nn.Linear):
|
|
221
|
+
new_layer = BayesianLinear(
|
|
222
|
+
child.in_features, child.out_features, self.prior_sigma
|
|
223
|
+
)
|
|
224
|
+
with torch.no_grad():
|
|
225
|
+
new_layer.w_mu.data.copy_(child.weight.data)
|
|
226
|
+
if child.bias is not None:
|
|
227
|
+
new_layer.b_mu.data.copy_(child.bias.data)
|
|
228
|
+
setattr(module, name, new_layer)
|
|
229
|
+
else:
|
|
230
|
+
replace_layers(child)
|
|
231
|
+
|
|
232
|
+
replace_layers(model)
|
|
233
|
+
return model
|
|
234
|
+
|
|
235
|
+
# Временные заглушки!!!!!
|
|
236
|
+
def _get_ensemble_state(self):
|
|
237
|
+
return {}
|
|
238
|
+
|
|
239
|
+
def _set_ensemble_state(self, state):
|
|
240
|
+
pass
|