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 ADDED
File without changes
File without changes
bensemble/core/base.py ADDED
@@ -0,0 +1,73 @@
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
+ class BaseBayesianEnsemble(abc.ABC):
9
+ """Базовый класс для всех методов байесовского ансамблирования"""
10
+
11
+ def __init__(self, model: nn.Module, **kwargs):
12
+ self.model = model
13
+ self.is_fitted = False
14
+ self.ensemble = []
15
+
16
+ @abc.abstractmethod
17
+ def fit(
18
+ self, #
19
+ train_loader: torch.utils.data.DataLoader,
20
+ val_loader: Optional[torch.utils.data.DataLoader] = None,
21
+ **kwargs
22
+ ) -> Dict[str, List[float]]:
23
+ """Обучение ансамбля"""
24
+ # Надо обсудить параметры и реализацию
25
+ pass
26
+
27
+ @abc.abstractmethod
28
+ def predict(
29
+ self, X: torch.Tensor, n_samples: int = 100
30
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
31
+ """Предсказание с оценкой неопределенности"""
32
+ # Надо обсудить параметры и реализацию
33
+ pass
34
+
35
+ @abc.abstractmethod
36
+ def sample_models(
37
+ self, n_models: int = 10
38
+ ) -> List[
39
+ nn.Module
40
+ ]: # Добавить онлайн-поддерживание сгенереированных моделей -> Поменять предикт
41
+ """Сэмплирование моделей из апостериорного распределения"""
42
+ # Надо обсудить параметры
43
+ pass
44
+
45
+ def save(self, path: str): # Сделать загрузку и выгрузку моделей через стэйт диктов
46
+ """Сохранение обученного ансамбля"""
47
+ torch.save(
48
+ {
49
+ "model_state_dict": self.model.state_dict(),
50
+ "ensemble_state": self._get_ensemble_state(),
51
+ "is_fitted": self.is_fitted,
52
+ },
53
+ path,
54
+ )
55
+
56
+ def load(self, path: str): # Сделать загрузку и выгрузку моделей через стэйт диктов
57
+ """Загрузка обученного ансамбля"""
58
+ checkpoint = torch.load(path)
59
+ self.model.load_state_dict(checkpoint["model_state_dict"])
60
+ self._set_ensemble_state(checkpoint["ensemble_state"])
61
+ self.is_fitted = checkpoint["is_fitted"]
62
+
63
+ @abc.abstractmethod
64
+ def _get_ensemble_state(self) -> Dict[str, Any]:
65
+ """Получение внутреннего состояния ансамбля"""
66
+ # Надо обсудить параметры
67
+ pass
68
+
69
+ @abc.abstractmethod
70
+ def _set_ensemble_state(self, state: Dict[str, Any]):
71
+ """Установка внутреннего состояния ансамбля"""
72
+ # Надо обсудить параметры
73
+ pass
@@ -0,0 +1,50 @@
1
+ from typing import Tuple
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ def compute_uncertainty(predictions: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
8
+ """
9
+ Вычисление эпистемической и алеаторной неопределенности
10
+ """
11
+ # Эпистемическая неопределенность (вариация между моделями)
12
+ epistemic_uncertainty = predictions.var(dim=0)
13
+
14
+ # Алеаторная неопределенность (средняя энтропия предсказаний)
15
+ if predictions.dim() > 2: # Классификация
16
+ mean_probs = predictions.mean(dim=0)
17
+ aleatoric_uncertainty = -(mean_probs * torch.log(mean_probs + 1e-8)).sum(dim=-1)
18
+ else: # Регрессия
19
+ aleatoric_uncertainty = torch.zeros_like(epistemic_uncertainty)
20
+
21
+ return epistemic_uncertainty, aleatoric_uncertainty
22
+
23
+
24
+ def enable_dropout(model: nn.Module):
25
+ """Активация dropout слоев для MC Dropout"""
26
+ for module in model.modules():
27
+ if isinstance(module, nn.Dropout):
28
+ module.train()
29
+
30
+
31
+ class EarlyStopping:
32
+ """Ранняя остановка для обучения"""
33
+
34
+ def __init__(self, patience=10, delta=0):
35
+ self.patience = patience
36
+ self.delta = delta
37
+ self.counter = 0
38
+ self.best_score = None
39
+ self.early_stop = False
40
+
41
+ def __call__(self, val_loss):
42
+ if self.best_score is None:
43
+ self.best_score = val_loss
44
+ elif val_loss > self.best_score - self.delta:
45
+ self.counter += 1
46
+ if self.counter >= self.patience:
47
+ self.early_stop = True
48
+ else:
49
+ self.best_score = val_loss
50
+ self.counter = 0
File without changes
@@ -0,0 +1,470 @@
1
+ import copy
2
+ from typing import Any, Dict, List, Optional, Tuple
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+ from torch.utils.data import DataLoader
9
+
10
+ from core.base import BaseBayesianEnsemble
11
+
12
+
13
+ class LaplaceApproximation(BaseBayesianEnsemble):
14
+ """
15
+ A scalable Laplace approximation for neural networks based on Kronecker-factored curvature.
16
+ """
17
+
18
+ def __init__(
19
+ self,
20
+ model: nn.Module,
21
+ pretrained: bool = True,
22
+ likelihood: str = "classification",
23
+ verbose: bool = False,
24
+ ):
25
+ self.model = model
26
+ self.is_fitted = False
27
+ self.device = next(model.parameters()).device
28
+ if likelihood in ["classification", "regression"]:
29
+ self.likelihood = likelihood
30
+ else:
31
+ raise ValueError(f"Unsupported likelihood: {likelihood}")
32
+
33
+ self.pretrained = pretrained
34
+
35
+ # Storage for Kronecker factors
36
+ self.kronecker_factors = {}
37
+ self.sampling_factors = {}
38
+ self.dataset_size = 1
39
+
40
+ # Hook handles
41
+ self.hook_handles = []
42
+
43
+ self.verbose = verbose
44
+
45
+ def toggle_verbose(self):
46
+ """
47
+ Turn verbose on or off.
48
+ """
49
+ self.verbose = not self.verbose
50
+ print("Verbose:", "on" if self.verbose else "off")
51
+
52
+ def fit(
53
+ self,
54
+ train_loader: torch.utils.data.DataLoader,
55
+ val_loader: Optional[torch.utils.data.DataLoader] = None,
56
+ num_epochs: int = 100,
57
+ lr: float = 1e-3,
58
+ prior_precision: float = 1.0,
59
+ num_samples: int = 1000,
60
+ ) -> Dict[str, List[float]]:
61
+
62
+ history = {}
63
+
64
+ if not self.pretrained:
65
+ if self.verbose:
66
+ print("Training model...")
67
+ # Сначала обучаем модель MAP оценке
68
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=lr)
69
+ history["train_loss"] = []
70
+
71
+ for epoch in range(num_epochs):
72
+ self.model.train()
73
+ train_loss = 0.0
74
+ for batch_X, batch_y in train_loader:
75
+ optimizer.zero_grad()
76
+ output = self.model(batch_X)
77
+ if self.likelihood == "classification":
78
+ loss = F.cross_entropy(output, batch_y)
79
+ else:
80
+ loss = F.mse_loss(output, batch_y)
81
+ loss.backward()
82
+ optimizer.step()
83
+ train_loss += loss.item()
84
+
85
+ total_loss = train_loss / len(train_loader)
86
+ history["train_loss"].append(total_loss)
87
+
88
+ if self.verbose:
89
+ print(f"Epoch {epoch}: training loss = {total_loss:.4f}")
90
+
91
+ self.pretrained = True
92
+
93
+ self.compute_posterior(train_loader, prior_precision, num_samples)
94
+
95
+ return history
96
+
97
+ def compute_posterior(
98
+ self,
99
+ train_loader: DataLoader,
100
+ prior_precision: float = 0.0,
101
+ num_samples: int = 1000,
102
+ ) -> None:
103
+ """
104
+ Compute the Kronecker-factored Laplace approximation.
105
+ """
106
+ self.prior_precision = prior_precision
107
+ self.dataset_size = len(train_loader.dataset)
108
+
109
+ if self.verbose:
110
+ print("Registering hooks...")
111
+ self._register_hooks()
112
+
113
+ if self.verbose:
114
+ print("Estimating Kronecker factors...")
115
+ self._estimate_kronecker_factors(train_loader, num_samples)
116
+
117
+ if self.verbose:
118
+ print("Removing hooks...")
119
+ self._remove_hooks()
120
+
121
+ print("Posterior computation completed!")
122
+
123
+ def _register_hooks(self) -> None:
124
+ """Register forward hooks to capture activations and pre-activation Hessians."""
125
+ self.activations = {}
126
+ self.pre_activation_hessians = {}
127
+
128
+ def make_forward_hook(layer_name):
129
+ def forward_hook(module, input, output):
130
+ if isinstance(input, tuple):
131
+ input = input[0]
132
+ # Store input activations for Q factor
133
+ self.activations[layer_name] = input.detach().clone()
134
+
135
+ return forward_hook
136
+
137
+ # Register hooks for linear layers
138
+ for name, module in self.model.named_modules():
139
+ if isinstance(module, nn.Linear):
140
+ forward_handle = module.register_forward_hook(make_forward_hook(name))
141
+ self.hook_handles.append(forward_handle)
142
+
143
+ def _remove_hooks(self) -> None:
144
+ """Remove all registered hooks."""
145
+ for handle in self.hook_handles:
146
+ handle.remove()
147
+ self.hook_handles.clear()
148
+
149
+ def _compute_pre_activation_hessian(self, output, target):
150
+ """
151
+ Compute the Hessian with respect to the final layer pre-activations.
152
+ This depends on the likelihood function.
153
+ """
154
+ batch_size = output.shape[0]
155
+
156
+ if self.likelihood == "classification":
157
+ # For cross-entropy loss with softmax, the Hessian is:
158
+ # H = diag(p) - pp^T, where p is the softmax probabilities
159
+ probs = F.softmax(output, dim=1)
160
+ eye = torch.eye(probs.size(1), device=self.device).unsqueeze(0) # (1, C, C)
161
+ probs_outer = torch.einsum("bi,bj->bij", probs, probs) # (B, C, C)
162
+ hessian = (
163
+ probs_outer - eye
164
+ ) # This is actually -H, but we'll account for sign later
165
+ return -hessian # Return the negative Hessian of NLL
166
+
167
+ else: # self.likelihood == 'regression':
168
+ # For MSE loss, the Hessian is identity
169
+ output_dim = output.shape[1]
170
+ hessian = (
171
+ torch.eye(output_dim, device=self.device)
172
+ .unsqueeze(0)
173
+ .repeat(batch_size, 1, 1)
174
+ )
175
+ return hessian
176
+
177
+ def _backward_hessian(self, hessian_final):
178
+ """
179
+ Correct recursive backpropagation of pre-activation Hessian.
180
+ Uses weights of the NEXT layer to compute Hessian for the CURRENT layer.
181
+ """
182
+ hessians = {}
183
+
184
+ # Get all linear layers in forward order
185
+ linear_layers = []
186
+ for name, module in self.model.named_modules():
187
+ if isinstance(module, nn.Linear):
188
+ linear_layers.append((name, module))
189
+
190
+ # Initialize with the final layer Hessian
191
+ if hessian_final.dim() == 3:
192
+ current_hessian = hessian_final.mean(0) # Average over batch
193
+ else:
194
+ current_hessian = hessian_final
195
+
196
+ final_layer_name, final_layer = linear_layers[-1]
197
+ hessians[final_layer_name] = current_hessian
198
+
199
+ # Backpropagate through layers in REVERSE order (from output to input)
200
+ for i in range(
201
+ len(linear_layers) - 2, -1, -1
202
+ ): # Start from second-to-last layer
203
+ current_layer_name, current_layer = linear_layers[i]
204
+ next_layer_name, next_layer = linear_layers[i + 1]
205
+
206
+ # The recursive formula: H_λ = W_{λ+1}^T @ H_{λ+1} @ W_{λ+1} + D_λ
207
+ # For piecewise linear activations (ReLU), D_λ ≈ 0
208
+ W_next = next_layer.weight # Shape: (out_dim_{λ+1}, in_dim_{λ+1})
209
+
210
+ # H_current = W_next^T @ H_next @ W_next
211
+ H_current = W_next.T @ current_hessian @ W_next
212
+
213
+ # Store the Hessian for this layer
214
+ hessians[current_layer_name] = H_current
215
+
216
+ # Update for next iteration
217
+ current_hessian = H_current
218
+
219
+ return hessians
220
+
221
+ def _estimate_kronecker_factors(
222
+ self, train_loader: DataLoader, num_samples: int
223
+ ) -> None:
224
+ """
225
+ Estimate Kronecker factors using proper Hessian computation.
226
+ """
227
+ self.model.eval() # We want deterministic behavior for curvature estimation
228
+
229
+ accumulators = {}
230
+ sample_count = 0
231
+
232
+ if self.verbose:
233
+ print(f"Processing up to {num_samples} samples...")
234
+
235
+ for batch_idx, (data, target) in enumerate(train_loader):
236
+ if sample_count >= num_samples:
237
+ break
238
+
239
+ data, target = data.to(self.device), target.to(self.device)
240
+ batch_size = data.shape[0]
241
+
242
+ # Forward pass
243
+ output = self.model(data)
244
+
245
+ # Compute pre-activation Hessian for the final layer
246
+ H_final = self._compute_pre_activation_hessian(output, target)
247
+
248
+ # Backpropagate Hessian through all layers
249
+ layer_hessians = self._backward_hessian(H_final)
250
+
251
+ # Process each layer
252
+ with torch.no_grad():
253
+ for name, module in self.model.named_modules():
254
+ if (
255
+ isinstance(module, nn.Linear)
256
+ and name in self.activations
257
+ and name in layer_hessians
258
+ ):
259
+ a = self.activations[name] # input activations (B, in_dim)
260
+ H = layer_hessians[
261
+ name
262
+ ] # pre-activation Hessian (out_dim, out_dim)
263
+
264
+ if name not in accumulators:
265
+ in_dim = a.shape[1]
266
+ out_dim = H.shape[0] if H.dim() == 2 else H.shape[1]
267
+
268
+ accumulators[name] = {
269
+ "Q_sum": torch.zeros(
270
+ in_dim, in_dim, device=self.device
271
+ ),
272
+ "H_sum": torch.zeros(
273
+ out_dim, out_dim, device=self.device
274
+ ),
275
+ "count": 0,
276
+ "in_dim": in_dim,
277
+ "out_dim": out_dim,
278
+ }
279
+
280
+ # Compute Q factor: covariance of input activations
281
+ batch_Q = torch.einsum("bi,bj->ij", a, a) / batch_size
282
+
283
+ # H factor is already computed from backpropagation
284
+ # Average if we have multiple samples
285
+ if H.dim() == 3: # batch of Hessians
286
+ batch_H = H.mean(0)
287
+ else:
288
+ batch_H = H
289
+
290
+ accumulators[name]["Q_sum"] += batch_Q * batch_size
291
+ accumulators[name]["H_sum"] += batch_H * batch_size
292
+ accumulators[name]["count"] += batch_size
293
+
294
+ sample_count += batch_size
295
+ if sample_count % 1000 == 0 and self.verbose:
296
+ print(f"Processed {sample_count} samples...")
297
+
298
+ # Compute final factors with proper regularization
299
+ if self.verbose:
300
+ print("Computing final Kronecker factors...")
301
+ with torch.no_grad():
302
+ for name, acc in accumulators.items():
303
+ if acc["count"] == 0:
304
+ continue
305
+
306
+ # Expected Kronecker factors (Equation 7 in the paper)
307
+ Q = acc["Q_sum"] / acc["count"] # E[Q_λ]
308
+ H = acc["H_sum"] / acc["count"] # E[H_λ]
309
+
310
+ # Add prior precision and scale by dataset size (Equation 9)
311
+ N = self.dataset_size
312
+ tau = self.prior_precision
313
+
314
+ Q_reg = np.sqrt(N) * Q + np.sqrt(tau) * torch.eye(
315
+ acc["in_dim"], device=self.device
316
+ )
317
+ H_reg = np.sqrt(N) * H + np.sqrt(tau) * torch.eye(
318
+ acc["out_dim"], device=self.device
319
+ )
320
+
321
+ # Store the precision matrices for sampling
322
+ self.kronecker_factors[name] = {
323
+ "Q": Q_reg, # Precision for rows
324
+ "H": H_reg, # Precision for columns
325
+ }
326
+
327
+ if self.verbose:
328
+ print(
329
+ f"Layer {name}:\nQ shape {Q_reg.shape}, H shape {H_reg.shape}"
330
+ )
331
+ Q_norm = torch.norm(Q_reg).item()
332
+ H_norm = torch.norm(H_reg).item()
333
+ print(f" Q norm: {Q_norm:.6f}, H norm: {H_norm:.6f}")
334
+ cond_Q = torch.linalg.cond(Q_reg)
335
+ cond_H = torch.linalg.cond(H_reg)
336
+ print(f"cond(Q)={cond_Q:.2e}, cond(H)={cond_H:.2e}")
337
+
338
+ # Convert to covariance matrices for sampling
339
+ U = torch.linalg.inv(Q_reg) # Row covariance
340
+ V = torch.linalg.inv(H_reg) # Column covariance
341
+
342
+ # Matrix sqrt for sampling
343
+ L_U = self._matrix_sqrt(U)
344
+ L_V = self._matrix_sqrt(V)
345
+
346
+ self.sampling_factors[name] = {
347
+ "L_U": L_U,
348
+ "L_V": L_V,
349
+ "weight_shape": (acc["out_dim"], acc["in_dim"]),
350
+ }
351
+
352
+ def _matrix_sqrt(self, A: torch.Tensor) -> torch.Tensor:
353
+ """Compute matrix square root using eigen decomposition."""
354
+ # Eigen decomposition for symmetric matrices
355
+ L, V = torch.linalg.eigh(A)
356
+ return V @ torch.diag(torch.sqrt(L)) @ V.T
357
+
358
+ def sample_models(
359
+ self, n_models: int = 10, temperature: float = 1.0
360
+ ) -> List[nn.Module]:
361
+ """
362
+ Sample weight matrices from the matrix normal posterior.
363
+ Returns a list of dictionaries, where each dictionary contains
364
+ the complete set of weights for one sampled model.
365
+
366
+ Args:
367
+ num_samples: Number of model samples to generate
368
+
369
+ Returns:
370
+ List of dictionaries, where each dict has layer names as keys
371
+ and sampled weight tensors as values
372
+ """
373
+ samples = []
374
+
375
+ for i in range(n_models):
376
+ weight_sample = {}
377
+
378
+ for name, factors in self.sampling_factors.items():
379
+ module = dict(self.model.named_modules())[name]
380
+ M = module.weight.data # MAP estimate
381
+
382
+ L_V = factors["L_V"] # Row precision (in_dim, in_dim)
383
+ L_U = factors["L_U"] # Column precision (out_dim, out_dim)
384
+ weight_shape = factors["weight_shape"]
385
+
386
+ # Generate single sample for this layer
387
+ Z = torch.randn(weight_shape, device=self.device)
388
+ W_sample = M + temperature * L_V @ Z @ L_U.T
389
+
390
+ # Store in the model sample dictionary
391
+ weight_sample[f"{name}.weight"] = W_sample.cpu()
392
+
393
+ # Also include bias terms if they exist
394
+ for name, module in self.model.named_modules():
395
+ if isinstance(module, nn.Linear) and module.bias is not None:
396
+ # For bias, we can use a simple diagonal approximation
397
+ # or sample from the appropriate marginal distribution
398
+ if name in self.kronecker_factors:
399
+ # The bias is typically part of the same layer's distribution
400
+ # but for simplicity, we'll use the MAP estimate for bias
401
+ weight_sample[f"{name}.bias"] = module.bias.data.clone()
402
+
403
+ model_sample = copy.deepcopy(self.model)
404
+ model_sample.load_state_dict(weight_sample)
405
+
406
+ samples.append(model_sample)
407
+
408
+ return samples
409
+
410
+ def predict(
411
+ self, X: torch.Tensor, n_samples: int = 100, temperature: float = 1.0
412
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
413
+ """
414
+ Compute predictive distribution using sampled weights.
415
+ """
416
+ predictions = []
417
+
418
+ for _ in range(n_samples):
419
+ sampled_model = self.sample_models(n_models=1, temperature=temperature)[0]
420
+ sampled_model.to(self.device)
421
+
422
+ with torch.no_grad():
423
+ output = sampled_model(X)
424
+ predictions.append(output)
425
+
426
+ sampled_model.cpu()
427
+
428
+ predictions = torch.stack(predictions)
429
+
430
+ if self.likelihood == "classification":
431
+ probs = F.softmax(predictions, dim=-1)
432
+ mean_probs = probs.mean(dim=0)
433
+ uncertainty = -(mean_probs * torch.log(mean_probs + 1e-8)).sum(dim=-1)
434
+ return mean_probs, uncertainty
435
+ else:
436
+ mean = predictions.mean(dim=0)
437
+ variance = predictions.var(dim=0)
438
+ return mean, variance
439
+
440
+ def _get_ensemble_state(self) -> Dict[str, Any]:
441
+ """Получение внутреннего состояния ансамбля"""
442
+ return {
443
+ "model": self.model,
444
+ "is_fitted": self.is_fitted,
445
+ "device": self.device,
446
+ "likelihood": self.likelihood,
447
+ "pretrained": self.pretrained,
448
+ "kronecker_factors": self.kronecker_factors,
449
+ "sampling_factors": self.sampling_factors,
450
+ "dataset_size": self.dataset_size,
451
+ "hook_handles": self.hook_handles,
452
+ "verbose": self.verbose,
453
+ }
454
+
455
+ def _set_ensemble_state(self, state: Dict[str, Any]):
456
+ """Установка внутреннего состояния ансамбля"""
457
+ if state["likelihood"] in ["classification", "regression"]:
458
+ self.likelihood = state[""]
459
+ else:
460
+ raise ValueError(f"Unsupported likelihood: {state['']}")
461
+
462
+ self.model = state["model"]
463
+ self.is_fitted = state["is_fitted"]
464
+ self.device = state["device"]
465
+ self.pretrained = state["pretrained"]
466
+ self.kronecker_factors = state["kronecker_factors"]
467
+ self.sampling_factors = state["sampling_factors"]
468
+ self.dataset_size = state["dataset_size"]
469
+ self.hook_handles = state["hook_handles"]
470
+ self.verbose = state["verbose"]