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,268 @@
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
+ class PBPEnsemble(BaseBayesianEnsemble):
11
+ """Bayesian ensemble using Probabilistic Backpropagation (PBP)"""
12
+
13
+ class ProbLinear(nn.Module):
14
+ def __init__(self, in_features: int, out_features: int):
15
+ super().__init__()
16
+ self.in_features = in_features
17
+ self.out_features = out_features
18
+ d = self.in_features + 1 # +1 bias
19
+ h = self.out_features
20
+ scale = 1.0 / math.sqrt(d)
21
+ self.m = nn.Parameter(scale * torch.randn(h, d, dtype=torch.float64))
22
+ self.v = nn.Parameter(0.5 * torch.ones(h, d, dtype=torch.float64))
23
+
24
+ class PBPNet(nn.Module):
25
+ def __init__(self, layer_sizes: List[int]):
26
+ super().__init__()
27
+ self.layers: List[PBPEnsemble.ProbLinear] = nn.ModuleList()
28
+ for i in range(len(layer_sizes) - 1):
29
+ self.layers.append(
30
+ PBPEnsemble.ProbLinear(layer_sizes[i], layer_sizes[i + 1])
31
+ )
32
+
33
+ def forward_moments(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
34
+ batch = x.shape[0]
35
+ mz = torch.cat([x, torch.ones(batch, 1, dtype=torch.float64)], dim=1)
36
+ vz = torch.zeros_like(mz)
37
+
38
+ for li, layer in enumerate(self.layers):
39
+ d = layer.in_features + 1
40
+ scale = 1.0 / math.sqrt(d)
41
+
42
+ ma = (mz @ layer.m.t()) * scale
43
+ term1 = vz @ (layer.m**2).t()
44
+ term2 = (mz**2) @ layer.v.t()
45
+ term3 = vz @ layer.v.t()
46
+ va = (term1 + term2 + term3) * (scale**2)
47
+
48
+ is_last = li == len(self.layers) - 1
49
+ if not is_last:
50
+ mb, vb = PBPEnsemble.relu_moments(ma, va)
51
+ mz = torch.cat(
52
+ [mb, torch.ones(batch, 1, dtype=torch.float64)], dim=1
53
+ )
54
+ vz = torch.cat(
55
+ [vb, torch.zeros(batch, 1, dtype=torch.float64)], dim=1
56
+ )
57
+ else:
58
+ mz = ma
59
+ vz = va
60
+ return mz, vz
61
+
62
+ def __init__(self, layer_sizes: List[int], **kwargs):
63
+ model = self.PBPNet(layer_sizes)
64
+ super().__init__(model, **kwargs)
65
+ self.alpha_g = torch.tensor(6.0, dtype=torch.float64) # noise precision
66
+ self.beta_g = torch.tensor(6.0, dtype=torch.float64)
67
+ self.alpha_l = torch.tensor(6.0, dtype=torch.float64) # weight precision
68
+ self.beta_l = torch.tensor(6.0, dtype=torch.float64)
69
+
70
+ @staticmethod
71
+ def phi(x: torch.Tensor) -> torch.Tensor:
72
+ return torch.exp(-0.5 * x * x) / math.sqrt(2.0 * math.pi)
73
+
74
+ @staticmethod
75
+ def Phi(x: torch.Tensor) -> torch.Tensor:
76
+ return 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0)))
77
+
78
+ @staticmethod
79
+ def relu_moments(
80
+ m: torch.Tensor, v: torch.Tensor, eps: float = 1e-12
81
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
82
+ v = torch.clamp(v, min=eps)
83
+ sigma = torch.sqrt(v)
84
+ alpha = m / sigma
85
+ alpha_eval = torch.clamp(alpha, min=-10.0, max=10.0)
86
+ pdf = PBPEnsemble.phi(alpha_eval)
87
+ cdf = PBPEnsemble.Phi(alpha_eval)
88
+ mean = sigma * pdf + m * cdf
89
+ second_moment = (v + m * m) * cdf + m * sigma * pdf
90
+ var = torch.clamp(second_moment - mean * mean, min=eps)
91
+ return mean, var
92
+
93
+ @staticmethod
94
+ def logZ_gaussian_likelihood(y, mz, vz, alpha_g, beta_g, eps=1e-12):
95
+ alpha_g = torch.clamp(alpha_g, min=1.0 + 1e-6)
96
+ sigma2_eff = beta_g / (alpha_g - 1.0) + vz
97
+ sigma2_eff = torch.clamp(sigma2_eff, min=eps)
98
+ return (
99
+ -0.5 * ((y - mz) ** 2) / sigma2_eff
100
+ - 0.5 * torch.log(2.0 * math.pi * sigma2_eff)
101
+ ).squeeze(-1)
102
+
103
+ @staticmethod
104
+ def gamma_adf_update_from_Z(
105
+ logZ, logZ1, logZ2, alpha_old, beta_old, clamp_eps=1e-9
106
+ ):
107
+ r1 = torch.exp(logZ1 - logZ)
108
+ r2 = torch.exp(logZ2 - logZ)
109
+ term_alpha = (r2 / (r1 * r1)) * ((alpha_old + 1.0) / alpha_old)
110
+ denom_alpha = torch.clamp(term_alpha - 1.0, min=1e-12)
111
+ alpha_new = 1.0 / denom_alpha
112
+ termA = r2 / r1 * ((alpha_old + 1.0) / beta_old)
113
+ termB = r1 * (alpha_old / beta_old)
114
+ denom_beta = torch.clamp(termA - termB, min=clamp_eps)
115
+ beta_new = 1.0 / denom_beta
116
+ alpha_new = torch.clamp(alpha_new, min=1.0 + 1e-6, max=1e6)
117
+ beta_new = torch.clamp(beta_new, min=clamp_eps, max=1e9)
118
+ return alpha_new.detach(), beta_new.detach()
119
+
120
+ def single_datapoint_adf_step(
121
+ self, x: torch.Tensor, y: torch.Tensor, step_clip: float = 1.0
122
+ ):
123
+ net = self.model
124
+ for layer in net.layers:
125
+ layer.m.requires_grad_(True)
126
+ layer.v.requires_grad_(True)
127
+ mz, vz = net.forward_moments(x[None, :])
128
+ logZ = self.logZ_gaussian_likelihood(
129
+ y[None, None], mz, vz, self.alpha_g, self.beta_g
130
+ ).mean()
131
+ logZ1 = self.logZ_gaussian_likelihood(
132
+ y[None, None], mz, vz, self.alpha_g + 1.0, self.beta_g
133
+ ).mean()
134
+ logZ2 = self.logZ_gaussian_likelihood(
135
+ y[None, None], mz, vz, self.alpha_g + 2.0, self.beta_g
136
+ ).mean()
137
+ for p in net.parameters():
138
+ if p.grad is not None:
139
+ p.grad.zero_()
140
+ logZ.backward()
141
+ for layer in net.layers:
142
+ gm = layer.m.grad
143
+ gv = layer.v.grad
144
+ if step_clip is not None:
145
+ gm = torch.clamp(gm, min=-step_clip, max=step_clip)
146
+ gv = torch.clamp(gv, min=-step_clip, max=step_clip)
147
+ m = layer.m
148
+ v = torch.clamp(layer.v, min=1e-10, max=1e3)
149
+ m_new = m + v * gm
150
+ v_new = v - (v * v) * (gm * gm - 2.0 * gv)
151
+ m_new = m_new.detach()
152
+ v_new = v_new.detach()
153
+ with torch.no_grad():
154
+ layer.m.copy_(m_new)
155
+ layer.v.copy_(v_new)
156
+ self.alpha_g, self.beta_g = self.gamma_adf_update_from_Z(
157
+ logZ.detach(), logZ1.detach(), logZ2.detach(), self.alpha_g, self.beta_g
158
+ )
159
+ for layer in net.layers:
160
+ layer.m.grad = None
161
+ layer.v.grad = None
162
+
163
+ def prior_refresh_epoch(self, n_refresh: int = 1):
164
+ net = self.model
165
+ alpha_l = torch.clamp(self.alpha_l, min=1.0 + 1e-6)
166
+ beta_l = self.beta_l
167
+ for _ in range(n_refresh):
168
+ s2 = beta_l / (alpha_l - 1.0)
169
+ s2_1 = beta_l / (alpha_l)
170
+ s2_2 = beta_l / (alpha_l + 1.0)
171
+ Z_acc = 0.0
172
+ Z1_acc = 0.0
173
+ Z2_acc = 0.0
174
+ n_tot = 0
175
+ for layer in net.layers:
176
+ m = layer.m
177
+ v = torch.clamp(layer.v, min=1e-12)
178
+ m_tmp = m.detach().clone().requires_grad_(True)
179
+ v_tmp = v.detach().clone().requires_grad_(True)
180
+ sigma2 = s2 + v_tmp
181
+ lp = -0.5 * (m_tmp**2) / sigma2 - 0.5 * torch.log(
182
+ 2.0 * math.pi * sigma2
183
+ )
184
+ logZ_prior = lp.sum()
185
+ for p in [m_tmp, v_tmp]:
186
+ if p.grad is not None:
187
+ p.grad.zero_()
188
+ logZ_prior.backward()
189
+ gm = m_tmp.grad
190
+ gv = v_tmp.grad
191
+ m_new = m + v * gm
192
+ v_new = v - (v * v) * (gm * gm - 2.0 * gv)
193
+ v_new = torch.clamp(v_new, min=1e-12, max=1e3)
194
+ m_new = m_new.detach()
195
+ v_new = v_new.detach()
196
+ with torch.no_grad():
197
+ layer.m.copy_(m_new)
198
+ layer.v.copy_(v_new)
199
+
200
+ def sum_logZ_given_s2(s2_local: torch.Tensor) -> torch.Tensor:
201
+ sigma2_local = s2_local + v
202
+ lp_local = -0.5 * (m**2) / sigma2_local - 0.5 * torch.log(
203
+ 2.0 * math.pi * sigma2_local
204
+ )
205
+ return lp_local.sum()
206
+
207
+ Z_acc += sum_logZ_given_s2(s2).detach()
208
+ Z1_acc += sum_logZ_given_s2(s2_1).detach()
209
+ Z2_acc += sum_logZ_given_s2(s2_2).detach()
210
+ n_tot += m.numel()
211
+ logZ_avg = Z_acc / max(n_tot, 1)
212
+ logZ1_avg = Z1_acc / max(n_tot, 1)
213
+ logZ2_avg = Z2_acc / max(n_tot, 1)
214
+ alpha_l, beta_l = self.gamma_adf_update_from_Z(
215
+ logZ_avg, logZ1_avg, logZ2_avg, alpha_l, beta_l
216
+ )
217
+ self.alpha_l = alpha_l.detach()
218
+ self.beta_l = beta_l.detach()
219
+
220
+ def fit(
221
+ self,
222
+ train_loader: torch.utils.data.DataLoader,
223
+ val_loader: Optional[torch.utils.data.DataLoader] = None,
224
+ epochs: int = 1,
225
+ step_clip: float = 2.0,
226
+ refresh_prior: bool = True,
227
+ **kwargs
228
+ ) -> Dict[str, List[float]]:
229
+ """Пример реализации fit для PBP"""
230
+ self.model.train()
231
+ history = {"rmse": [], "nlpd": []}
232
+ for epoch in range(epochs):
233
+ for x, y in train_loader:
234
+ self.single_datapoint_adf_step(x, y, step_clip=step_clip)
235
+ if refresh_prior:
236
+ self.prior_refresh_epoch(n_refresh=1)
237
+ self.is_fitted = True
238
+ return history
239
+
240
+ def predict(
241
+ self, X: torch.Tensor, n_samples: int = 100
242
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
243
+ """Предсказание среднего и дисперсии"""
244
+ self.model.eval()
245
+ with torch.no_grad():
246
+ mz, vz = self.model.forward_moments(X)
247
+ sigma2_eff = self.beta_g / (self.alpha_g - 1.0) + vz
248
+ return mz, sigma2_eff
249
+
250
+ def sample_models(self, n_models: int = 10) -> List[nn.Module]:
251
+ """Простейший метод сэмплирования моделей — копии текущей модели"""
252
+ return [self.model for _ in range(n_models)]
253
+
254
+ def _get_ensemble_state(self) -> Dict[str, Any]:
255
+ return {
256
+ "alpha_g": self.alpha_g,
257
+ "beta_g": self.beta_g,
258
+ "alpha_l": self.alpha_l,
259
+ "beta_l": self.beta_l,
260
+ "model_state": self.model.state_dict(),
261
+ }
262
+
263
+ def _set_ensemble_state(self, state: Dict[str, Any]):
264
+ self.alpha_g = state["alpha_g"]
265
+ self.beta_g = state["beta_g"]
266
+ self.alpha_l = state["alpha_l"]
267
+ self.beta_l = state["beta_l"]
268
+ self.model.load_state_dict(state["model_state"])