Coverage for /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/equine/equine_gp.py: 99%
386 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-20 23:10 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-20 23:10 +0000
1# Copyright 2024, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
2# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
3# SPDX-License-Identifier: MIT
5import math
6import sys
7import warnings
8from collections import OrderedDict
9from collections.abc import Callable, Iterable, Sized
10from datetime import datetime
11from typing import Any, Self, cast
13import icontract
14import torch
15from beartype import beartype
16from torch.utils.data import DataLoader, Dataset, TensorDataset
17from torchmetrics.metric import Metric
18from tqdm import tqdm
20from .equine import Equine, EquineOutput, _eval_mode
21from .registry import _describe_error, _positive_int, _truncate
22from .utils import (
23 EQUINE_FORMAT_VERSION,
24 _adopt_stored_dtypes,
25 _checked_settings,
26 _embedding_checkpoint,
27 _get_shuffle_idxs_by_class,
28 _input_to_model,
29 _load_checkpoint_for_device,
30 _plain_names,
31 _plain_train_summary,
32 _rebuild_embedding,
33 _refuse_torchscript,
34 _require_device,
35 _require_entries,
36 _require_examples,
37 _require_finite_embeddings,
38 _require_matching_weights,
39 _require_names,
40 _support_from_file,
41 generate_support,
42 generate_train_summary,
43)
45BatchType = tuple[torch.Tensor, ...]
46# -------------------------------------------------------------------------------
47# Note that the below code for
48# * `_random_ortho`,
49# * `_RandomFourierFeatures``, and
50# * `_Laplace`
51# is copied and modified from https://github.com/y0ast/DUE/blob/main/due/sngp.py
52# under its original MIT license, redisplayed here:
53# -------------------------------------------------------------------------------
54# MIT License
55#
56# Copyright (c) 2021 Joost van Amersfoort
57#
58# Permission is hereby granted, free of charge, to any person obtaining a copy
59# of this software and associated documentation files (the "Software"), to deal
60# in the Software without restriction, including without limitation the rights
61# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
62# copies of the Software, and to permit persons to whom the Software is
63# furnished to do so, subject to the following conditions:
64#
65# The above copyright notice and this permission notice shall be included in all
66# copies or substantial portions of the Software.
67#
68# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
69# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
70# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
71# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
72# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
73# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
74# SOFTWARE.
75# ------------------------------------------------------------------------------
76# Following the recommendation of their README at https://github.com/y0ast/DUE
77# we encourage anyone using this code in their research to cite the following papers:
78#
79# @article{van2021on,
80# title={On Feature Collapse and Deep Kernel Learning for Single Forward Pass Uncertainty},
81# author={van Amersfoort, Joost and Smith, Lewis and Jesson, Andrew and Key, Oscar and Gal, Yarin},
82# journal={arXiv preprint arXiv:2102.11409},
83# year={2021}
84# }
85#
86# @article{liu2020simple,
87# title={Simple and principled uncertainty estimation with deterministic deep learning via distance awareness},
88# author={Liu, Jeremiah and Lin, Zi and Padhy, Shreyas and Tran, Dustin and Bedrax Weiss, Tania and Lakshminarayanan, Balaji},
89# journal={Advances in Neural Information Processing Systems},
90# volume={33},
91# pages={7498--7512},
92# year={2020}
93# }
96@beartype
97def _random_ortho(n: int, m: int) -> torch.Tensor:
98 """
99 Generate a random orthonormal matrix.
101 Parameters
102 ----------
103 n : int
104 The number of rows.
105 m : int
106 The number of columns.
108 Returns
109 -------
110 torch.Tensor
111 The random orthonormal matrix.
112 """
113 q, _ = torch.linalg.qr(torch.randn(n, m))
114 return q
117@beartype
118class _RandomFourierFeatures(torch.nn.Module):
119 """
120 A private class to generate random Fourier features for the embedding model.
121 """
123 W: torch.Tensor
124 b: torch.Tensor
125 feature_scale: torch.Tensor
127 def __init__(
128 self, in_dim: int, num_random_features: int, feature_scale: float | None
129 ) -> None:
130 """
131 Initialize the _RandomFourierFeatures module, which generates random Fourier features
132 for the embedding model.
134 Parameters
135 ----------
136 in_dim : int
137 The input dimensionality.
138 num_random_features : int
139 The number of random Fourier features to generate.
140 feature_scale : float | None
141 The scaling factor for the random Fourier features. If None, defaults to sqrt(num_random_features / 2).
142 """
143 super().__init__()
144 if feature_scale is None:
145 feature_scale = math.sqrt(num_random_features / 2)
147 self.register_buffer("feature_scale", torch.tensor(feature_scale))
149 if num_random_features <= in_dim:
150 W: torch.Tensor = _random_ortho(in_dim, num_random_features)
151 else:
152 # generate blocks of orthonormal rows which are not necessarily orthonormal
153 # to each other.
154 dim_left = num_random_features
155 ws = []
156 while dim_left > in_dim:
157 ws.append(_random_ortho(in_dim, in_dim))
158 dim_left -= in_dim
159 ws.append(_random_ortho(in_dim, dim_left))
160 W: torch.Tensor = torch.cat(ws, 1)
162 feature_norm = torch.randn(W.shape) ** 2
164 W = W * feature_norm.sum(0).sqrt()
165 self.register_buffer("W", W)
167 b: torch.Tensor = torch.empty(num_random_features).uniform_(0, 2 * math.pi)
168 self.register_buffer("b", b)
170 def forward(self, x: torch.Tensor) -> torch.Tensor:
171 """
172 Compute the forward pass of the _RandomFourierFeatures module.
174 Parameters
175 ----------
176 x : torch.Tensor
177 The input tensor of shape (batch_size, in_dim).
179 Returns
180 -------
181 torch.Tensor
182 The output tensor of shape (batch_size, num_random_features).
183 """
184 k = torch.cos(x @ self.W + self.b)
185 k = k / self.feature_scale
187 return k
190def _inverse_via_cholesky(a: torch.Tensor) -> torch.Tensor:
191 """
192 Invert the symmetric positive-definite ``a`` through its Cholesky factor.
194 Raises
195 ------
196 torch.linalg.LinAlgError
197 If ``a`` is not positive definite.
198 """
199 u, info = torch.linalg.cholesky_ex(a)
200 if not bool((info == 0).all()):
201 raise torch.linalg.LinAlgError("Precision matrix inversion failed!") # type: ignore
202 return torch.cholesky_inverse(u)
205def _sync_seen_count(module: "_Laplace", incompatible_keys: Any) -> None:
206 """``load_state_dict`` post hook: the Python ``_seen_count`` follows the loaded ``seen_data``."""
207 module._seen_count = int(module.seen_data)
210class _Laplace(torch.nn.Module):
211 """
212 A private class to compute a Laplace approximation to a Gaussian Process (GP)
213 """
215 random_matrix: torch.Tensor
217 def __init__(
218 self,
219 feature_extractor: torch.nn.Module,
220 num_deep_features: int,
221 num_gp_features: int,
222 normalize_gp_features: bool,
223 num_random_features: int,
224 num_outputs: int,
225 feature_scale: float | None,
226 mean_field_factor: float | None, # required for classification problems
227 ridge_penalty: float = 1.0,
228 ) -> None:
229 """
230 Initialize the _Laplace module.
232 Parameters
233 ----------
234 feature_extractor : torch.nn.Module
235 The feature extractor module.
236 num_deep_features : int
237 The number of features output by the feature extractor.
238 num_gp_features : int
239 The number of features to use in the Gaussian process.
240 normalize_gp_features : bool
241 Whether to normalize the GP features.
242 num_random_features : int
243 The number of random Fourier features to use.
244 num_outputs : int
245 The number of outputs of the model.
246 feature_scale : float | None
247 The scaling factor for the random Fourier features.
248 mean_field_factor : float | None
249 The mean-field factor for the Gaussian-Softmax approximation.
250 Required for classification problems.
251 ridge_penalty : float, optional
252 The ridge penalty for the Laplace approximation.
253 """
254 super().__init__()
255 self.feature_extractor = feature_extractor
256 self.mean_field_factor = mean_field_factor
257 self.ridge_penalty = ridge_penalty
258 self.train_batch_size = 0 # to be set later
260 if num_gp_features > 0:
261 self.num_gp_features = num_gp_features
262 random_matrix: torch.Tensor = torch.normal(
263 0, 0.05, (num_gp_features, num_deep_features)
264 )
265 self.register_buffer("random_matrix", random_matrix)
266 else:
267 self.num_gp_features: int = num_deep_features
268 self._has_projection: bool = num_gp_features > 0
270 self.normalize_gp_features = normalize_gp_features
271 if normalize_gp_features:
272 self.normalize: torch.nn.LayerNorm = torch.nn.LayerNorm(num_gp_features)
274 self.rff: _RandomFourierFeatures = _RandomFourierFeatures(
275 num_gp_features, num_random_features, feature_scale
276 )
277 self.beta: torch.nn.Linear = torch.nn.Linear(num_random_features, num_outputs)
279 self.num_data = 0 # to be set later
280 self.register_buffer("seen_data", torch.tensor(0))
281 # A Python mirror of seen_data, read back from the buffer after load_state_dict.
282 self._seen_count: int = 0
283 self.register_load_state_dict_post_hook(_sync_seen_count)
285 precision = torch.eye(num_random_features) * self.ridge_penalty
286 self.register_buffer("precision", precision)
288 self.recompute_covariance = True
289 self.register_buffer("covariance", torch.eye(num_random_features))
290 self.training_parameters_set = False
292 def jl(self, x: torch.Tensor) -> torch.Tensor:
293 """
294 Project features onto the GP feature space.
296 Parameters
297 ----------
298 x : torch.Tensor
299 The feature-extractor output.
301 Returns
302 -------
303 torch.Tensor
304 The projected features, or ``x`` unchanged when no
305 projection was built.
306 """
307 if self._has_projection:
308 return torch.nn.functional.linear(x, self.random_matrix)
309 return x
311 def reset_precision_matrix(self) -> None:
312 """
313 Reset the precision matrix to the identity matrix times the ridge penalty.
314 """
315 identity = torch.eye(self.precision.shape[0], device=self.precision.device)
316 self.precision: torch.Tensor = identity * self.ridge_penalty
317 self.seen_data: torch.Tensor = torch.tensor(0, device=self.precision.device)
318 self._seen_count = 0
319 self.recompute_covariance = True
321 @icontract.require(lambda num_data: num_data > 0)
322 @icontract.require(
323 lambda num_data, batch_size: (0 < batch_size) & (batch_size <= num_data)
324 )
325 def set_training_params(self, num_data: int, batch_size: int) -> None:
326 """
327 Set the training parameters for the Laplace approximation.
329 Parameters
330 ----------
331 num_data : int
332 The total number of data points.
333 batch_size : int
334 The batch size to use during training.
335 """
336 self.num_data: int = num_data
337 self.train_batch_size: int = batch_size
338 self.training_parameters_set: bool = True
340 @icontract.require(lambda mean_field_factor: mean_field_factor is not None)
341 def mean_field_logits(
342 self, logits: torch.Tensor, pred_var: torch.Tensor, mean_field_factor: float
343 ) -> torch.Tensor:
344 """
345 Compute the mean-field logits for the Gaussian-Softmax approximation.
347 Parameters
348 ----------
349 logits : torch.Tensor
350 The logits tensor of shape (batch_size, num_outputs).
351 pred_var : torch.Tensor
352 The predictive variance of each example, of shape (batch_size,): the
353 diagonal of the predictive covariance matrix.
354 mean_field_factor : float
355 Diagonal scaling factor
357 Returns
358 -------
359 torch.Tensor
360 The mean-field logits tensor of shape (batch_size, num_outputs).
361 """
362 # Mean-Field approximation as alternative to MC integration of Gaussian-Softmax
363 # Based on: https://arxiv.org/abs/2006.07584
365 logits_scale = torch.sqrt(1.0 + pred_var * mean_field_factor)
366 if mean_field_factor > 0: 366 ↛ 369line 366 didn't jump to line 369 because the condition on line 366 was always true
367 logits = logits / logits_scale.unsqueeze(-1)
369 return logits
371 def forward(
372 self, x: torch.Tensor
373 ) -> torch.Tensor | tuple[torch.Tensor, torch.Tensor]:
374 """
375 Compute the forward pass of the Laplace approximation to the Gaussian Process.
377 Requires ``set_training_params`` to have been called.
379 Parameters
380 ----------
381 x : torch.Tensor
382 The input tensor of shape (batch_size, num_features).
384 Returns
385 -------
386 torch.Tensor | tuple[torch.Tensor, torch.Tensor]
387 The logits of shape (batch_size, num_outputs). In training mode
388 they are the raw GP mean; in evaluation mode they are mean-field
389 adjusted with the predictive covariance when ``mean_field_factor``
390 is set (always, in equine). Only when ``mean_field_factor`` is
391 ``None`` does evaluation mode return the tuple ``(mean, pred_cov)``
392 instead, with ``pred_cov`` of shape (batch_size, batch_size).
393 """
394 return self._forward_with_features(x)[0]
396 @icontract.require(lambda self: self.training_parameters_set)
397 def _forward_with_features(
398 self, x: torch.Tensor
399 ) -> tuple[torch.Tensor | tuple[torch.Tensor, torch.Tensor], torch.Tensor]:
400 """
401 ``forward`` that also returns the random Fourier features it computed.
403 The features are the output of ``rff`` (feature_extractor -> jl -> normalize ->
404 rff), the same tensor ``EquineGP.compute_embeddings`` returns, except that a
405 single unbatched example gets a batch dimension of one here. The
406 ``training_parameters_set`` precondition is checked here, before anything is
407 computed or the precision/seen_data buffers are touched.
409 Returns
410 -------
411 tuple
412 The value ``forward(x)`` would return (the logits, or
413 ``(logits, pred_cov)`` when ``mean_field_factor`` is ``None``)
414 and the post-``rff`` features.
415 """
416 f = self.feature_extractor(x)
417 f_reduc = self.jl(f)
418 if self.normalize_gp_features: 418 ↛ 420line 418 didn't jump to line 420 because the condition on line 418 was always true
419 f_reduc = self.normalize(f_reduc)
420 if f_reduc.dim() == 1:
421 # A single unbatched example: give it a batch dimension of one.
422 f_reduc = f_reduc.unsqueeze(0)
424 k = self.rff(f_reduc)
426 pred = self.beta(k)
428 if self.training:
429 # Detached: the stored precision carries no autograd graph.
430 k_detached = k.detach()
431 precision_minibatch = k_detached.t() @ k_detached
432 self.precision += precision_minibatch
433 # Marks any covariance cached since the last reset as stale.
434 self.recompute_covariance = True
435 self.seen_data += k.shape[0]
436 self._seen_count += k.shape[0]
438 if self._seen_count > self.num_data:
439 raise RuntimeError("Did not reset precision matrix at start of epoch")
440 else:
441 if self._seen_count <= self.num_data - self.train_batch_size:
442 raise RuntimeError("Not seen sufficient data for precision matrix")
444 if self.recompute_covariance:
445 with torch.no_grad():
446 eps = 1e-7
447 jitter = eps * torch.eye(
448 self.precision.shape[1],
449 device=self.precision.device,
450 )
451 covariance = cast(torch.Tensor, self.covariance)
452 covariance.copy_(_inverse_via_cholesky(self.precision + jitter))
454 self.recompute_covariance: bool = False
456 if self.mean_field_factor is None:
457 with torch.no_grad():
458 pred_cov = k @ ((self.covariance @ k.t()) * self.ridge_penalty)
459 return (pred, pred_cov), k
460 else:
461 with torch.no_grad():
462 # The diagonal of k @ covariance @ k.T * ridge_penalty.
463 pred_var = ((k @ self.covariance) * k).sum(-1) * self.ridge_penalty
464 pred = self.mean_field_logits(pred, pred_var, self.mean_field_factor)
466 return pred, k
469_DEFAULT_NUM_RANDOM_FEATURES = 1024
471_DEVICE_TYPE_DEPRECATION = (
472 "EquineGP.device_type is deprecated and will be removed in the next release: "
473 "read EquineGP.device (a str) instead; to move the model, call "
474 "model.to(value)."
475)
478def _expected_laplace_state(settings: dict[str, Any]) -> dict[str, torch.Tensor]:
479 """
480 The ``_Laplace`` state_dict that ``EquineGP(embedding, **settings)`` builds,
481 feature extractor excluded, as meta tensors (names and shapes, no data). For a
482 ``num_classes`` of 1, which ``EquineGP`` refuses, the shapes of a one-class model.
484 Plain arithmetic mirroring ``EquineGP.__init__`` (which always builds ``_Laplace``
485 with ``num_gp_features == emb_out_dim`` and normalized GP features),
486 ``_Laplace.__init__`` and ``_RandomFourierFeatures.__init__``.
487 """
488 e, c, n = (
489 _positive_int(settings.get(name, default), f"Model file's settings[{name!r}]")
490 for name, default in (
491 ("emb_out_dim", None),
492 ("num_classes", None),
493 ("num_random_features", _DEFAULT_NUM_RANDOM_FEATURES),
494 )
495 )
496 shapes: dict[str, tuple[int, ...]] = {
497 "random_matrix": (e, e),
498 "seen_data": (),
499 "precision": (n, n),
500 "covariance": (n, n),
501 "normalize.weight": (e,),
502 "normalize.bias": (e,),
503 "rff.feature_scale": (),
504 "rff.W": (e, n),
505 "rff.b": (n,),
506 "beta.weight": (c, n),
507 "beta.bias": (c,),
508 }
509 try:
510 return {key: torch.empty(shape, device="meta") for key, shape in shapes.items()}
511 except (RuntimeError, TypeError) as err: # sizes too large to represent
512 raise ValueError(
513 "Model file's settings describe a model too large to represent; "
514 "refusing to load."
515 ) from err
518# -------------------------------------------------------------------------------
519# EquineGP, below, demonstrates how to adapt that approach in EQUINE
520@beartype
521class EquineGP(Equine):
522 """
523 An example of an EQUINE model that builds upon the approach in "Spectral Norm
524 Gaussian Processes" (SNGP). This wraps any pytorch embedding neural network and provides
525 the `forward`, `predict`, `save`, and `load` methods required by Equine.
527 Notes
528 -----
529 Although this model build upon the approach in SNGP, it does not enforce the spectral normalization
530 and ResNet architecture required for SNGP. Instead, it is a simple wrapper around
531 any pytorch embedding neural network. Your mileage may vary.
532 """
534 def __init__(
535 self,
536 embedding_model: torch.nn.Module,
537 emb_out_dim: int,
538 num_classes: int,
539 num_random_features: int = _DEFAULT_NUM_RANDOM_FEATURES,
540 init_temperature: float = 1.0,
541 device: str = "cpu",
542 feature_names: list[str] | None = None,
543 label_names: list[str] | None = None,
544 ) -> None:
545 """
546 Initialize the EquineGP model.
548 Parameters
549 ----------
550 embedding_model : torch.nn.Module
551 Neural Network feature embedding.
552 emb_out_dim : int
553 The number of deep features from the feature embedding.
554 num_classes : int
555 The number of output classes this model predicts, at least 2.
556 num_random_features : int
557 The dimension of the output of the RandomFourierFeatures operation
558 init_temperature : float, optional
559 What to use as the initial temperature (1.0 has no effect).
560 device : str, optional
561 The device to train the equine model on ('cpu', 'cuda' or 'mps';
562 defaults to cpu).
563 feature_names : list[str], optional
564 List of strings of the names of the tabular features (ex ["duration", "fiat_mean", ...])
565 label_names : list[str], optional
566 List of strings of the names of the labels (ex ["streaming", "voip", ...])
568 Raises
569 ------
570 ValueError
571 If ``emb_out_dim``, ``num_classes`` or ``num_random_features`` is
572 not a positive integer, or ``num_classes`` is 1.
573 """
574 _positive_int(emb_out_dim, "emb_out_dim")
575 _positive_int(num_classes, "num_classes")
576 if num_classes < 2:
577 raise ValueError(f"num_classes must be at least 2, got {num_classes}.")
578 _positive_int(num_random_features, "num_random_features")
579 super().__init__(
580 embedding_model,
581 device=device,
582 feature_names=feature_names,
583 label_names=label_names,
584 )
585 self.support: OrderedDict[int, torch.Tensor] = OrderedDict()
586 self.support_embeddings: OrderedDict[int, torch.Tensor] = OrderedDict()
587 self.prototypes: torch.Tensor = torch.Tensor()
588 self.num_deep_features = emb_out_dim
589 self.num_gp_features = emb_out_dim
590 self.normalize_gp_features = True
591 self.num_random_features = num_random_features
592 self.num_outputs = num_classes
593 self.mean_field_factor = 25
594 self.ridge_penalty = 1
595 self.feature_scale: float = 2.0
596 self.init_temperature = init_temperature
597 self.register_buffer(
598 "temperature", torch.Tensor(self.init_temperature * torch.ones(1))
599 )
600 self.model: _Laplace = _Laplace(
601 self.embedding_model,
602 self.num_deep_features,
603 self.num_gp_features,
604 self.normalize_gp_features,
605 self.num_random_features,
606 self.num_outputs,
607 self.feature_scale,
608 self.mean_field_factor,
609 self.ridge_penalty,
610 )
611 # Moves the temperature buffer and the Laplace head onto the model's device.
612 self.to(self.device)
614 @property
615 def device_type(self) -> str:
616 """Deprecated alias of ``device``."""
617 warnings.warn(
618 _DEVICE_TYPE_DEPRECATION,
619 DeprecationWarning,
620 # Past the beartype wrapper (none under -O), to the caller's line.
621 stacklevel=2 + (0 if sys.flags.optimize else 1),
622 )
623 return self.device
625 @device_type.setter
626 def device_type(self, value: str) -> None:
627 """
628 Deprecated: moves the model with ``model.to(value)``, then assigns ``device``.
629 """
630 warnings.warn(
631 _DEVICE_TYPE_DEPRECATION,
632 DeprecationWarning,
633 # Past nn.Module.__setattr__ and the beartype wrapper (none under -O).
634 stacklevel=3 + (0 if sys.flags.optimize else 1),
635 )
636 # The module moves before ``device`` changes.
637 self.to(value)
638 self.device = value
640 def train_model(
641 self,
642 dataset: Dataset[Any],
643 loss_fn: Callable,
644 opt: torch.optim.Optimizer,
645 num_epochs: int,
646 scheduler: torch.optim.lr_scheduler.LRScheduler | None = None,
647 batch_size: int = 64,
648 validation_dataset: Dataset[Any] | None = None,
649 val_metrics: Iterable[Metric] | None = None,
650 vis_support: bool = False,
651 support_size: int = 25,
652 ) -> dict[str, Any]:
653 """
654 Train or fine-tune an EquineGP model.
656 Parameters
657 ----------
658 dataset : Dataset
659 The training data. ``dataset[:]`` must return the ``(inputs, labels)``
660 tensors, as it does for a ``TensorDataset``, a ``Subset`` of one or a
661 part returned by ``random_split``. ``vis_support=True`` needs a
662 ``TensorDataset`` (``dataset.tensors``).
663 loss_fn : Callable
664 A pytorch loss function, e.g., torch.nn.CrossEntropyLoss().
665 opt : torch.optim.Optimizer
666 A pytorch optimizer, e.g., torch.optim.Adam().
667 num_epochs : int
668 The desired number of epochs to use for training.
669 scheduler : torch.optim.lr_scheduler.LRScheduler, optional
670 A pytorch scheduler, stepped once after each epoch's training pass.
671 validation_dataset: Dataset
672 If provided, will compute validation metrics on this dataset after each epoch of training
673 val_metrics : Iterable[Metric], optional
674 torchmetrics metrics computed on ``validation_dataset`` after each
675 epoch. Each one is moved to this model's device in place and reset
676 before each epoch's validation pass.
677 batch_size : int, optional
678 The number of samples to use per batch.
679 vis_support : bool, optional
680 If True, calls ``update_support`` with the training tensors after the
681 last epoch. Requires a ``TensorDataset``.
682 support_size : int, optional
683 Maximum number of support examples per class that ``update_support``
684 keeps when ``vis_support`` is True.
686 Returns
687 -------
688 dict[str, Any]
689 ``{"train_summary": ...}`` (the dict ``generate_train_summary``
690 builds, also stored on ``self.train_summary``) plus, when a
691 ``validation_dataset`` was given, ``"val_metrics"``: one list per
692 metric in ``val_metrics`` holding what its ``compute()`` returned
693 after each epoch, usually a tensor (``None`` when ``val_metrics``
694 was not given). The entry for epoch ``n`` covers that epoch's
695 validation pass only.
697 Notes
698 -----
699 Training and eval mode are toggled on this wrapper, which propagates to the
700 inner module. The model is left in eval mode afterwards, ready to predict.
701 """
703 self.validate_feature_label_names(dataset[0][0].shape[-1], self.num_outputs)
705 train_loader = DataLoader(
706 dataset, batch_size=batch_size, shuffle=True, drop_last=False
707 )
709 val_loader: DataLoader | None = None
710 if validation_dataset is not None:
711 val_loader = DataLoader(
712 validation_dataset,
713 batch_size=batch_size,
714 shuffle=False,
715 drop_last=False,
716 )
718 self.model.set_training_params(len(cast(Sized, dataset)), batch_size)
719 val_metrics_outputs: list[list[Any]] | None = None
721 if validation_dataset is not None and val_metrics is not None:
722 val_metrics = list(val_metrics)
723 for metric in val_metrics:
724 metric.to(self.device)
725 val_metrics_outputs = [[] for _ in val_metrics]
727 for _ in tqdm(range(num_epochs)):
728 self.train() # wrapper and inner module together
729 self.model.reset_precision_matrix()
730 epoch_loss = 0.0
731 for i, (xs, labels) in enumerate(train_loader):
732 opt.zero_grad()
733 xs = self._input_to_model(xs)
734 labels = labels.to(self.device)
735 yhats = self.model(xs)
736 loss = loss_fn(yhats, labels.to(torch.long))
737 loss.backward()
738 opt.step()
739 epoch_loss += loss.item()
740 if scheduler is not None:
741 scheduler.step()
742 self.eval()
743 # compute the validation metrics
744 if (
745 validation_dataset is not None
746 and val_loader is not None
747 and val_metrics is not None
748 and val_metrics_outputs is not None
749 ):
750 for metric in val_metrics:
751 metric.reset()
752 for _, (xs_val, labels_val) in enumerate(val_loader):
753 xs_val = self._input_to_model(xs_val)
754 labels_val = labels_val.to(self.device)
755 yhats_val = self.model(xs_val)
756 for metric in val_metrics:
757 metric.update(yhats_val, labels_val)
758 for i, metric in enumerate(val_metrics):
759 val_metrics_outputs[i].append(metric.compute())
760 if vis_support:
761 tensors = cast(TensorDataset, dataset).tensors
762 self.update_support(tensors[0], tensors[1], support_size=support_size)
764 _, train_y = dataset[:]
765 date_trained = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
766 self.train_summary: dict[str, Any] = generate_train_summary(
767 self, train_y, date_trained
768 )
770 return_dict: dict[str, Any] = dict()
771 return_dict["train_summary"] = self.train_summary
772 if validation_dataset is not None:
773 return_dict["val_metrics"] = val_metrics_outputs
775 return return_dict
777 def update_support(
778 self,
779 support_x: torch.Tensor,
780 support_y: torch.Tensor,
781 *args: Any,
782 support_size: int | None = None,
783 ) -> None:
784 """Replace the support with up to ``support_size`` examples of each class,
785 and store their embeddings and the class prototypes.
787 Computes in eval mode and leaves the model in the mode the caller had it in (via
788 ``train()``/``eval()``).
790 Parameters
791 ----------
792 support_x : torch.Tensor
793 Tensor containing the examples to take the support from.
794 support_y : torch.Tensor
795 Tensor containing the label of each example in ``support_x``.
796 *args : Any
797 Deprecated: ``support_size`` passed by position. Emits a
798 ``DeprecationWarning`` and is then handled as the keyword.
799 support_size : int
800 Maximum number of support examples to keep per class. Required,
801 keyword-only.
803 Returns
804 -------
805 None
807 Raises
808 ------
809 TypeError
810 If ``support_size`` is missing, is passed both by position and by
811 keyword, or more than one option is passed by position.
812 ValueError
813 If ``support_x`` and ``support_y`` hold different numbers of examples.
814 """
815 if len(args) > 1:
816 raise TypeError(
817 "EquineGP.update_support() takes at most 1 option by position "
818 f"(support_size) but {len(args)} were given"
819 )
820 if args:
821 if support_size is not None:
822 raise TypeError(
823 "EquineGP.update_support() got multiple values for argument "
824 "'support_size'"
825 )
826 warnings.warn(
827 "Passing support_size to EquineGP.update_support by position is "
828 "deprecated and will stop working in the next release: pass "
829 "support_size=... by keyword.",
830 DeprecationWarning,
831 # Past the beartype wrapper (none under -O), to the caller's line.
832 stacklevel=2 + (0 if sys.flags.optimize else 1),
833 )
834 EquineGP.update_support(self, support_x, support_y, support_size=args[0])
835 return
836 if support_size is None:
837 raise TypeError(
838 "EquineGP.update_support() missing required keyword argument: "
839 "'support_size'"
840 )
841 with _eval_mode(self):
842 if support_x.shape[0] != support_y.shape[0]:
843 raise ValueError(
844 f"support_x has {support_x.shape[0]} examples but support_y has "
845 f"{support_y.shape[0]} labels; they must match."
846 )
847 labels, counts = torch.unique(support_y, return_counts=True)
848 shuffled_idxs = _get_shuffle_idxs_by_class(support_y, labels.tolist())
849 support = OrderedDict()
850 for label, count in list(zip(labels.tolist(), counts.tolist())):
851 class_support = generate_support(
852 support_x,
853 support_y,
854 support_size=min(count, support_size),
855 selected_labels=[label],
856 shuffled_indexes={label: shuffled_idxs[label]},
857 )
858 support.update(class_support)
860 # Through the model boundary: on the device and, for floating support, in
861 # the model's dtype.
862 self.support = OrderedDict(
863 (label, self._input_to_model(x)) for label, x in support.items()
864 )
866 # Embedded without autograd: the result carries no graph.
867 with torch.no_grad():
868 support_embeddings = OrderedDict().fromkeys(
869 self.support.keys(), torch.Tensor()
870 )
871 for label in self.support:
872 support_embeddings[label] = self.compute_embeddings(
873 self.support[label]
874 )
876 self.support_embeddings = support_embeddings
877 self.prototypes = self._prototypes_from_embeddings()
879 def compute_embeddings(self, x: torch.Tensor) -> torch.Tensor:
880 """
881 Method for computing deep embeddings for given input tensor.
883 Parameters
884 ----------
885 x : torch.Tensor
886 Input tensor for generating embeddings.
888 Returns
889 -------
890 torch.Tensor
891 Output embeddings .
892 """
893 x = self._input_to_model(x)
894 f = self.model.feature_extractor(x)
895 f_reduc = self.model.jl(f)
896 if self.model.normalize_gp_features: 896 ↛ 899line 896 didn't jump to line 899 because the condition on line 896 was always true
897 f_reduc = self.model.normalize(f_reduc)
899 return self.model.rff(f_reduc)
901 @icontract.require(lambda self: len(self.support) > 0)
902 def compute_prototypes(self) -> torch.Tensor:
903 """
904 Method for computing class prototypes based on given support examples.
905 ``Prototypes'' in this context are the means of the support embeddings for each class.
907 Embeds ``self.support`` with the current model (one pass per class)
908 and returns the mean of each class's embeddings, in support order.
909 Nothing is stored: ``support_embeddings`` and ``prototypes`` are left
910 as they are.
912 Returns
913 -------
914 torch.Tensor
915 Tensors of prototypes for each of the given classes in the support.
916 """
917 embeddings = [self.compute_embeddings(x) for x in self.support.values()]
918 return torch.stack([torch.mean(e, dim=0) for e in embeddings])
920 @icontract.require(lambda self: len(self.support_embeddings) > 0)
921 def _prototypes_from_embeddings(self) -> torch.Tensor:
922 """Mean of ``self.support_embeddings`` per class, in support order; embeds nothing."""
923 proto_list = []
924 for label in self.support_embeddings: # look at doing functorch
925 class_prototype = torch.mean(self.support_embeddings[label], dim=0)
926 proto_list.append(class_prototype)
928 prototypes = torch.stack(proto_list)
930 return prototypes
932 @icontract.require(lambda self: len(self.support) > 0)
933 def get_support(self) -> OrderedDict[int, torch.Tensor]:
934 """
935 Method for returning support examples used in training.
937 Returns
938 -------
939 OrderedDict[int, torch.Tensor]
940 Dictionary containing support examples for each class.
941 """
942 return self.support
944 @icontract.require(lambda self: len(self.prototypes) > 0)
945 def get_prototypes(self) -> torch.Tensor:
946 """
947 Method for returning class prototypes.
949 Returns
950 -------
951 torch.Tensor
952 Tensors of prototypes for each of the given classes in the support.
953 """
954 return self.prototypes
956 @icontract.require(lambda num_calibration_epochs: 0 < num_calibration_epochs)
957 @icontract.require(lambda calibration_lr: calibration_lr > 0.0)
958 def calibrate_model(
959 self,
960 dataset: Dataset[Any],
961 num_calibration_epochs: int = 1,
962 calibration_lr: float = 0.01,
963 calibration_batch_size: int = 256,
964 ) -> None:
965 """
966 Fine-tune the temperature on ``dataset``.
968 ``train_model`` does not call this method; ``temperature`` stays at
969 ``init_temperature`` until it is called.
971 Parameters
972 ----------
973 dataset : Dataset
974 A map-style pytorch ``Dataset`` (with ``__len__``) of
975 ``(input, label)`` pairs.
976 num_calibration_epochs : int, optional
977 Number of epochs to tune temperature.
978 calibration_lr : float, optional
979 Learning rate for temperature optimization.
980 calibration_batch_size : int, optional
981 Batch size of the calibration data loader.
982 """
984 calibration_loader = DataLoader(
985 dataset,
986 batch_size=calibration_batch_size,
987 shuffle=True,
988 drop_last=False,
989 )
991 temperature = cast(torch.Tensor, self.temperature)
992 temperature.requires_grad = True
993 loss_fn = torch.nn.functional.cross_entropy
994 optimizer = torch.optim.Adam([temperature], lr=calibration_lr)
995 for _ in range(num_calibration_epochs):
996 for xs, labels in calibration_loader:
997 optimizer.zero_grad()
998 xs = self._input_to_model(xs)
999 labels = labels.to(self.device)
1000 with torch.no_grad():
1001 logits = self.model(xs)
1002 logits = logits / temperature
1003 loss = loss_fn(logits, labels.to(torch.long))
1004 loss.backward()
1005 optimizer.step()
1006 temperature.requires_grad = False
1008 def _input_to_model(self, X: torch.Tensor) -> torch.Tensor:
1009 """
1010 Move ``X`` to the model device; a floating input is cast to the model's dtype.
1012 The reference is the Laplace head (``self.model``, see
1013 ``utils._input_to_model``): its first parameter is the embedding
1014 model's when that has one, else the head's own (``normalize.weight`` or
1015 ``beta``). A parameter-less embedding such as ``nn.Identity`` gets an input in
1016 the head's dtype.
1017 """
1018 return _input_to_model(X, self.model, self.device)
1020 def forward(self, X: torch.Tensor) -> torch.Tensor:
1021 """
1022 EquineGP forward function, generates logits for classification.
1024 Parameters
1025 ----------
1026 X : torch.Tensor
1027 Input tensor for generating predictions. Moved to the model device
1028 and cast to the embedding model's parameter dtype.
1030 Returns
1031 -------
1032 torch.Tensor
1033 Logits divided by ``temperature``, shape (examples, classes).
1034 """
1035 logits, _ = self._forward_with_embeddings(X)
1036 return logits
1038 def _forward_with_embeddings(
1039 self, X: torch.Tensor
1040 ) -> tuple[torch.Tensor, torch.Tensor]:
1041 """
1042 ``forward`` that also returns its embeddings.
1044 The embeddings are ``compute_embeddings(X)``, with a single unbatched
1045 example given a batch dimension of one.
1046 """
1047 X = self._input_to_model(X)
1048 logits, embeddings = self.model._forward_with_features(X)
1049 logits = cast(torch.Tensor, logits) # mean_field_factor is always set
1050 temperature = cast(torch.Tensor, self.temperature) # registered buffer
1051 return logits / temperature, embeddings
1053 @icontract.ensure(
1054 lambda result: all((0 <= result.ood_scores) & (result.ood_scores <= 1.0))
1055 )
1056 def predict(self, X: torch.Tensor) -> EquineOutput:
1057 """
1058 Predict function for EquineGP, inherited and implemented from Equine.
1060 Computes in eval mode and leaves the model in the mode the caller had it in (via
1061 ``train()``/``eval()``). Every submodule's mode is restored; an embedding frozen
1062 with ``model.embedding_model.eval()`` during fine-tuning stays frozen.
1064 Parameters
1065 ----------
1066 X : torch.Tensor
1067 Input tensor. It is moved to the model device and cast to the embedding
1068 model's parameter dtype; a float64 input to a float32 model is accepted.
1070 Returns
1071 -------
1072 EquineOutput
1073 Output object containing prediction probabilities, OOD scores and
1074 embeddings. Computed under ``torch.no_grad()``: the tensors carry
1075 no autograd graph but are ordinary tensors (not inference-mode
1076 tensors), which a caller can use in autograd.
1078 Raises
1079 ------
1080 ValueError
1081 If ``X`` is empty, or its embeddings hold a NaN or infinite value.
1082 """
1083 _require_examples(X)
1084 # One embedding pass, under no_grad.
1085 with _eval_mode(self), torch.no_grad():
1086 logits, embeddings = self._forward_with_embeddings(X)
1087 _require_finite_embeddings(embeddings)
1088 preds = torch.softmax(logits, dim=1)
1089 equiprobable = (
1090 torch.ones(self.num_outputs, device=logits.device) / self.num_outputs
1091 )
1092 max_entropy = torch.sum(torch.special.entr(equiprobable))
1093 ood_score = torch.sum(torch.special.entr(preds), dim=1) / max_entropy
1094 eq_out = EquineOutput(
1095 classes=preds, ood_scores=ood_score, embeddings=embeddings
1096 )
1098 self.validate_feature_label_names(X.shape[-1], self.num_outputs)
1100 return eq_out
1102 def save(self, path: str) -> None:
1103 """
1104 Save all model parameters to a file.
1106 The embedding model (the feature extractor) is stored as a *recipe*
1107 (registered architecture name plus constructor arguments) and a
1108 ``state_dict``, so the file holds only data.
1110 Parameters
1111 ----------
1112 path : str
1113 Filename to write the model.
1115 Raises
1116 ------
1117 ValueError
1118 If the embedding model is not a registered architecture.
1119 RuntimeError
1120 If the model has not been trained with ``train_model``.
1121 """
1122 if self.model.num_data == 0:
1123 raise RuntimeError(
1124 "The model has not been trained; call train_model before save."
1125 )
1126 torch.save(self._to_checkpoint(), path)
1128 def _to_checkpoint(self) -> dict[str, Any]:
1129 """Build the checkpoint dictionary that ``save`` writes and ``_from_checkpoint`` reads."""
1130 model_settings = {
1131 "emb_out_dim": self.num_deep_features,
1132 "num_classes": self.num_outputs,
1133 "num_random_features": self.num_random_features,
1134 "init_temperature": cast(torch.Tensor, self.temperature).item(),
1135 "device": self.device,
1136 }
1137 # The feature extractor is the embedding model, stored separately.
1138 laplace_sd = {
1139 key: value
1140 for key, value in self.model.state_dict().items()
1141 if "feature_extractor" not in key
1142 }
1143 # Plain values only, so load_checkpoint can read it with weights_only=True.
1144 save_data: dict[str, Any] = {
1145 "equine_format_version": EQUINE_FORMAT_VERSION,
1146 **_embedding_checkpoint(self.embedding_model),
1147 "feature_names": _plain_names(self.feature_names),
1148 "label_names": _plain_names(self.label_names),
1149 "laplace_model_save": laplace_sd,
1150 "num_data": self.model.num_data,
1151 "settings": model_settings,
1152 "support": {
1153 int(label): x.detach().clone() for label, x in self.support.items()
1154 },
1155 "train_batch_size": self.model.train_batch_size,
1156 "train_summary": _plain_train_summary(self.train_summary),
1157 }
1158 return save_data
1160 @classmethod
1161 def load(
1162 cls,
1163 path: str,
1164 device: str | None = None,
1165 *,
1166 embedding_model: torch.nn.Module | None = None,
1167 ) -> Self:
1168 """
1169 Load a previously saved EquineGP model.
1171 Loading runs no code from the file: it is read with
1172 ``torch.load(weights_only=True)`` and the embedding model is rebuilt from its
1173 recipe through the architecture registry.
1175 Parameters
1176 ----------
1177 path : str
1178 Input filename.
1179 device : str | None
1180 The device to load the model onto. Overrides the device recorded
1181 in the file; by default the model lands on the saved device.
1182 embedding_model : torch.nn.Module | None
1183 Keyword-only. Use this module as the embedding architecture instead
1184 of rebuilding it from the file's recipe; the file's weights are
1185 loaded into it, and its floating-point tensors take their stored
1186 dtypes.
1188 Returns
1189 -------
1190 EquineGP
1191 The reconstituted EquineGP object.
1193 Raises
1194 ------
1195 ValueError
1196 If the file is not in the current EQUINE format or stores its
1197 embedding model as TorchScript (both are rewritten once with
1198 ``python -m equine.upgrade``), or names an unregistered
1199 architecture. If ``device`` is unavailable here, names an index at
1200 or above its device count, or lacks a dtype the file holds (float64
1201 on MPS: load such a file with ``device="cpu"``). If the file's
1202 ``num_classes`` is 1.
1203 """
1204 model_save = _load_checkpoint_for_device(path, device)
1205 _refuse_torchscript(model_save, path)
1206 return cls._from_checkpoint(model_save, device, embedding_model=embedding_model)
1208 @classmethod
1209 def _from_checkpoint(
1210 cls,
1211 model_save: dict[str, Any],
1212 device: str | None = None,
1213 embedding_model: torch.nn.Module | None = None,
1214 ) -> Self:
1215 """
1216 Rebuild an EquineGP from an already-loaded checkpoint dictionary.
1218 Parameters
1219 ----------
1220 model_save : dict[str, Any]
1221 The dictionary returned by ``utils.load_checkpoint``.
1222 device : str | None
1223 Device override for the reconstituted model.
1224 embedding_model : torch.nn.Module | None
1225 Use this module as the embedding architecture instead of the file's
1226 recipe; the file's weights are loaded into it, and its
1227 floating-point tensors take their stored dtypes.
1229 Returns
1230 -------
1231 EquineGP
1232 The reconstituted EquineGP object.
1233 """
1234 # The embedding is rebuilt first.
1235 embedding = _rebuild_embedding(model_save, embedding_model)
1236 _require_entries(
1237 model_save,
1238 (
1239 "settings",
1240 "support",
1241 "train_summary",
1242 "laplace_model_save",
1243 "num_data",
1244 "train_batch_size",
1245 ),
1246 cls,
1247 )
1248 stored_support = _support_from_file(model_save["support"])
1249 num_data = _positive_int(model_save["num_data"], "Model file's num_data")
1250 batch_size = _positive_int(
1251 model_save["train_batch_size"], "Model file's train_batch_size"
1252 )
1253 if batch_size > num_data:
1254 raise ValueError(
1255 "Model file's train_batch_size is larger than its num_data; the file "
1256 "is inconsistent or was tampered with."
1257 )
1258 for key in ("feature_names", "label_names"):
1259 _require_names(model_save.get(key), key)
1260 settings = _checked_settings(cls, model_save["settings"])
1261 # Allow the user to override the saved device state dynamically
1262 if device is not None:
1263 settings["device"] = device
1264 else:
1265 _require_device(settings, hint=" (pass device= to choose another)")
1266 # The stored Laplace weights are checked against the settings before the model
1267 # is built.
1268 _require_matching_weights(
1269 _expected_laplace_state(settings),
1270 model_save.get("laplace_model_save"),
1271 "laplace_model_save",
1272 )
1273 try:
1274 eq_model = cls(embedding, **settings)
1275 except Exception as err:
1276 raise ValueError(
1277 f"Could not build {cls.__name__} from the model file's settings "
1278 f"({_truncate(_describe_error(err), 200)})."
1279 ) from err
1281 eq_model.feature_names = model_save.get("feature_names")
1282 eq_model.label_names = model_save.get("label_names")
1283 eq_model.train_summary = cast(dict[str, Any], model_save.get("train_summary"))
1285 _adopt_stored_dtypes(
1286 eq_model.model, model_save["laplace_model_save"], "laplace_model_save"
1287 )
1288 laplace_save = cast(dict[str, Any], model_save.get("laplace_model_save"))
1289 eq_model.model.load_state_dict(laplace_save, strict=False)
1290 # The load_state_dict post hook has already updated _seen_count.
1291 eq_model.model.seen_data = cast(torch.Tensor, laplace_save.get("seen_data")).to(
1292 eq_model.model.precision.device
1293 )
1295 eq_model.model.set_training_params(num_data, batch_size)
1296 eq_model.eval()
1298 # load_checkpoint returns CPU tensors; the support goes to the model's device.
1299 try:
1300 support = OrderedDict(
1301 (label, x.to(eq_model.device)) for label, x in stored_support.items()
1302 )
1303 if len(support) > 0:
1304 eq_model.support = support
1305 with torch.no_grad():
1306 eq_model.support_embeddings = OrderedDict(
1307 (label, eq_model.compute_embeddings(x))
1308 for label, x in support.items()
1309 )
1310 eq_model.prototypes = eq_model._prototypes_from_embeddings()
1311 except Exception as err:
1312 raise ValueError(
1313 "Model file's support could not be passed through its embedding "
1314 f"model ({_truncate(_describe_error(err), 200)}); the "
1315 "file is inconsistent or was tampered with."
1316 ) from err
1318 return eq_model