Coverage for /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/equine/utils.py: 99%
774 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 copy
6import inspect
7import io
8import itertools
9import math
10import os
11import pickle
12import sys
13import warnings
14import zipfile
15from collections import OrderedDict
16from collections.abc import Mapping
17from typing import Any
19import icontract
20import torch
21from beartype import beartype
22from scipy.stats import gaussian_kde
23from torch import _weights_only_unpickler
24from torchmetrics.classification import (
25 MulticlassAccuracy,
26 MulticlassCalibrationError,
27 MulticlassConfusionMatrix,
28 MulticlassF1Score,
29)
31from .equine import Equine
32from .equine_output import EquineOutput
33from .registry import (
34 _check_plain,
35 _describe_error,
36 _message_or_type,
37 _truncate,
38 build_from_recipe,
39 embedding_recipe,
40)
42# Layout version written by ``save``. Versions 2 and 3 hold only tensors,
43# containers and plain scalars/strings, so ``torch.load(weights_only=True)``
44# reads them. The embedding is a recipe plus a state_dict (see
45# ``equine.registry``). ``EquineProtonet.save`` writes the ``ood_distance``
46# setting; a Protonet file without it (every version 2 file, and the files
47# ``equine.upgrade`` writes) loads as ``"rmd_sqrt"``.
48EQUINE_FORMAT_VERSION = 3
50# Values of the ``EquineProtonet`` setting ``ood_distance``.
51_OOD_DISTANCES = ("rmd_sq", "rmd_sqrt")
53_UPGRADE_HINT = "python -m equine.upgrade"
55_UPGRADE_USAGE = (
56 f"`{_UPGRADE_HINT} {{path}} --recipe '<recipe JSON>' [--import MODULE]`, or "
57 "`from equine.upgrade import upgrade_model_file; upgrade_model_file({path!r}, "
58 "<an instance of your registered architecture>)`"
59)
61_TORCHSCRIPT_FILE_ERROR = (
62 "'{path}' stores its embedding model as TorchScript, which EQUINE does not "
63 "load. Rewrite it once with "
64 + _UPGRADE_USAGE
65 + ". Only upgrade files you trust: loading TorchScript runs code from the file."
66)
68_TORCHSCRIPT_CHECKPOINT_ERROR = (
69 "Model file stores its embedding model as TorchScript, which EQUINE does not "
70 f"load. Rewrite it once with `{_UPGRADE_HINT}`. Only upgrade files you trust: "
71 "loading TorchScript runs code from the file."
72)
74_LEGACY_FILE_ERROR = (
75 "'{path}' is not in the current EQUINE model format: it has no "
76 "equine_format_version, or it holds pickled Python objects, as files saved "
77 "by earlier EQUINE releases do. Rewrite it once with "
78 + _UPGRADE_USAGE
79 + ". Only upgrade files you trust: the upgrade unpickles the file "
80 "without restrictions, which can run code embedded in it."
81)
84class LegacyFormatError(ValueError):
85 """The file predates the current format; ``python -m equine.upgrade`` rewrites it."""
88# torch < 2.6 has a known bypass of weights_only=True (CVE-2025-32434).
89_MIN_SAFE_TORCH = (2, 6)
91_OLD_TORCH_ERROR = (
92 "EQUINE needs torch >= 2.6 to read model files (installed: {version}): "
93 "torch.load(weights_only=True) has a known bypass on earlier releases "
94 "(CVE-2025-32434)."
95)
98_STORAGE_TRICK_ERROR = (
99 "Model file contains a tensor whose storage is smaller than its shape "
100 "(expanded or overlapping view); refusing to load."
101)
103_NOT_PLAIN_ARCHIVE_ERROR = (
104 "Model file is not a plain (uncompressed) PyTorch archive; refusing to load."
105)
107_PICKLE_CALL_ERROR = (
108 "Model file's pickle uses {name}, which EQUINE model files do not contain; "
109 "refusing to load."
110)
112_PICKLE_SIZE_ERROR = (
113 "Model file's pickle copies more items than it has bytes; refusing to load."
114)
116_PICKLE_STORAGE_CALL_ERROR = (
117 "Model file's pickle calls {name}, which EQUINE model files only reference as a "
118 "tensor's storage; refusing to load."
119)
121# Functions, storage classes and dtypes a model file's pickle may name.
122_PICKLE_FUNCTIONS = frozenset(
123 {
124 "torch._utils._rebuild_tensor_v2",
125 "torch._utils._rebuild_tensor_v3",
126 "torch._utils._rebuild_parameter",
127 }
128)
129_PICKLE_STORAGE_CLASSES = frozenset(
130 f"torch.{kind}Storage"
131 for kind in (
132 "Float",
133 "Double",
134 "Half",
135 "BFloat16",
136 "Long",
137 "Int",
138 "Short",
139 "Char",
140 "Byte",
141 "Bool",
142 "ComplexFloat",
143 "ComplexDouble",
144 )
145) | {"torch.storage.UntypedStorage"}
146_PICKLE_DTYPES = {
147 f"torch.{name}": value
148 for name, value in vars(torch).items()
149 if isinstance(value, torch.dtype)
150}
152# torch.load reads a file as a zip archive exactly when it starts with this
153# local-file-header signature (torch.serialization._is_zipfile).
154_ZIP_SIGNATURE = b"PK\x03\x04"
156_NO_STORAGE_ERROR = (
157 "Model file contains a sparse or meta tensor, which has no dense storage "
158 "backing its shape; refusing to load."
159)
161_STORAGE_SIZE_ERROR = (
162 "Model file declares tensor storage larger than the data it contains; "
163 "refusing to load."
164)
166_ALIASED_SUPPORT_ERROR = (
167 "Model file's support/KDE tensors alias one another, which lets a small file "
168 "multiply the memory and work of loading it; refusing to load. The current "
169 f"format stores each label's data separately; `{_UPGRADE_HINT}` rewrites a "
170 "trusted file from an earlier release with the tensors copied apart."
171)
173_SET_ERROR = "Model file contains a set; EQUINE files never do; refusing to load."
176def _torch_version() -> tuple[int, int]:
177 """Return the installed torch version as an ``(major, minor)`` tuple."""
178 major, minor = (int(p) for p in torch.__version__.split("+")[0].split(".")[:2])
179 return (major, minor)
182def _warn_if_torch_crashes_with_threads() -> None:
183 """
184 Warn on macOS with Python 3.15 or later and torch older than 2.15, where
185 torch can crash when it runs on several threads at once.
186 """
187 if (
188 sys.platform == "darwin"
189 and sys.version_info >= (3, 15)
190 and _torch_version() < (2, 15)
191 ):
192 warnings.warn(
193 f"torch {torch.__version__} can crash on macOS with Python 3.15 when "
194 "torch runs on several threads at once (for example, two threads "
195 "calling predict). Install torch >= 2.15; until it is on PyPI: "
196 "pip install --upgrade 'torch>=2.15' "
197 "--index-url https://download.pytorch.org/whl/test/cpu",
198 RuntimeWarning,
199 stacklevel=3,
200 )
203def load_checkpoint(path: str, map_location: str | None = None) -> dict[str, Any]:
204 """
205 Read a saved EQUINE model file with ``torch.load(weights_only=True)``.
207 Files from earlier releases hold pickled Python objects and are refused;
208 ``python -m equine.upgrade`` rewrites them in the current format.
210 Memory is bounded by the bytes present in the file. The file must be a plain zip
211 archive (see ``_check_zip_archive``) whose pickle names only what ``save`` writes
212 (see ``_check_pickle_globals``), and is mapped with ``mmap=True``; each storage is a
213 slice of the file. Expanded or overlapping views, meta and sparse tensors, and
214 support/KDE tensors that alias one another are refused. Every storage is then
215 copied once off the mapping, onto ``map_location``.
217 The file contains no executable code: the embedding model is stored as a recipe and
218 weights.
220 Parameters
221 ----------
222 path : str
223 Filename of the saved model.
224 map_location : str | None
225 Device to move the loaded tensors to; with None they stay on the CPU,
226 whatever device they were saved from. It must name the CPU or an
227 accelerator available on this machine, with an index below its device count;
228 anything else, ``meta`` included, is refused before the file is opened.
230 Returns
231 -------
232 dict[str, Any]
233 The saved checkpoint dictionary.
235 Raises
236 ------
237 ValueError
238 If ``map_location`` names a device this machine cannot build on, or an
239 accelerator without a dtype the file holds (float64 on MPS). If torch
240 is older than 2.6, if the file is not in the current format (not a zip
241 archive, pickled objects, or no ``equine_format_version``), if it
242 declares a format version this EQUINE does not know, or if its layout
243 could exhaust memory (compressed or oversized entries, a pickle global
244 ``save`` does not write, no dictionary at the top level, a set, a tensor
245 whose storage is smaller than its shape, storages that overlap in the
246 file, aliased support/KDE tensors).
247 """
248 if map_location is not None:
249 # Checked before the file is opened.
250 _require_device({"device": map_location}, what="The requested device")
251 if _torch_version() < _MIN_SAFE_TORCH:
252 raise ValueError(_OLD_TORCH_ERROR.format(version=torch.__version__))
253 if not _check_zip_archive(path):
254 raise LegacyFormatError(_LEGACY_FILE_ERROR.format(path=path))
255 _check_pickle_globals(path)
256 try:
257 # torch reopens the file; a swapped file skips the zip and pickle pre-checks.
258 checkpoint = torch.load(path, map_location="cpu", weights_only=True, mmap=True)
259 except pickle.UnpicklingError as err:
260 raise LegacyFormatError(_LEGACY_FILE_ERROR.format(path=path)) from err
261 except Exception as err: # malformed archive: report it as a ValueError
262 if "resiz" in str(err): # torch refusing a tensor larger than its storage
263 raise ValueError(_STORAGE_SIZE_ERROR) from err
264 raise ValueError(
265 f"Model file could not be read as a PyTorch archive "
266 f"({_truncate(str(err), 200)}); refusing to load."
267 ) from err
268 _require_dict(checkpoint, path)
269 _validate_format_version(checkpoint)
270 tensors = _unique_tensors(checkpoint)
271 _reject_storage_tricks(tensors)
272 _reject_overlapping_storages(tensors)
273 # Checked before the copy below.
274 if _support_is_aliased(checkpoint):
275 raise ValueError(_ALIASED_SUPPORT_ERROR)
276 if "equine_format_version" not in checkpoint:
277 raise LegacyFormatError(_LEGACY_FILE_ERROR.format(path=path))
278 if map_location is not None: 278 ↛ 279line 278 didn't jump to line 279 because the condition on line 278 was never true
279 _require_supported_dtypes(tensors, torch.device(map_location))
280 _copy_off_the_file(tensors, map_location)
281 return checkpoint
284def _load_checkpoint_for_device(path: str, device: str | None) -> dict[str, Any]:
285 """
286 ``load_checkpoint(path)`` for a model loader that builds on ``device``.
288 The tensors stay on the CPU; the loader builds the model from them and
289 moves it to ``device``. An explicit ``device`` is checked as
290 ``map_location`` is: before the file is opened, and against the dtypes
291 of the tensors the file holds.
292 """
293 if device is not None:
294 _require_device({"device": device}, what="The requested device")
295 checkpoint = load_checkpoint(path)
296 if device is not None:
297 _require_supported_dtypes(_unique_tensors(checkpoint), torch.device(device))
298 return checkpoint
301def _validate_format_version(checkpoint: Any) -> None:
302 """
303 Raise if a loaded checkpoint declares a format version newer than this
304 EQUINE build understands.
306 A missing key is reported by the caller. A present key must be an ``int``
307 (not a ``bool``); a huge one is not formatted into the message.
308 """
309 if isinstance(checkpoint, dict) and "equine_format_version" in checkpoint:
310 version = checkpoint["equine_format_version"]
311 if type(version) is not int:
312 raise ValueError(
313 "Model file's equine_format_version is malformed (expected an int; "
314 f"got {_shown(version)})."
315 )
316 if version > EQUINE_FORMAT_VERSION:
317 shown = version if version < 10**6 else "a much newer one"
318 raise ValueError(
319 f"Unsupported EQUINE model format version {shown}; this "
320 f"EQUINE supports up to {EQUINE_FORMAT_VERSION}. Upgrade EQUINE."
321 )
324def _plain_names(names: list[str] | None) -> list[str] | None:
325 """
326 ``feature_names`` / ``label_names`` as plain ``str`` for a checkpoint.
328 Names often come from numpy (``LabelEncoder.inverse_transform`` returns
329 ``numpy.str_``), which ``torch.load(weights_only=True)`` refuses to unpickle.
330 """
331 return None if names is None else [str(name) for name in names]
334def _plain_train_summary(summary: Any) -> Any:
335 """
336 Return ``summary`` after the plain-value check, accepting tensors (not quantized,
337 without Python attributes), ``torch.Size`` and ``OrderedDict`` too, and str, int,
338 float, bool and None dict keys. A refused entry raises ``ValueError``.
339 """
340 try:
341 _check_plain(
342 {"train_summary": summary},
343 allow_tensors=True,
344 what="Training summary entry",
345 owner="the model",
346 key_types=(str, int, float, bool, type(None)),
347 )
348 except TypeError as err:
349 raise ValueError(f"Cannot save: {err}") from err
350 return summary
353def _require_dict(checkpoint: Any, path: str) -> None:
354 if not isinstance(checkpoint, dict):
355 raise ValueError(
356 f"'{path}' is not an EQUINE model file (expected a dictionary at the "
357 "top level)."
358 )
361def _check_zip_archive(path: str) -> bool:
362 """
363 Refuse a zip archive that ``torch.load`` could inflate beyond the file's size.
365 DEFLATE entries are refused here, before ``torch.load`` runs, and so is an archive
366 whose entries add up to more than the file. A file that torch would read as a zip
367 but the ``zipfile`` module cannot parse is refused too.
369 Returns whether the file is a zip archive at all. The caller refuses a non-zip file
370 (torch's pre-1.6 format); ``python -m equine.upgrade`` rewrites such files.
371 """
372 with open(path, "rb") as file:
373 if file.read(len(_ZIP_SIGNATURE)) != _ZIP_SIGNATURE:
374 return False
375 try:
376 with zipfile.ZipFile(file) as archive:
377 entries = archive.infolist()
378 except Exception as err: # any parse failure of a hostile file
379 raise ValueError(_NOT_PLAIN_ARCHIVE_ERROR) from err
380 file_size = os.fstat(file.fileno()).st_size
381 compressed = any(info.compress_type != zipfile.ZIP_STORED for info in entries)
382 if compressed or sum(info.file_size for info in entries) > file_size:
383 raise ValueError(_NOT_PLAIN_ARCHIVE_ERROR)
384 return True
387class _PickleRefusal(ValueError):
388 """A global or call the dry run of a model file's pickle refuses."""
391class _Placeholder:
392 """What the dry run of a model file's pickle builds for a tensor or storage."""
395class _StorageClass:
396 """A storage class named by the pickle; only a storage reference may hold it."""
398 def __init__(self, name: str) -> None:
399 self.name = name
401 def __call__(self, *args: Any) -> None:
402 raise _PickleRefusal(_PICKLE_STORAGE_CALL_ERROR.format(name=self.name))
405def _sizes(args: tuple[Any, ...]) -> int:
406 """The number of arguments plus the lengths of those that have one."""
407 return len(args) + sum(len(arg) for arg in args if hasattr(arg, "__len__"))
410class _DryRunUnpickler(pickle._Unpickler):
411 """
412 Unpickle with placeholders for tensors and storages, refusing other globals.
414 The calls it allows and the state ``BUILD`` sets are charged their number of
415 arguments plus the lengths of those arguments; together they may use at most
416 ``budget`` items. ``NEWOBJ`` is refused.
417 """
419 dispatch = dict(pickle._Unpickler.dispatch)
420 stack: list[Any]
422 def __init__(self, file: Any, budget: int) -> None:
423 super().__init__(file)
424 self.budget = budget
426 def _spend(self, items: int) -> None:
427 self.budget -= items
428 if self.budget < 0:
429 raise _PickleRefusal(_PICKLE_SIZE_ERROR)
431 def _counted(self, build: Any) -> Any:
432 def call(*args: Any) -> Any:
433 self._spend(_sizes(args))
434 return build(*args)
436 return call
438 def _rebuild(self, source: Any, *args: Any) -> _Placeholder:
439 if not isinstance(source, _Placeholder):
440 raise _PickleRefusal(
441 _PICKLE_CALL_ERROR.format(name="a tensor without a storage")
442 )
443 self._spend(_sizes((source, *args)))
444 return _Placeholder()
446 def load_build(self) -> None:
447 state = self.stack[-1]
448 self._spend(_sizes(state if isinstance(state, tuple) else (state,)))
449 pickle._Unpickler.load_build(self) # type: ignore
451 dispatch[pickle.BUILD[0]] = load_build # type: ignore
453 def load_newobj(self) -> None:
454 raise _PickleRefusal(_PICKLE_CALL_ERROR.format(name="NEWOBJ"))
456 dispatch[pickle.NEWOBJ[0]] = load_newobj # type: ignore
458 def find_class(self, module: str, name: str) -> Any:
459 full_name = f"{module}.{name}"
460 if full_name == "collections.OrderedDict":
461 return self._counted(OrderedDict)
462 if full_name == "torch.Size":
463 return self._counted(tuple)
464 if full_name in ("__builtin__.set", "builtins.set"):
465 return self._counted(set)
466 if full_name in _PICKLE_DTYPES:
467 return _PICKLE_DTYPES[full_name]
468 if full_name in _PICKLE_FUNCTIONS:
469 return self._rebuild
470 if full_name in _PICKLE_STORAGE_CLASSES:
471 return _StorageClass(full_name)
472 raise _PickleRefusal(_PICKLE_CALL_ERROR.format(name=_truncate(full_name, 100)))
474 def persistent_load(self, pid: Any) -> _Placeholder:
475 if not (
476 type(pid) is tuple
477 and len(pid) == 5
478 and pid[0] == "storage"
479 and isinstance(pid[1], _StorageClass)
480 ):
481 raise _PickleRefusal(
482 _PICKLE_CALL_ERROR.format(name="a malformed storage reference")
483 )
484 return _Placeholder()
487def _check_pickle_globals(path: str) -> None:
488 """
489 Refuse a pickle that names a global ``save`` does not write, before ``torch.load``.
491 The pickle checked is the record ``torch.load`` reads. A global outside torch's
492 default ``weights_only`` allowlist marks a file from an earlier release
493 (``LegacyFormatError``). Of the globals torch allows, a model file may name only
494 ``OrderedDict``, ``torch.Size``, ``set``, torch dtypes, the tensor and parameter
495 rebuild functions, and the storage classes, which only a storage reference may
496 hold. The pickle is then unpickled with placeholders for tensors and storages; that
497 dry run calls no torch function, and the arguments of the calls it allows, counted
498 with their lengths, add up to at most as many items as the pickle has bytes.
499 """
500 try:
501 with (
502 open(path, "rb") as file,
503 torch.serialization._open_zipfile_reader(file) as archive,
504 ):
505 pickled = archive.get_record("data.pkl")
506 names = _weights_only_unpickler.get_globals_in_pkl(io.BytesIO(pickled))
507 except Exception as err: # malformed pickle or archive
508 raise ValueError(
509 f"Model file could not be read as a PyTorch archive "
510 f"({_truncate(str(err), 200)}); refusing to load."
511 ) from err
512 if not names <= _weights_only_unpickler._get_allowed_globals().keys():
513 raise LegacyFormatError(_LEGACY_FILE_ERROR.format(path=path))
514 try:
515 _DryRunUnpickler(io.BytesIO(pickled), budget=len(pickled)).load()
516 except _PickleRefusal:
517 raise
518 except Exception as err: # malformed pickle
519 raise ValueError(
520 f"Model file could not be read as a PyTorch archive "
521 f"({_truncate(str(err), 200)}); refusing to load."
522 ) from err
525def _has_honest_storage(tensor: torch.Tensor) -> bool:
526 """Whether every element of a dense tensor has its own bytes in its storage."""
527 if tensor.numel() == 0:
528 return True
529 if tensor.untyped_storage().nbytes() < tensor.numel() * tensor.element_size():
530 return False
531 # No two elements may share an address: with the dimensions sorted by stride, each
532 # stride must step past everything the smaller strides can reach. Size-1 dimensions
533 # are skipped.
534 reach = 0
535 steps = sorted(
536 (stride, size)
537 for size, stride in zip(tensor.shape, tensor.stride())
538 if size > 1
539 )
540 for stride, size in steps:
541 if stride <= reach:
542 return False
543 reach += stride * (size - 1)
544 return True
547def _unique_tensors(obj: Any) -> list[torch.Tensor]:
548 """
549 Every distinct tensor reachable from ``obj`` through dicts, lists and tuples.
551 Walks without recursion and tolerates cycles; other objects are not inspected. A set
552 or frozenset is refused.
553 """
554 tensors: list[torch.Tensor] = []
555 pending = [obj]
556 seen: set[int] = set()
557 while pending:
558 item = pending.pop()
559 if id(item) in seen:
560 continue
561 seen.add(id(item))
562 if isinstance(item, torch.Tensor):
563 tensors.append(item)
564 elif isinstance(item, dict):
565 pending.extend(item.keys())
566 pending.extend(item.values())
567 elif isinstance(item, (list, tuple)):
568 pending.extend(item)
569 elif isinstance(item, (set, frozenset)):
570 raise ValueError(_SET_ERROR)
571 return tensors
574def _reject_storage_tricks(tensors: list[torch.Tensor]) -> None:
575 """
576 Refuse any tensor whose shape is not backed by its own storage.
578 Meta tensors (a shape with no data), non-strided tensors, and expanded or
579 overlapping views (a huge shape over a few bytes) are refused.
580 """
581 for tensor in tensors:
582 try:
583 dense = tensor.layout == torch.strided and not tensor.is_meta
584 honest = dense and _has_honest_storage(tensor)
585 except (RuntimeError, NotImplementedError):
586 dense = honest = False
587 if not dense:
588 raise ValueError(_NO_STORAGE_ERROR)
589 if not honest:
590 raise ValueError(_STORAGE_TRICK_ERROR)
593def _reject_overlapping_storages(tensors: list[torch.Tensor]) -> None:
594 """
595 Refuse tensors whose storages overlap in the file without being the same slice.
597 With ``mmap=True`` every storage is a slice of one mapping of the file: as long as
598 the pickle claims, cut at the end of the file. torch refuses a tensor whose shape
599 needs bytes past that cut. Overlapping slices are refused here, except identical
600 ones: storages with the same slice count as one, and ``_copy_off_the_file`` copies
601 it once. A slice that runs past its own record into bytes no other storage of
602 ``tensors`` uses (zip headers, padding, other records, trailing metadata) is not
603 detected; it is bounded by the file's size.
604 """
605 spans = sorted(
606 {(s.data_ptr(), s.nbytes()) for s in (t.untyped_storage() for t in tensors)}
607 )
608 end = 0
609 for start, nbytes in spans:
610 if nbytes == 0:
611 continue
612 if start < end:
613 raise ValueError(_STORAGE_SIZE_ERROR)
614 end = max(end, start + nbytes)
617def _support_is_aliased(checkpoint: dict[str, Any]) -> bool:
618 """
619 Whether support or KDE data is stored once and referenced several times.
621 An untrusted file must keep every container and tensor under ``support`` and
622 ``outlier_kde`` distinct, with no two of those tensors sharing a storage. Runs
623 before ``_copy_off_the_file``.
624 """
625 seen_objects: set[int] = set()
626 seen_storages: set[tuple[int, int]] = set()
627 pending = [checkpoint.get("support"), checkpoint.get("outlier_kde")]
628 while pending:
629 item = pending.pop()
630 if not isinstance(item, (torch.Tensor, dict, list, tuple)):
631 continue
632 if id(item) in seen_objects:
633 return True
634 seen_objects.add(id(item))
635 if isinstance(item, torch.Tensor):
636 storage = item.untyped_storage()
637 key = (storage.data_ptr(), storage.nbytes())
638 if storage.nbytes() and key in seen_storages:
639 return True
640 seen_storages.add(key)
641 elif isinstance(item, dict):
642 pending.extend(item.values())
643 else:
644 pending.extend(item)
645 return False
648def _unalias_support(checkpoint: dict[str, Any]) -> None:
649 """
650 Give each label its own copy of its support and KDE data (used by
651 ``equine.upgrade``).
653 ``support`` maps labels to tensors, and ``outlier_kde`` maps labels to ``{"dataset":
654 tensor, ...}`` states. The per-label containers are rebuilt too. No container is
655 shared between labels.
656 """
657 for key in ("support", "outlier_kde"):
658 per_label = checkpoint.get(key)
659 if not isinstance(per_label, dict):
660 continue
661 copied = copy.copy(per_label) # keeps an OrderedDict an OrderedDict
662 for label, value in per_label.items():
663 if isinstance(value, torch.Tensor):
664 copied[label] = value.clone()
665 elif isinstance(value, dict): 665 ↛ 662line 665 didn't jump to line 662 because the condition on line 665 was always true
666 copied[label] = {
667 k: v.clone() if isinstance(v, torch.Tensor) else v
668 for k, v in value.items()
669 }
670 checkpoint[key] = copied
673def _require_supported_dtypes(
674 tensors: list[torch.Tensor], device: torch.device
675) -> None:
676 """
677 Refuse ``tensors`` if ``device`` lacks one of their dtypes (MPS has no float64).
679 A file saved from a float64 model, or holding float64 support, loads onto
680 MPS only with ``device="cpu"``.
681 """
682 for dtype in dict.fromkeys(tensor.dtype for tensor in tensors):
683 try:
684 torch.empty(0, dtype=dtype, device=device)
685 except (TypeError, RuntimeError) as err:
686 raise ValueError(
687 f"Model file holds a {str(dtype).removeprefix('torch.')} tensor, "
688 f"which {device.type} does not support; load it with device='cpu'"
689 ) from err
692def _copy_off_the_file(tensors: list[torch.Tensor], map_location: str | None) -> None:
693 """
694 Give every tensor its own copy of its storage, on ``map_location``.
696 Tensors loaded by the safe path (``mmap=True``) first view a mapping of the file.
697 After the copy they stay valid if the file later changes or shrinks. Each storage is
698 copied once and its tensors are re-pointed in place. Views and tied tensors keep
699 sharing, containers are untouched, and the copies add up to no more than the
700 storages already checked.
701 """
702 device = torch.device(map_location if map_location is not None else "cpu")
703 copies: dict[tuple[int, int], torch.UntypedStorage] = {}
704 with torch.no_grad():
705 for tensor in tensors:
706 storage = tensor.untyped_storage()
707 key = (storage.data_ptr(), storage.nbytes())
708 if key not in copies:
709 # Copied through a uint8 view of the storage.
710 raw = torch.empty(0, dtype=torch.uint8).set_(storage)
711 copies[key] = (
712 raw.clone() if device.type == "cpu" else raw.to(device)
713 ).untyped_storage()
714 layout = (
715 copies[key],
716 tensor.storage_offset(),
717 tensor.size(),
718 tensor.stride(),
719 )
720 if device.type == "cpu": 720 ↛ 723line 720 didn't jump to line 723 because the condition on line 720 was always true
721 tensor.set_(*layout)
722 else:
723 tensor.data = torch.empty(0, dtype=tensor.dtype, device=device).set_(
724 *layout
725 )
728def _is_extra_state_key(key: str) -> bool:
729 """Whether ``key`` is a module's ``get_extra_state`` entry in a state_dict."""
730 return key == "_extra_state" or key.endswith("._extra_state")
733def _state_dict_mismatch(
734 expected: Mapping[str, Any], actual: Mapping[str, Any]
735) -> str | None:
736 """
737 Check that ``actual`` (weights from a file) can fill ``expected`` (a module).
739 ``expected`` should come from ``state_dict(keep_vars=True)``. Parameter names and
740 shapes must agree, and the distinct storages behind ``actual`` must hold at least
741 one byte per element of ``expected``. Extra-state entries are skipped and left to
742 ``load_state_dict``.
743 Returns None when the weights fit, otherwise a short description whose
744 length does not depend on the (possibly file-supplied) key names.
745 """
746 expected_shapes = {
747 k: tuple(v.shape) for k, v in expected.items() if not _is_extra_state_key(k)
748 }
749 actual_shapes = {
750 k: tuple(v.shape) for k, v in actual.items() if not _is_extra_state_key(k)
751 }
752 differing = sorted(
753 k
754 for k in expected_shapes.keys() | actual_shapes.keys()
755 if expected_shapes.get(k) != actual_shapes.get(k)
756 )
757 if differing:
758 examples = ", ".join(_truncate(repr(k), 80) for k in differing[:3])
759 return f"{len(differing)} parameter(s) differ in name or shape, e.g. {examples}"
761 unique_expected = {
762 id(v): v for k, v in expected.items() if not _is_extra_state_key(k)
763 }
764 needed = sum(tensor.numel() for tensor in unique_expected.values())
765 storages = {
766 (storage.data_ptr(), storage.nbytes())
767 for storage in (
768 v.untyped_storage() for k, v in actual.items() if not _is_extra_state_key(k)
769 )
770 }
771 stored = sum(nbytes for _, nbytes in storages)
772 if stored < needed:
773 return (
774 f"the weights occupy {stored} bytes of storage, too small for the "
775 f"architecture they claim to describe ({needed} elements)"
776 )
777 return None
780def _dtype_kind(dtype: torch.dtype) -> str:
781 """Whether ``dtype`` is floating point, complex, or neither (integer or bool)."""
782 if dtype.is_floating_point:
783 return "floating-point"
784 if dtype.is_complex: 784 ↛ 785line 784 didn't jump to line 785 because the condition on line 784 was never true
785 return "complex"
786 return "integer or bool"
789def _dtype_kind_mismatch(
790 expected: Mapping[str, Any], actual: Mapping[str, Any]
791) -> str | None:
792 """
793 Describe the first tensor whose dtype kind differs between ``expected``
794 (a module's tensors) and ``actual`` (weights from a file), if any.
796 ``load_state_dict`` converts each stored tensor to the dtype of the
797 module's tensor without complaint, even floating-point weights into an
798 integer buffer. Extra-state entries, which it hands to ``set_extra_state``
799 unchanged, are skipped. The description's length does not depend on the
800 key names.
801 """
802 for key, tensor in expected.items():
803 stored = actual.get(key)
804 if _is_extra_state_key(key) or not (
805 isinstance(tensor, torch.Tensor) and isinstance(stored, torch.Tensor)
806 ):
807 continue
808 have, want = _dtype_kind(stored.dtype), _dtype_kind(tensor.dtype)
809 if have != want:
810 return (
811 f"{_truncate(repr(key), 80)} is {have} in the file but {want} in "
812 "the model"
813 )
814 return None
817def _adopt_stored_dtypes(
818 module: torch.nn.Module, stored: Mapping[str, Any], key: str
819) -> None:
820 """
821 Give each floating-point and complex tensor of ``module`` the dtype of the
822 tensor stored under its name in ``model_save[key]``.
824 A module is built at the dtypes its constructor chooses (usually torch's default
825 dtype). Converting each parameter and buffer in place first keeps every stored
826 precision, tensor by tensor, and keeps tied parameters tied. A stored tensor of
827 another kind is refused (see ``_dtype_kind_mismatch``); names the module lacks are
828 left to ``load_state_dict``.
829 """
830 owned = dict(
831 itertools.chain(
832 module.named_parameters(remove_duplicate=False),
833 module.named_buffers(remove_duplicate=False),
834 )
835 )
836 mismatch = _dtype_kind_mismatch(owned, stored)
837 if mismatch is not None:
838 raise ValueError(
839 f"Model file's {key} does not match the model it describes "
840 f"({mismatch}); the file is inconsistent or was tampered with."
841 )
842 for name, tensor in owned.items():
843 value = stored.get(name)
844 if (
845 isinstance(value, torch.Tensor)
846 and tensor.dtype != value.dtype
847 and (tensor.is_floating_point() or tensor.is_complex())
848 ):
849 tensor.data = tensor.data.to(value.dtype)
852def _require_weights_dict(
853 value: Any, key: str, allow_extra_state: bool = False
854) -> None:
855 """
856 Refuse ``model_save[key]`` unless it maps parameter names to tensors.
858 With ``allow_extra_state`` (an embedding's ``state_dict``), a module's
859 ``get_extra_state`` entries may hold other plain values; ``load_state_dict``
860 validates those.
861 """
862 if not (
863 isinstance(value, dict)
864 and all(
865 isinstance(k, str)
866 and (
867 isinstance(v, torch.Tensor)
868 or (allow_extra_state and _is_extra_state_key(k))
869 )
870 for k, v in value.items()
871 )
872 ):
873 raise ValueError(
874 f"Model file's {key} is malformed (expected a dictionary of parameter "
875 "names to tensors)."
876 )
879def _require_matching_weights(
880 expected: Mapping[str, torch.Tensor], stored: Any, key: str
881) -> None:
882 """
883 Refuse stored weights ``model_save[key]`` that cannot fill ``expected``.
885 ``expected`` holds meta tensors with the names and shapes that the model's
886 ``settings`` would build; the check runs before the model is constructed (see
887 ``_state_dict_mismatch``).
888 """
889 _require_weights_dict(stored, key)
890 mismatch = _state_dict_mismatch(expected, stored)
891 if mismatch is not None:
892 raise ValueError(
893 f"Model file's {key} does not match the model its settings describe "
894 f"({mismatch}); the file is inconsistent or was tampered with."
895 )
898def _require_entries(
899 model_save: dict[str, Any], keys: tuple[str, ...], cls: type
900) -> None:
901 """Refuse a checkpoint that lacks any of the entries ``cls`` rebuilds itself from."""
902 missing = [key for key in keys if key not in model_save]
903 if missing:
904 raise ValueError(
905 f"Model file is missing {', '.join(repr(key) for key in missing)}, which "
906 f"{cls.__name__} needs; the file is incomplete or was not written by "
907 "EQUINE."
908 )
911def _shown(value: Any) -> str:
912 """A bounded description of a file-supplied value for an error message."""
913 if isinstance(value, str):
914 return _truncate(repr(value), 80)
915 return f"a {type(value).__name__}"
918def _input_to_model(
919 X: torch.Tensor, module: torch.nn.Module, device: str
920) -> torch.Tensor:
921 """
922 Move ``X`` to ``device`` for ``module``, casting a floating input to its dtype.
924 A floating-point input is cast to the dtype of the module's first registered
925 parameter (a mixed-dtype module follows whichever parameter is registered first). A
926 non-floating input (integer indices for an ``nn.Embedding``, booleans) keeps its
927 dtype and is only moved, as is any input to a module without parameters.
928 """
929 param = next(module.parameters(), None)
930 if param is None or not X.is_floating_point():
931 return X.to(device=device)
932 return X.to(device=device, dtype=param.dtype)
935def _require_examples(X: torch.Tensor) -> None:
936 """
937 Refuse an empty input batch.
939 Raises
940 ------
941 ValueError
942 If ``X`` has no elements.
943 """
944 if X.numel() == 0:
945 raise ValueError("X is empty; predict needs at least one example.")
948def _require_finite_embeddings(embeddings: torch.Tensor) -> None:
949 """
950 Refuse embeddings that hold a NaN or infinite value.
952 Raises
953 ------
954 ValueError
955 If ``embeddings`` holds a NaN or infinite value.
956 """
957 if not bool(torch.isfinite(embeddings).all()):
958 raise ValueError(
959 "The embeddings of X hold NaN or infinite values; check X and the "
960 "embedding model."
961 )
964def _label_text(label: Any) -> str:
965 """``label`` as text, with an integral float shown as an integer."""
966 if isinstance(label, float) and label.is_integer():
967 return str(int(label))
968 return str(label)
971def _require_device(
972 settings: dict[str, Any],
973 hint: str = "",
974 what: str = "Model file's settings['device']",
975) -> None:
976 """
977 Refuse a file's ``settings["device"]`` unless this machine can build on it.
979 It must name a torch device that is the CPU or an accelerator available here, with
980 an index below that accelerator's device count when it has one (``cuda:7`` on a one-
981 GPU machine, or ``mps:1``, is refused); ``meta`` is refused. ``hint`` is appended to
982 the message for an unavailable device or index. ``what`` opens every message and
983 names the value being checked (``load_checkpoint`` and
984 ``_load_checkpoint_for_device`` pass "The requested device" for a caller's
985 ``map_location`` or ``device``).
986 """
987 if "device" not in settings:
988 return
989 value = settings["device"]
990 try:
991 if not isinstance(value, str):
992 raise TypeError("not a string")
993 device = torch.device(value)
994 except (TypeError, ValueError, RuntimeError) as err:
995 raise ValueError(
996 f"{what} is not a torch device name ({_shown(value)})."
997 ) from err
998 if device.type == "cpu":
999 return
1000 if device.type == "meta":
1001 raise ValueError(f"{what} is 'meta', which holds no data; refusing to load.")
1002 try:
1003 is_available = getattr(torch.get_device_module(device.type), "is_available")
1004 available = bool(is_available())
1005 except Exception: # an unknown or unregistered device type
1006 available = False
1007 if not available:
1008 raise ValueError(
1009 f"{what} ({_shown(value)}) is not available on this machine{hint}."
1010 )
1011 if device.index is not None: 1011 ↛ exitline 1011 didn't return from function '_require_device' because the condition on line 1011 was always true
1012 device_count = getattr(
1013 torch.get_device_module(device.type), "device_count", None
1014 )
1015 count = device_count() if device_count is not None else None
1016 if count is not None and device.index >= count: 1016 ↛ exitline 1016 didn't return from function '_require_device' because the condition on line 1016 was always true
1017 raise ValueError(
1018 f"{what} ({_shown(value)}) names device index {device.index}, but "
1019 f"this machine has {count} {device.type} device(s){hint}."
1020 )
1023def _int_label(label: Any) -> int | None:
1024 """
1025 ``label`` as an ``int`` if it is a whole number that ``int()`` converts exactly.
1027 Legacy files may store a label as a 0-dim tensor or a numpy integer. A
1028 ``bool`` (or bool tensor) or ``str`` is refused, as is anything ``int()``
1029 changes (``1.5``) or cannot convert (``inf``, a tuple); returns None then.
1030 """
1031 if isinstance(label, (bool, str, bytes)) or (
1032 isinstance(label, torch.Tensor) and label.dtype == torch.bool
1033 ):
1034 return None
1035 try:
1036 converted = int(label)
1037 exact = bool(converted == label)
1038 except (TypeError, ValueError, RuntimeError, OverflowError):
1039 return None
1040 return converted if exact else None
1043def _support_from_file(support: Any) -> OrderedDict[int, torch.Tensor]:
1044 """
1045 A checkpoint's ``support`` as ``{label: tensor}`` with distinct ``int`` labels.
1047 Each tensor holds rows of examples and has at least one dimension; every label's
1048 examples have the same shape. Anything else is refused with a bounded ValueError
1049 (see ``_int_label``).
1050 """
1051 error = ValueError(
1052 "Model file's support is malformed (expected a dictionary of distinct "
1053 "integer labels to tensors of rows that share one example shape)."
1054 )
1055 if not isinstance(support, dict):
1056 raise error
1057 converted: OrderedDict[int, torch.Tensor] = OrderedDict()
1058 example_shape: torch.Size | None = None
1059 for label, rows in support.items():
1060 key = _int_label(label)
1061 if key is None or key in converted or not isinstance(rows, torch.Tensor):
1062 raise error
1063 if rows.dim() == 0 or (
1064 example_shape is not None and rows.shape[1:] != example_shape
1065 ):
1066 raise error
1067 example_shape = rows.shape[1:]
1068 converted[key] = rows
1069 return converted
1072def _finite_float(value: Any) -> float | None:
1073 """
1074 ``value`` as a finite ``float`` if it is exactly an ``int`` or ``float``.
1076 Returns None for anything else, including an ``int`` too large for a
1077 ``float`` and an infinite or NaN ``float``. A ``bool`` is refused.
1078 """
1079 if type(value) not in (int, float):
1080 return None
1081 try:
1082 converted = float(value)
1083 except OverflowError:
1084 return None
1085 return converted if math.isfinite(converted) else None
1088def _kde_from_state(state: Any) -> gaussian_kde:
1089 """Rebuild one outlier-score KDE from the state that ``save`` writes."""
1090 if not (isinstance(state, dict) and set(state) == {"dataset", "bw_factor"}):
1091 raise ValueError(
1092 "Model file's outlier_kde is malformed (each entry must be a dictionary "
1093 "with exactly 'dataset' and 'bw_factor')."
1094 )
1095 dataset, bw_factor = state["dataset"], state["bw_factor"]
1096 if not (
1097 isinstance(dataset, torch.Tensor)
1098 and (dataset.dim() == 1 or (dataset.dim() == 2 and dataset.shape[0] == 1))
1099 ):
1100 raise ValueError(
1101 "Model file's outlier_kde is malformed ('dataset' must be a 1-D or "
1102 "(1, n) tensor)."
1103 )
1104 bandwidth = _finite_float(bw_factor)
1105 if bandwidth is None or bandwidth <= 0:
1106 raise ValueError(
1107 "Model file's outlier_kde is malformed ('bw_factor' must be a positive "
1108 f"finite number; got {_shown(bw_factor)})."
1109 )
1110 try:
1111 return gaussian_kde(dataset.detach().cpu().numpy(), bw_method=bandwidth)
1112 except Exception as err: # e.g. too few points for a covariance
1113 raise ValueError(
1114 "Model file's outlier_kde could not be rebuilt "
1115 f"({_truncate(_describe_error(err), 200)})."
1116 ) from err
1119def _outlier_kde_from_file(value: Any) -> OrderedDict[int, gaussian_kde]:
1120 """
1121 A checkpoint's ``outlier_kde`` as ``{label: gaussian_kde}`` with distinct labels.
1123 Each KDE is stored as ``{"dataset": tensor, "bw_factor": number}`` (see
1124 ``_kde_from_state``).
1125 """
1126 if not isinstance(value, dict):
1127 raise ValueError(
1128 "Model file's outlier_kde is malformed (expected a dictionary of labels "
1129 "to KDE states)."
1130 )
1131 kdes: OrderedDict[int, gaussian_kde] = OrderedDict()
1132 for label, state in value.items():
1133 key = _int_label(label)
1134 if key is None or key in kdes:
1135 raise ValueError(
1136 "Model file's outlier_kde is malformed (its labels must be distinct "
1137 "integers)."
1138 )
1139 if isinstance(state, gaussian_kde):
1140 raise ValueError(
1141 "Model file's outlier_kde holds a pickled gaussian_kde object, as "
1142 f"files from earlier EQUINE releases do; rewrite the file with "
1143 f"`{_UPGRADE_HINT}`."
1144 )
1145 kdes[key] = _kde_from_state(state)
1146 return kdes
1149def _require_names(value: Any, key: str) -> None:
1150 """
1151 Refuse ``feature_names`` / ``label_names`` that are not None or a list of str.
1153 ``str`` subclasses pass: legacy files may hold numpy strings.
1154 """
1155 if value is None or (
1156 isinstance(value, list) and all(isinstance(name, str) for name in value)
1157 ):
1158 return
1159 raise ValueError(
1160 f"Model file's {key} must be None or a list of strings; got {_shown(value)}."
1161 )
1164def _checked_settings(cls: type, settings: Any) -> dict[str, Any]:
1165 """
1166 Return a copy of a file's ``settings`` once ``cls`` is known to accept them.
1168 The settings are passed as ``cls(embedding, **settings)``.
1169 Keys must be strings naming a parameter of ``cls.__init__`` (other than
1170 ``self`` and ``embedding_model``); a constructor taking ``**kwargs``
1171 accepts any string key. The plain values common to the model classes are
1172 type-checked here (an ``int`` temperature becomes a ``float``), and so is
1173 ``ood_distance``, which must be one of ``_OOD_DISTANCES``; sizes,
1174 ``cov_type`` and ``device`` are checked by the caller.
1175 """
1176 if not (isinstance(settings, dict) and all(isinstance(k, str) for k in settings)):
1177 raise ValueError(
1178 "Model file's settings are malformed (expected a dictionary with "
1179 "string keys)."
1180 )
1181 parameters = inspect.signature(cls.__init__).parameters
1182 if not any(p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values()):
1183 accepted = set(parameters) - {"self", "embedding_model"}
1184 unknown = sorted(k for k in settings if k not in accepted)
1185 if unknown:
1186 examples = ", ".join(_truncate(repr(k), 80) for k in unknown[:3])
1187 raise ValueError(
1188 f"Model file's settings contain {len(unknown)} key(s) that "
1189 f"{cls.__name__} does not accept, e.g. {examples}; the file was "
1190 "written by an incompatible EQUINE version or was tampered with."
1191 )
1192 checked = dict(settings)
1193 if "init_temperature" in checked: 1193 ↛ 1207line 1193 didn't jump to line 1207 because the condition on line 1193 was always true
1194 temperature = checked["init_temperature"]
1195 if type(temperature) not in (int, float):
1196 raise ValueError(
1197 "Model file's settings['init_temperature'] must be a number; got "
1198 f"{_shown(temperature)}."
1199 )
1200 try:
1201 checked["init_temperature"] = float(temperature)
1202 except OverflowError as err:
1203 raise ValueError(
1204 "Model file's settings['init_temperature'] is an int too large for "
1205 "a float."
1206 ) from err
1207 for key in ("relative_mahal", "use_temperature"):
1208 if key in checked and type(checked[key]) is not bool:
1209 raise ValueError(
1210 f"Model file's settings[{key!r}] must be True or False; got "
1211 f"{_shown(checked[key])}."
1212 )
1213 if "ood_distance" in checked:
1214 ood_distance = checked["ood_distance"]
1215 if not (isinstance(ood_distance, str) and ood_distance in _OOD_DISTANCES):
1216 raise ValueError(
1217 "Model file's settings['ood_distance'] must be one of "
1218 f"{list(_OOD_DISTANCES)}; got {_shown(ood_distance)}."
1219 )
1220 for key in ("feature_names", "label_names"):
1221 if key in checked:
1222 _require_names(checked[key], f"settings[{key!r}]")
1223 return checked
1226def _off_meta_tensors(module: torch.nn.Module) -> list[str]:
1227 """Names of the parameters and buffers a meta-device build left off the meta device."""
1228 owned = itertools.chain(module.named_parameters(), module.named_buffers())
1229 return [name for name, tensor in owned if not tensor.is_meta]
1232def _submodule_layout(module: torch.nn.Module) -> list[tuple[str, str, str, str]]:
1233 """
1234 Name, class (module and qualified name) and hyper-parameters of every
1235 submodule of ``module``.
1237 A class is identified by its module and qualified name. A class created anew for
1238 each instance (as torch's parametrizations do) or defined again by re-running its
1239 definition matches. Hyper-parameters come from ``extra_repr`` for torch's own layers
1240 only. For a user-defined module only its class is compared (its children are listed
1241 separately).
1242 """
1243 return [
1244 (
1245 name,
1246 type(sub).__module__,
1247 type(sub).__qualname__,
1248 sub.extra_repr() if type(sub).__module__.startswith("torch.") else "",
1249 )
1250 for name, sub in module.named_modules()
1251 ]
1254def _submodule_difference(
1255 rebuilt: torch.nn.Module, live: torch.nn.Module
1256) -> str | None:
1257 """Where ``live``'s submodules differ from those its recipe rebuilds, if anywhere."""
1259 def describe(
1260 entry: tuple[str, str, str, str] | None,
1261 other: tuple[str, str, str, str] | None,
1262 ) -> str:
1263 if entry is None:
1264 return "nothing"
1265 _, module, qualname, hyper = entry
1266 shown = qualname.rpartition(".")[2]
1267 # Two classes with the same name are told apart by where they are defined.
1268 if other is not None and other[2].rpartition(".")[2] == shown:
1269 if other[1] != module:
1270 shown = f"{module}.{qualname}"
1271 elif other[2] != qualname:
1272 shown = qualname
1273 return _truncate(f"{shown}({hyper})", 100)
1275 expected, actual = _submodule_layout(rebuilt), _submodule_layout(live)
1276 for want, have in itertools.zip_longest(expected, actual):
1277 if want != have:
1278 name = (have or want)[0]
1279 return (
1280 f"its submodules differ from those its recipe builds (at "
1281 f"{_truncate(repr(name), 80)}: {describe(have, want)} in the model, "
1282 f"{describe(want, have)} from the recipe); every architectural choice "
1283 "must be a constructor argument, not set after construction"
1284 )
1285 return None
1288def _recipe_problem(
1289 recipe: Any,
1290 state_dict: Mapping[str, Any],
1291 live: torch.nn.Module | None = None,
1292) -> str | None:
1293 """
1294 Why ``recipe`` cannot be trusted to rebuild a module holding ``state_dict``.
1296 Returns None when it can. The recipe is built on the meta device (no memory) and
1297 checked before anything is allocated: the constructor must leave every tensor on the
1298 meta device, ``state_dict()`` (including ``get_extra_state``) must run there,
1299 and the stored weights must match it in names, shapes and dtype kinds
1300 with enough storage behind them (see ``_state_dict_mismatch`` and
1301 ``_dtype_kind_mismatch``). With ``live``, the module being saved, its submodules
1302 must also match the rebuild. A recipe that cannot be built at all raises
1303 ``build_from_recipe``'s ValueError.
1304 """
1305 with torch.device("meta"):
1306 skeleton = build_from_recipe(recipe)
1307 off_meta = _off_meta_tensors(skeleton)
1308 if off_meta:
1309 return (
1310 f"its constructor allocated {len(off_meta)} tensor(s) off the meta "
1311 f"device, e.g. {_truncate(repr(off_meta[0]), 80)}, so its size cannot be "
1312 "checked before it is built"
1313 )
1314 try:
1315 expected = skeleton.state_dict(keep_vars=True)
1316 except Exception as err:
1317 return (
1318 "its state_dict()/get_extra_state could not run on the meta device "
1319 f"({_truncate(_describe_error(err), 300)})"
1320 )
1321 if live is not None:
1322 difference = _submodule_difference(skeleton, live)
1323 if difference is not None:
1324 return difference
1325 mismatch = _state_dict_mismatch(expected, state_dict) or _dtype_kind_mismatch(
1326 expected, state_dict
1327 )
1328 if mismatch is not None:
1329 return f"the recipe does not match the weights ({mismatch})"
1330 return None
1333def _require_rebuildable(
1334 embedding: torch.nn.Module, recipe: dict[str, Any], state_dict: Mapping[str, Any]
1335) -> None:
1336 """
1337 Refuse to save an embedding that the loader could not rebuild from its recipe.
1339 Runs the loader's ``_recipe_problem`` check, and also compares the rebuild's
1340 submodules with the live module. Extra state (``get_extra_state``) holding anything
1341 but plain values and tensors (not quantized, without Python attributes) is refused
1342 too.
1343 """
1344 extra_state = {k: v for k, v in state_dict.items() if _is_extra_state_key(k)}
1345 try:
1346 _check_plain(extra_state, allow_tensors=True, what="Extra state")
1347 except TypeError as err:
1348 raise ValueError(
1349 f"Cannot save the embedding model ({type(embedding).__name__}): {err}"
1350 ) from err
1351 try:
1352 problem = _recipe_problem(recipe, state_dict, live=embedding)
1353 except ValueError as err:
1354 problem = f"building it on the meta device failed ({_truncate(str(err), 300)})"
1355 if problem is not None:
1356 raise ValueError(
1357 f"Cannot save: the embedding model ({type(embedding).__name__}, registered "
1358 f"as {recipe['builder']!r}) cannot be rebuilt from its recipe: {problem}. "
1359 "It may have been modified after construction, or its constructor may not "
1360 "run on the meta device; see the constructor requirements in the "
1361 "equine.embedding_architecture docstring."
1362 )
1365def _embedding_checkpoint(embedding: torch.nn.Module) -> dict[str, Any]:
1366 """
1367 The checkpoint entries describing an embedding model: its recipe and its
1368 ``state_dict``, after checking that the recipe rebuilds the same module
1369 (see ``_require_rebuildable``).
1370 """
1371 recipe = embedding_recipe(embedding)
1372 if recipe is None:
1373 raise ValueError(
1374 f"Cannot save: the embedding model ({type(embedding).__name__}) is not a "
1375 "registered architecture, so it has no recipe to store. Register it with "
1376 "@equine.embedding_architecture('yourproject.name') and construct it "
1377 "with plain-valued arguments."
1378 )
1379 state_dict = embedding.state_dict()
1380 # The check below runs the constructor, which could mutate the recipe.
1381 stored_recipe = copy.deepcopy(recipe)
1382 _require_rebuildable(embedding, recipe, state_dict)
1383 return {"embedding_recipe": stored_recipe, "embedding_state_dict": state_dict}
1386def _load_embedding_weights(
1387 module: torch.nn.Module, state_dict: Mapping[str, Any]
1388) -> None:
1389 """``load_state_dict`` with any failure reported as a bounded ValueError."""
1390 try:
1391 module.load_state_dict(state_dict)
1392 except Exception as err:
1393 raise ValueError(
1394 "Could not load the embedding weights stored in the file: "
1395 f"{_truncate(_message_or_type(err))}"
1396 ) from err
1399def _holds_torchscript(checkpoint: Mapping[str, Any]) -> bool:
1400 """Whether a checkpoint stores its embedding model as TorchScript."""
1401 return (
1402 "embed_jit_save" in checkpoint or checkpoint.get("contains_executable") is True
1403 )
1406def _refuse_torchscript(checkpoint: Mapping[str, Any], path: str) -> None:
1407 """Raise if the checkpoint read from ``path`` stores its embedding as TorchScript."""
1408 if _holds_torchscript(checkpoint):
1409 raise ValueError(_TORCHSCRIPT_FILE_ERROR.format(path=path))
1412def _rebuild_embedding(
1413 model_save: dict[str, Any], embedding_model: torch.nn.Module | None
1414) -> torch.nn.Module:
1415 """
1416 Reconstitute an embedding model from a checkpoint: a caller-supplied
1417 module (the file's stored dtypes and weights loaded into it), else the
1418 file's recipe rebuilt through the registry. A file that stores its
1419 embedding as TorchScript is refused first, whatever else it holds.
1420 """
1421 if _holds_torchscript(model_save):
1422 raise ValueError(_TORCHSCRIPT_CHECKPOINT_ERROR)
1423 state_dict = model_save.get("embedding_state_dict")
1424 if state_dict is not None:
1425 _require_weights_dict(
1426 state_dict, "embedding_state_dict", allow_extra_state=True
1427 )
1429 if embedding_model is not None:
1430 if state_dict is None:
1431 raise ValueError(
1432 "Model file contains no embedding weights to load into the "
1433 "supplied embedding_model (no embedding_state_dict)."
1434 )
1435 owned = embedding_model.state_dict(keep_vars=True)
1436 mismatch = _state_dict_mismatch(owned, state_dict) or _dtype_kind_mismatch(
1437 owned, state_dict
1438 )
1439 if mismatch is not None:
1440 raise ValueError(
1441 f"The supplied embedding_model ({type(embedding_model).__name__}) does "
1442 f"not match the weights stored in the file ({mismatch}); pass a module "
1443 "of the architecture the file was saved with."
1444 )
1445 # Converted on the CPU; the model's constructor then moves the module to the
1446 # model's device.
1447 embedding_model.to("cpu")
1448 _adopt_stored_dtypes(embedding_model, state_dict, "embedding_state_dict")
1449 _load_embedding_weights(embedding_model, state_dict)
1450 return embedding_model
1452 if "embedding_recipe" in model_save:
1453 recipe = model_save["embedding_recipe"]
1454 # Checked on the meta device against the file's weights first.
1455 problem = _recipe_problem(recipe, state_dict or {})
1456 if problem is not None:
1457 raise ValueError(
1458 f"Refusing to build the embedding recipe {recipe.get('builder')!r} "
1459 f"stored in the file: {problem}."
1460 )
1461 embedding = build_from_recipe(recipe)
1462 _adopt_stored_dtypes(embedding, state_dict or {}, "embedding_state_dict")
1463 _load_embedding_weights(embedding, state_dict or {})
1464 return embedding
1466 raise ValueError("Model file contains no embedding model (no recipe).")
1469@icontract.require(lambda y_hat, y_test: y_hat.size(dim=0) == y_test.size(dim=0))
1470@icontract.ensure(lambda result: result >= 0.0)
1471@beartype
1472def brier_score(y_hat: torch.Tensor, y_test: torch.Tensor) -> float:
1473 """
1474 Compute the Brier score for a multiclass problem:
1475 $$ \\frac{1}{N} \\sum_{i=1}^{N} \\sum_{j=1}^{M} (f_{ij} - o_{ij})^2 , $$
1476 where $f_{ij}$ is the predicted probability of class $j$ for inference sample $i$
1477 and $o_{ij}$ is the one-hot encoded ground truth label.
1479 Parameters
1480 ----------
1481 y_hat : torch.Tensor
1482 Probabilities for each class.
1483 y_test : torch.Tensor
1484 Integer argument class labels (ground truth), moved to ``y_hat``'s device.
1486 Returns
1487 -------
1488 float
1489 Brier score.
1490 """
1491 _, num_classes = y_hat.size()
1492 one_hot_y_test = torch.nn.functional.one_hot(
1493 y_test.to(y_hat.device).long(), num_classes=num_classes
1494 )
1495 bs = torch.mean(torch.sum((y_hat - one_hot_y_test) ** 2, dim=1)).item()
1496 return bs
1499@icontract.require(lambda y_hat, y_test: y_hat.size(dim=0) == y_test.size(dim=0))
1500@icontract.ensure(lambda result: result <= 1.0)
1501@beartype
1502def brier_skill_score(y_hat: torch.Tensor, y_test: torch.Tensor) -> float:
1503 """
1504 Compute the Brier skill score as compared to randomly guessing.
1506 Parameters
1507 ----------
1508 y_hat : torch.Tensor
1509 Probabilities for each class.
1510 y_test : torch.Tensor
1511 Integer argument class labels (ground truth), moved to ``y_hat``'s device.
1513 Returns
1514 -------
1515 float
1516 Brier skill score.
1517 """
1518 _, num_classes = y_hat.size()
1519 random_guess = (1.0 / num_classes) * torch.ones(y_hat.size(), device=y_hat.device)
1520 bs0 = brier_score(random_guess, y_test)
1521 bs1 = brier_score(y_hat, y_test)
1522 bss = 1.0 - bs1 / bs0
1523 return bss
1526@icontract.require(lambda y_hat, y_test: y_hat.size(dim=0) == y_test.size(dim=0))
1527@icontract.ensure(lambda result: (0.0 <= result) and (result <= 1.0))
1528@beartype
1529def expected_calibration_error(y_hat: torch.Tensor, y_test: torch.Tensor) -> float:
1530 """
1531 Compute the expected calibration error (ECE) for a multiclass problem.
1533 Parameters
1534 ----------
1535 y_hat : torch.Tensor
1536 Probabilities for each class.
1537 y_test : torch.Tensor
1538 Class label indices (ground truth), moved to ``y_hat``'s device.
1540 Returns
1541 -------
1542 float
1543 Expected calibration error.
1544 """
1545 _, num_classes = y_hat.size()
1546 metric = MulticlassCalibrationError(num_classes=num_classes, n_bins=25, norm="l1")
1547 ece = metric.to(y_hat.device)(y_hat, y_test.to(y_hat.device)).item()
1548 return ece
1551@icontract.require(
1552 lambda train_y, selected_labels: len(selected_labels) <= len(train_y)
1553)
1554@icontract.ensure(
1555 lambda result, selected_labels: set(result.keys()).issubset(set(selected_labels))
1556)
1557@beartype
1558def _get_shuffle_idxs_by_class(
1559 train_y: torch.Tensor, selected_labels: list
1560) -> dict[Any, torch.Tensor]:
1561 """
1562 Internal helper function to randomly select indices of example classes for a given
1563 set of labels.
1565 Parameters
1566 ----------
1567 train_y : torch.Tensor
1568 Label data.
1569 selected_labels : list
1570 list of unique labels found in the label data.
1572 Returns
1573 -------
1574 dict[Any, torch.Tensor]
1575 Tensor of indices corresponding to each label.
1577 Raises
1578 ------
1579 ValueError
1580 If a label in ``selected_labels`` has no examples in ``train_y``.
1581 """
1582 shuffled_idxs_by_class = OrderedDict()
1583 for label in selected_labels:
1584 label_idxs = torch.argwhere(train_y == label).reshape(-1)
1585 if label_idxs.shape[0] == 0:
1586 raise ValueError(f"Class {label} has no examples.")
1587 shuffled_idxs_by_class[label] = label_idxs[torch.randperm(label_idxs.shape[0])]
1589 return shuffled_idxs_by_class
1592@icontract.require(lambda train_x, train_y: len(train_x) <= len(train_y))
1593@icontract.require(
1594 lambda selected_labels, train_x: (
1595 (0 < len(selected_labels)) & (len(selected_labels) < len(train_x))
1596 )
1597)
1598@icontract.require(
1599 lambda support_size, train_x: (0 < support_size) & (support_size < len(train_x))
1600)
1601@icontract.require(
1602 lambda support_size, selected_labels, train_x: (
1603 support_size * len(selected_labels) <= len(train_x)
1604 )
1605)
1606@icontract.require(
1607 lambda selected_labels, shuffled_indexes: (
1608 (len(shuffled_indexes.keys()) == len(selected_labels))
1609 if shuffled_indexes is not None
1610 else True
1611 )
1612)
1613@icontract.ensure(
1614 lambda result, selected_labels: len(result.keys()) == len(selected_labels)
1615)
1616@beartype
1617def generate_support(
1618 train_x: torch.Tensor,
1619 train_y: torch.Tensor,
1620 support_size: int,
1621 selected_labels: list[Any],
1622 shuffled_indexes: dict[Any, torch.Tensor] | None = None,
1623) -> OrderedDict[int, torch.Tensor]:
1624 """
1625 Randomly select `support_size` examples of each class in `selected_labels` from the examples in
1626 `train_x` with corresponding labels in `train_y` and return them as a dictionary.
1628 Parameters
1629 ----------
1630 train_x : torch.Tensor
1631 Input training data.
1632 train_y : torch.Tensor
1633 Corresponding classification labels.
1634 support_size : int
1635 Number of support examples for each class.
1636 selected_labels : list
1637 Selected class labels to generate examples from.
1638 shuffled_indexes: dict[Any, torch.Tensor] | None, optional
1639 Simply use the precomputed indexes if they are available
1641 Returns
1642 -------
1643 OrderedDict[int, torch.Tensor]
1644 Ordered dictionary of class labels with corresponding support examples.
1646 Raises
1647 ------
1648 ValueError
1649 If ``shuffled_indexes`` is None and a selected class has fewer than
1650 ``support_size`` examples, or ``shuffled_indexes`` for a label selects
1651 no example or an example of another label.
1652 """
1653 if shuffled_indexes is None:
1654 labels, counts = torch.unique(train_y, return_counts=True)
1655 for label, count in list(zip(labels, counts)):
1656 if (label in selected_labels) and (count < support_size):
1657 raise ValueError(f"Not enough support examples in class {label}")
1658 shuffled_idxs = _get_shuffle_idxs_by_class(train_y, selected_labels)
1659 else:
1660 shuffled_idxs = shuffled_indexes
1662 support = OrderedDict[int, torch.Tensor]()
1663 for label in selected_labels:
1664 selected_support = train_x[shuffled_idxs[label][:support_size]]
1666 if torch.unique(train_y[shuffled_idxs[label]]).tolist() != [label]:
1667 raise ValueError(
1668 f"The shuffled indexes for label {label} must select at least one "
1669 "example, and only examples of that label."
1670 )
1671 support[int(label)] = selected_support
1673 return support
1676@icontract.require(lambda train_x: len(train_x.shape) >= 2)
1677@icontract.require(lambda train_y: len(train_y.shape) == 1)
1678@icontract.require(lambda support_size: support_size > 1)
1679@icontract.require(lambda way: way > 0)
1680@icontract.require(lambda episode_size: episode_size > 0)
1681@icontract.ensure(lambda result: len(result) == 3)
1682@icontract.ensure(lambda result: result[1].shape[0] == result[2].shape[0])
1683@icontract.ensure(lambda way, result: len(result[0]) == way)
1684@icontract.ensure(
1685 lambda support_size, result: all(
1686 len(support) == support_size for support in result[0].values()
1687 )
1688)
1689@beartype
1690def generate_episode(
1691 train_x: torch.Tensor,
1692 train_y: torch.Tensor,
1693 support_size: int,
1694 way: int,
1695 episode_size: int,
1696) -> tuple[OrderedDict[int, torch.Tensor], torch.Tensor, torch.Tensor]:
1697 """
1698 Generate a single episode of data for a few-shot learning task.
1700 Parameters
1701 ----------
1702 train_x : torch.Tensor
1703 Input training data.
1704 train_y : torch.Tensor
1705 Corresponding classification labels.
1706 support_size : int
1707 Number of support examples for each class.
1708 way : int
1709 Number of classes in the episode.
1710 episode_size : int
1711 Upper bound on the number of query examples; each class contributes
1712 up to ``episode_size // way``.
1714 Returns
1715 -------
1716 tuple[OrderedDict[int, torch.Tensor], torch.Tensor, torch.Tensor]
1717 tuple of the support examples keyed ``0`` to ``way - 1`` in ascending
1718 order of the selected labels, the query examples, and the query labels
1719 (the same indices).
1721 Raises
1722 ------
1723 ValueError
1724 If ``way`` exceeds the number of labels, or a selected class has no
1725 more than ``support_size`` examples.
1726 """
1727 labels, counts = torch.unique(train_y, return_counts=True)
1728 if way > len(labels):
1729 raise ValueError(
1730 f"The way (#classes in each episode), {way}, must be <= number of labels, {len(labels)}"
1731 )
1733 selected_labels = sorted(
1734 labels[torch.randperm(labels.shape[0])][:way].tolist()
1735 ) # need to be in same order every time
1737 for label, count in list(zip(labels.tolist(), counts.tolist())):
1738 if (label in selected_labels) and (count <= support_size):
1739 raise ValueError(
1740 f"Class {_label_text(label)} has {count} examples; an episode needs "
1741 f"more than support_size ({support_size})."
1742 )
1743 shuffled_idxs = _get_shuffle_idxs_by_class(train_y, selected_labels)
1745 support = generate_support(
1746 train_x, train_y, support_size, selected_labels, shuffled_idxs
1747 )
1749 examples_per_task = episode_size // way
1751 episode_data_list = []
1752 episode_label_list = []
1753 episode_support = OrderedDict()
1754 for episode_label, label in enumerate(selected_labels):
1755 num_remaining_examples = len(shuffled_idxs[label]) - support_size
1756 episode_end_idx = support_size + min(num_remaining_examples, examples_per_task)
1757 query_idxs = shuffled_idxs[label][support_size:episode_end_idx]
1759 episode_data_list.append(train_x[query_idxs])
1760 episode_label_list.append(torch.Tensor([episode_label] * len(query_idxs)))
1761 episode_support[episode_label] = support[label]
1763 episode_x = torch.concat(episode_data_list)
1764 episode_y = torch.concat(episode_label_list)
1766 return episode_support, episode_x, episode_y.to(torch.long)
1769def _labels_to_columns(y: torch.Tensor, label_order: list[int]) -> torch.Tensor:
1770 """
1771 The column of each label in ``y``, where column ``j`` holds ``label_order[j]``.
1773 Parameters
1774 ----------
1775 y : torch.Tensor
1776 Class labels.
1777 label_order : list[int]
1778 The class label of each column, in column order.
1780 Returns
1781 -------
1782 torch.Tensor
1783 ``torch.long`` column indices, one per element of ``y``, on its device.
1785 Raises
1786 ------
1787 ValueError
1788 If ``y`` holds a value that is not in ``label_order``.
1789 """
1790 order = torch.tensor(label_order, device=y.device)
1791 matches = y.reshape(-1, 1) == order
1792 unknown = ~matches.any(dim=1)
1793 if bool(unknown.any()):
1794 shown = torch.unique(y.reshape(-1)[unknown])[:5].tolist()
1795 raise ValueError(
1796 f"Labels {shown} are not among the class labels "
1797 f"{_truncate(str(label_order), 200)}."
1798 )
1799 return matches.long().argmax(dim=1)
1802@icontract.require(
1803 lambda eq_preds, true_y: eq_preds.classes.size(dim=0) == true_y.size(dim=0)
1804)
1805@beartype
1806def generate_model_metrics(
1807 eq_preds: EquineOutput,
1808 true_y: torch.Tensor,
1809 *,
1810 label_order: list[int] | None = None,
1811) -> dict[str, Any]:
1812 """
1813 Generate various metrics for evaluating a model's performance.
1815 Parameters
1816 ----------
1817 eq_preds : EquineOutput
1818 Model predictions.
1819 true_y : torch.Tensor
1820 True class labels, moved to the device of ``eq_preds.classes``, where
1821 the metrics are computed.
1822 label_order : list[int] | None, optional
1823 Keyword-only. The class label of each column of ``eq_preds.classes``,
1824 in column order (for an ``EquineProtonet``, ``list(model.get_support())``);
1825 ``true_y`` is mapped to column indices through it. With None, column
1826 ``j`` holds label ``j``.
1828 Returns
1829 -------
1830 dict[str, Any]
1831 Dictionary of model metrics. ``"confusionMatrix"`` has one row per true
1832 class and one column per predicted class, in column order.
1834 Raises
1835 ------
1836 ValueError
1837 If ``label_order`` does not name one distinct label per column, or
1838 ``true_y`` holds a label that is not in it.
1839 """
1840 device = eq_preds.classes.device
1841 true_y = true_y.to(device)
1842 if label_order is not None:
1843 columns = eq_preds.classes.shape[1]
1844 if len(label_order) != columns or len(set(label_order)) != columns:
1845 raise ValueError(
1846 f"label_order must hold {columns} distinct labels, one per column "
1847 f"of predictions; got {_truncate(str(label_order), 200)}."
1848 )
1849 true_y = _labels_to_columns(true_y, label_order)
1850 pred_y = torch.argmax(eq_preds.classes, dim=1)
1851 accuracy = MulticlassAccuracy(num_classes=eq_preds.classes.shape[1]).to(device)
1852 f1_score = MulticlassF1Score(
1853 num_classes=eq_preds.classes.shape[1], average="micro"
1854 ).to(device)
1855 confusion_matrix = MulticlassConfusionMatrix(
1856 num_classes=eq_preds.classes.shape[1]
1857 ).to(device)
1858 metrics = {
1859 "accuracy": accuracy(pred_y, true_y),
1860 "microF1Score": f1_score(pred_y, true_y),
1861 "confusionMatrix": confusion_matrix(pred_y, true_y).tolist(),
1862 "brierScore": brier_score(eq_preds.classes, true_y),
1863 "brierSkillScore": brier_skill_score(eq_preds.classes, true_y),
1864 "expectedCalibrationError": expected_calibration_error(
1865 eq_preds.classes, true_y
1866 ),
1867 }
1868 return metrics
1871@icontract.require(lambda Y: len(Y.shape) == 1)
1872@icontract.ensure(
1873 lambda result: all("label" in d and "numExamples" in d for d in result)
1874)
1875@icontract.ensure(lambda result: all(d["numExamples"] >= 0 for d in result))
1876@beartype
1877def get_num_examples_per_label(Y: torch.Tensor) -> list[dict[str, Any]]:
1878 """
1879 Get the number of examples per label in the given tensor.
1881 Parameters
1882 ----------
1883 Y : torch.Tensor
1884 Tensor of class labels.
1886 Returns
1887 -------
1888 list[dict[str, Any]]
1889 list of dictionaries containing label and number of examples.
1890 """
1891 tensor_labels, tensor_counts = Y.unique(return_counts=True)
1893 examples_per_label = []
1894 for i, label in enumerate(tensor_labels):
1895 examples_per_label.append(
1896 {"label": label.item(), "numExamples": tensor_counts[i].item()}
1897 )
1899 return examples_per_label
1902@icontract.require(lambda train_y: train_y.shape[0] > 0)
1903@beartype
1904def generate_train_summary(
1905 model: Equine, train_y: torch.Tensor, date_trained: str
1906) -> dict[str, Any]:
1907 """
1908 Generate a summary of the training data.
1910 Parameters
1911 ----------
1912 model : Equine
1913 Model object.
1914 train_y : torch.Tensor
1915 Training labels.
1916 date_trained : str
1917 Date of training.
1919 Returns
1920 -------
1921 dict[str, Any]
1922 Dictionary containing training summary.
1923 """
1924 train_summary = {
1925 "numTrainExamples": get_num_examples_per_label(train_y),
1926 "dateTrained": date_trained,
1927 "modelType": model.__class__.__name__,
1928 }
1929 return train_summary
1932@icontract.require(
1933 lambda eq_preds, test_y: test_y.shape[0] == eq_preds.classes.shape[0]
1934)
1935@beartype
1936def generate_model_summary(
1937 model: Equine,
1938 eq_preds: EquineOutput,
1939 test_y: torch.Tensor,
1940) -> dict[str, Any]:
1941 """
1942 Generate a summary of the model's performance.
1944 Parameters
1945 ----------
1946 model : Equine
1947 Model object.
1948 eq_preds : EquineOutput
1949 Model predictions.
1950 test_y : torch.Tensor
1951 True class labels.
1953 Returns
1954 -------
1955 dict[str, Any]
1956 Dictionary containing model summary.
1957 """
1958 summary = generate_model_metrics(eq_preds, test_y, label_order=model._label_order())
1959 summary["numTestExamples"] = get_num_examples_per_label(test_y)
1960 summary.update(model.train_summary) # union of train_summary and generated metrics
1962 return summary
1965def _mahalanobis_from_factor(x: torch.Tensor, factor: torch.Tensor) -> torch.Tensor:
1966 """``x^T C^{-1} x`` per column of ``x`` (classes, dim, examples), from ``C = L L^T``."""
1967 return torch.sum(torch.linalg.solve_triangular(factor, x, upper=False) ** 2, dim=1)
1970def _cholesky_with_jitter(cov: torch.Tensor) -> torch.Tensor:
1971 """
1972 Cholesky factors of a batch of covariance matrices, shape (classes, dim, dim).
1974 A matrix that factors as it is gets no jitter. A matrix whose factorization
1975 fails gets a diagonal jitter of machine epsilon times its largest variance,
1976 multiplied by 10 until the factorization succeeds, as long as the jitter
1977 stays at or below 1e-3 of that variance.
1979 Raises
1980 ------
1981 torch.linalg.LinAlgError
1982 If a matrix does not factor with the largest jitter (for example, one
1983 that holds NaN).
1984 """
1985 factor, info = torch.linalg.cholesky_ex(cov)
1986 failed = (info != 0) | ~torch.isfinite(factor).flatten(-2).all(-1)
1987 if not bool(failed.any()):
1988 return factor
1989 eps = torch.finfo(cov.dtype).eps
1990 largest = cov.detach().diagonal(dim1=-2, dim2=-1).amax(dim=-1)
1991 eye = torch.eye(cov.shape[-1], dtype=cov.dtype, device=cov.device)
1992 steps = int(math.log10(1e-3 / eps)) + 1
1993 jitter = torch.zeros_like(largest)
1994 for power in range(steps):
1995 jitter = torch.where(failed, eps * 10.0**power * largest, jitter)
1996 factor, info = torch.linalg.cholesky_ex(cov + jitter[:, None, None] * eye)
1997 failed = (info != 0) | ~torch.isfinite(factor).flatten(-2).all(-1)
1998 if not bool(failed.any()):
1999 return factor
2000 raise torch.linalg.LinAlgError( # type: ignore
2001 "A covariance matrix is not positive definite even with a diagonal "
2002 f"jitter of {eps * 10.0 ** (steps - 1):.1e} times its largest variance."
2003 )
2006@icontract.require(
2007 lambda cov: cov.dim() == 3, "cov must have shape (classes, dim, dim)"
2008)
2009@icontract.require(lambda cov: cov.shape[-2] == cov.shape[-1])
2010def mahalanobis_distance_nosq(x: torch.Tensor, cov: torch.Tensor) -> torch.Tensor:
2011 """
2012 Compute the squared Mahalanobis distance $x^T C^{-1} x$ (no square root).
2014 Computed as the squared norm of $L^{-1} x$, where $C = L L^T$ is the Cholesky
2015 factorization. The result is never negative, and the gradient is finite whenever $C$
2016 is positive definite, including when it has repeated eigenvalues.
2018 Parameters
2019 ----------
2020 x : torch.Tensor
2021 Vectors, shape ``(classes, dim, examples)``. A ``(dim, examples)`` or
2022 ``(dim,)`` tensor is used for every class.
2023 cov : torch.Tensor
2024 Symmetric positive-definite covariance matrices, shape
2025 ``(classes, dim, dim)``.
2027 Returns
2028 -------
2029 torch.Tensor
2030 Distances, shape ``(classes, examples)``, or ``(classes,)`` for a
2031 ``(dim,)`` input.
2033 Raises
2034 ------
2035 torch.linalg.LinAlgError
2036 If the Cholesky factorization of a covariance matrix fails. A singular
2037 matrix that rounding leaves positive definite gives very large
2038 distances instead, and a matrix that holds NaN gives NaN distances
2039 where the LAPACK build reports success for it (OpenBLAS does).
2040 """
2041 if x.dim() == 1:
2042 return mahalanobis_distance_nosq(x.unsqueeze(-1), cov).squeeze(-1)
2043 if x.dim() == 2:
2044 x = x.expand(cov.shape[0], -1, -1)
2045 return _mahalanobis_from_factor(x, torch.linalg.cholesky(cov))
2048@icontract.require(
2049 lambda X, Y: X.shape[0] == Y.shape[0],
2050 "X and Y must have the same number of samples.",
2051)
2052@icontract.require(
2053 lambda test_size: 0.0 < test_size < 1.0, "test_size must be between 0 and 1."
2054)
2055@icontract.ensure(
2056 lambda result: len(result) == 4, "Function must return four elements."
2057)
2058@icontract.ensure(
2059 lambda X, result: result[0].shape[0] + result[1].shape[0] == X.shape[0],
2060 "Total samples must be preserved.",
2061)
2062@icontract.ensure(
2063 lambda Y, result: result[2].shape[0] + result[3].shape[0] == Y.shape[0],
2064 "Total labels must be preserved.",
2065)
2066@icontract.ensure(
2067 lambda result: result[0].shape[0] == result[2].shape[0],
2068 "Train features and labels must match in size.",
2069)
2070@icontract.ensure(
2071 lambda result: result[1].shape[0] == result[3].shape[0],
2072 "Test features and labels must match in size.",
2073)
2074@beartype
2075def stratified_train_test_split(
2076 X: torch.Tensor, Y: torch.Tensor, test_size: float
2077) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
2078 """
2079 A pytorch-ified version of sklearn's train_test_split with data stratification
2081 Parameters
2082 ----------
2083 X : torch.Tensor
2084 Input features tensor of shape (n_samples, n_features).
2085 Y : torch.Tensor
2086 Labels tensor of shape (n_samples,).
2087 test_size : float
2088 Proportion of the dataset to include in the test split (between 0.0 and 1.0).
2090 Returns
2091 -------
2092 train_x : torch.Tensor
2093 Training set features.
2094 calib_x : torch.Tensor
2095 Test set features.
2096 train_y : torch.Tensor
2097 Training set labels.
2098 calib_y : torch.Tensor
2099 Test set labels.
2100 """
2101 unique_classes, class_counts = torch.unique(Y, return_counts=True)
2102 test_counts = (class_counts.float() * test_size).round().long()
2103 train_indices = []
2104 test_indices = []
2106 for cls, test_count in zip(unique_classes, test_counts):
2107 cls_indices = torch.where(Y == cls)[0]
2108 cls_indices = cls_indices[torch.randperm(len(cls_indices))]
2109 test_idx = cls_indices[:test_count]
2110 train_idx = cls_indices[test_count:]
2111 train_indices.append(train_idx)
2112 test_indices.append(test_idx)
2114 train_indices = torch.cat(train_indices)
2115 test_indices = torch.cat(test_indices)
2117 train_x = X[train_indices]
2118 train_y = Y[train_indices]
2119 calib_x = X[test_indices]
2120 calib_y = Y[test_indices]
2122 return train_x, calib_x, train_y, calib_y