Coverage for /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/equine/equine_protonet.py: 99%

458 statements  

« 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 

4from __future__ import annotations 

5 

6import sys 

7import warnings 

8from collections import OrderedDict 

9from collections.abc import Callable 

10from datetime import datetime 

11from enum import Enum 

12from typing import Any, Self, cast 

13 

14import icontract 

15import numpy as np 

16import torch 

17from beartype import beartype 

18from scipy.stats import gaussian_kde 

19from torch.utils.data import TensorDataset 

20from tqdm import tqdm 

21 

22from .equine import Equine, EquineOutput, _apply_to_stored_tensors, _eval_mode 

23from .registry import _describe_error, _positive_int, _truncate 

24from .utils import ( 

25 _OOD_DISTANCES, 

26 EQUINE_FORMAT_VERSION, 

27 _checked_settings, 

28 _cholesky_with_jitter, 

29 _embedding_checkpoint, 

30 _get_shuffle_idxs_by_class, 

31 _input_to_model, 

32 _label_text, 

33 _labels_to_columns, 

34 _load_checkpoint_for_device, 

35 _mahalanobis_from_factor, 

36 _outlier_kde_from_file, 

37 _plain_names, 

38 _plain_train_summary, 

39 _rebuild_embedding, 

40 _refuse_torchscript, 

41 _require_device, 

42 _require_entries, 

43 _require_examples, 

44 _require_finite_embeddings, 

45 _require_matching_weights, 

46 _require_names, 

47 _shown, 

48 _support_from_file, 

49 generate_episode, 

50 generate_support, 

51 generate_train_summary, 

52 stratified_train_test_split, 

53) 

54 

55 

56##################################### 

57class CovType(Enum): 

58 """ 

59 Enum class for covariance types used in EQUINE. 

60 """ 

61 

62 UNIT = "unit" 

63 DIAGONAL = "diag" 

64 FULL = "full" 

65 

66 

67PRED_COV_TYPE = CovType.DIAGONAL 

68OOD_COV_TYPE = CovType.DIAGONAL 

69DEFAULT_EPSILON = 1e-5 

70 

71 

72def _kde_to_state(kde: gaussian_kde) -> dict[str, Any]: 

73 """Reduce a fitted ``gaussian_kde`` to tensors/scalars for safe saving.""" 

74 return { 

75 "dataset": torch.as_tensor(kde.dataset).clone(), 

76 "bw_factor": float(cast(float, kde.factor)), 

77 } 

78 

79 

80COV_REG_TYPE = "epsilon" 

81 

82 

83############################################### 

84 

85 

86@beartype 

87class Protonet(torch.nn.Module): 

88 """ 

89 Private class that implements a prototypical neural network for use in EQUINE. 

90 """ 

91 

92 def __init__( 

93 self, 

94 embedding_model: torch.nn.Module, 

95 emb_out_dim: int, 

96 cov_type: CovType, 

97 cov_reg_type: str, 

98 epsilon: float, 

99 device: str = "cpu", 

100 ) -> None: 

101 """ 

102 Protonet class constructor. 

103 

104 Parameters 

105 ---------- 

106 embedding_model : torch.nn.Module 

107 The PyTorch embedding model to generate logits with. 

108 emb_out_dim : int 

109 Dimension size of given embedding model's output. 

110 cov_type : CovType 

111 Type of covariance to use when computing distances [unit, diag, full]. 

112 cov_reg_type : str 

113 Type of regularization to use when generating the covariance matrix [epsilon, shared]. 

114 epsilon : float 

115 Epsilon value to use for covariance regularization. 

116 device : str, optional 

117 The device to train the protonet model on (defaults to cpu). 

118 """ 

119 super().__init__() 

120 self.embedding_model = embedding_model 

121 self.cov_type = cov_type 

122 self.cov_reg_type = cov_reg_type 

123 self.epsilon = epsilon 

124 self.emb_out_dim = emb_out_dim 

125 self.to(device) 

126 self.device = device 

127 

128 self.support: OrderedDict[int, torch.Tensor] = OrderedDict() 

129 self.support_embeddings: OrderedDict[int, torch.Tensor] = OrderedDict() 

130 self.model_head: torch.nn.Module = self.create_model_head(emb_out_dim) 

131 self.model_head.to(device) 

132 

133 def _apply( 

134 self, fn: Callable[[torch.Tensor], torch.Tensor], recurse: bool = True 

135 ) -> Protonet: 

136 """ 

137 ``nn.Module._apply``, extended to the support, its embeddings, the prototypes and the covariances. 

138 

139 ``to``, ``cpu``, ``cuda`` and the dtype casts call it. Moving the model moves 

140 every tensor the Protonet keeps and updates its ``device`` (see 

141 ``equine._apply_to_stored_tensors``). 

142 """ 

143 super()._apply(fn, recurse) 

144 _apply_to_stored_tensors(self, fn, recurse) 

145 return self 

146 

147 def create_model_head(self, emb_out_dim: int) -> torch.nn.Identity: 

148 """ 

149 Method for adding a PyTorch layer on top of the given embedding model. This layer 

150 is intended to offer extra degrees of freedom for distance learning in the embedding space. 

151 

152 Parameters 

153 ---------- 

154 emb_out_dim : int 

155 Dimension size of the embedding model output. 

156 

157 Returns 

158 ------- 

159 torch.nn.Identity 

160 The model head: an identity layer. 

161 """ 

162 return torch.nn.Identity() # (emb_out_dim, emb_out_dim) 

163 

164 def compute_embeddings(self, X: torch.Tensor) -> torch.Tensor: 

165 """ 

166 Method for calculating model embeddings using both the given embedding model and the added model head. 

167 

168 Parameters 

169 ---------- 

170 X : torch.Tensor 

171 Input tensor to compute embeddings on. 

172 

173 Returns 

174 ------- 

175 torch.Tensor 

176 Fully computed embedding tensors for the given X tensor. 

177 """ 

178 X = _input_to_model(X, self.embedding_model, self.device) 

179 model_embeddings = self.embedding_model(X) 

180 head_embeddings = self.model_head(model_embeddings) 

181 return head_embeddings 

182 

183 @icontract.require(lambda self: len(self.support_embeddings) > 0) 

184 def compute_prototypes(self) -> torch.Tensor: 

185 """ 

186 Method for computing class prototypes based on given support examples. 

187 ``Prototypes'' in this context are the means of the support embeddings for each class. 

188 

189 Returns 

190 ------- 

191 torch.Tensor 

192 Tensors of prototypes for each of the given classes in the support. 

193 """ 

194 # Compute prototype for each class 

195 proto_list = [] 

196 for label in self.support_embeddings: # look at doing functorch 

197 class_prototype = torch.mean(self.support_embeddings[label], dim=0) 

198 proto_list.append(class_prototype) 

199 

200 prototypes = torch.stack(proto_list) 

201 

202 return prototypes 

203 

204 @icontract.require(lambda self: len(self.support_embeddings) > 0) 

205 def compute_covariance(self, cov_type: CovType) -> torch.Tensor: 

206 """ 

207 Method for generating the (regularized) support example covariance matrix(es) used for calculating distances. 

208 Note that this method is only called once per episode, and the resulting tensor is used for all queries. 

209 

210 Parameters 

211 ---------- 

212 cov_type : CovType 

213 Type of covariance to use [unit, diag, full]. 

214 

215 Returns 

216 ------- 

217 torch.Tensor 

218 Tensor containing the generated regularized covariance matrix. 

219 """ 

220 class_cov_dict = OrderedDict().fromkeys( 

221 self.support_embeddings.keys(), torch.Tensor() 

222 ) 

223 for label in self.support_embeddings.keys(): 

224 class_covariance = self.compute_covariance_by_type( 

225 cov_type, self.support_embeddings[label] 

226 ) 

227 class_cov_dict[label] = class_covariance 

228 

229 reg_covariance_dict = self.regularize_covariance( 

230 class_cov_dict, cov_type, self.cov_reg_type 

231 ) 

232 reg_covariance = torch.stack(list(reg_covariance_dict.values())) 

233 

234 return reg_covariance # TODO try putting everything on GPU with .to() and see if faster 

235 

236 def compute_covariance_by_type( 

237 self, cov_type: CovType, embedding: torch.Tensor 

238 ) -> torch.Tensor: 

239 """ 

240 Select the appropriate covariance matrix type based on cov_type. 

241 

242 Parameters 

243 ---------- 

244 cov_type : CovType 

245 Type of covariance to use. Options are ['unit', 'diag', 'full']. 

246 embedding : torch.Tensor 

247 Embedding tensor to use when generating the covariance matrix. 

248 

249 Returns 

250 ------- 

251 torch.Tensor 

252 Tensor containing the requested covariance matrix. 

253 

254 Raises 

255 ------ 

256 ValueError 

257 If ``cov_type`` is ``FULL`` or ``DIAGONAL`` and ``embedding`` has 

258 fewer than 2 rows. 

259 """ 

260 if cov_type in (CovType.FULL, CovType.DIAGONAL) and embedding.shape[0] < 2: 

261 raise ValueError( 

262 f"A {cov_type.value!r} covariance needs at least 2 examples per " 

263 f"class; got {embedding.shape[0]}." 

264 ) 

265 if cov_type == CovType.FULL: 

266 class_covariance = torch.cov(embedding.T) 

267 elif cov_type == CovType.DIAGONAL: 

268 class_covariance = torch.var(embedding, dim=0) 

269 elif cov_type == CovType.UNIT: 269 ↛ 272line 269 didn't jump to line 272 because the condition on line 269 was always true

270 class_covariance = torch.ones(self.emb_out_dim, device=self.device) 

271 else: 

272 raise ValueError 

273 

274 return class_covariance 

275 

276 def regularize_covariance( 

277 self, 

278 class_cov_dict: OrderedDict[int, torch.Tensor], 

279 cov_type: CovType, 

280 cov_reg_type: str, 

281 ) -> OrderedDict[int, torch.Tensor]: 

282 """ 

283 Method to add regularization to each class covariance matrix based on the selected regularization type. 

284 

285 Parameters 

286 ---------- 

287 class_cov_dict : OrderedDict[int, torch.Tensor] 

288 A dictionary containing each class and the corresponding covariance matrix. 

289 cov_type : CovType 

290 Type of covariance to use [unit, diag, full]. 

291 cov_reg_type : str 

292 Regularization type: ``"epsilon"`` or ``"shared"``. 

293 

294 Returns 

295 ------- 

296 OrderedDict[int, torch.Tensor] 

297 Dictionary containing the regularized class covariance matrices. 

298 """ 

299 

300 if cov_type == CovType.FULL: 

301 regularization = torch.diag(self.epsilon * torch.ones(self.emb_out_dim)).to( 

302 self.device 

303 ) 

304 elif cov_type == CovType.DIAGONAL: 

305 regularization = self.epsilon * torch.ones(self.emb_out_dim).to(self.device) 

306 elif cov_type == CovType.UNIT: 306 ↛ 309line 306 didn't jump to line 309 because the condition on line 306 was always true

307 regularization = torch.zeros(self.emb_out_dim).to(self.device) 

308 

309 if cov_reg_type == "shared": 

310 if cov_type != CovType.FULL and cov_type != CovType.DIAGONAL: 

311 for label in self.support_embeddings: 

312 class_cov_dict[label] = class_cov_dict[label] + regularization 

313 warnings.warn( 

314 "Covariance type UNIT is incompatible with shared regularization, \ 

315 reverting to epsilon regularization" 

316 ) 

317 return class_cov_dict 

318 

319 shared_covariance = self.compute_shared_covariance(class_cov_dict, cov_type) 

320 

321 for label in self.support_embeddings: 

322 num_class_support = self.support_embeddings[label].shape[0] 

323 lamb = num_class_support / (num_class_support + 1) 

324 

325 class_cov_dict[label] = ( 

326 lamb * class_cov_dict[label] 

327 + (1 - lamb) * shared_covariance 

328 + regularization 

329 ) 

330 

331 elif cov_reg_type == "epsilon": 331 ↛ 337line 331 didn't jump to line 337 because the condition on line 331 was always true

332 for label in class_cov_dict.keys(): 

333 class_cov_dict[label] = ( 

334 class_cov_dict[label].to(self.device) + regularization 

335 ) 

336 

337 return class_cov_dict 

338 

339 def compute_shared_covariance( 

340 self, class_cov_dict: OrderedDict[int, torch.Tensor], cov_type: CovType 

341 ) -> torch.Tensor: 

342 """ 

343 Method to calculate a shared covariance matrix. 

344 

345 The shared covariance matrix is calculated as the weighted average of the class covariance matrices, 

346 where the weights are the number of support examples for each class. This is useful when the number of 

347 support examples for each class is small. 

348 

349 Parameters 

350 ---------- 

351 class_cov_dict : OrderedDict[int, torch.Tensor] 

352 A dictionary containing each class and the corresponding covariance matrix. 

353 cov_type : CovType 

354 Type of covariance to use [unit, diag, full]. 

355 

356 Returns 

357 ------- 

358 torch.Tensor 

359 Tensor containing the shared covariance matrix. 

360 """ 

361 total_support = sum([x.shape[0] for x in class_cov_dict.values()]) 

362 

363 if cov_type == CovType.FULL: 

364 shared_covariance = torch.zeros( 

365 (self.emb_out_dim, self.emb_out_dim), device=self.device 

366 ) 

367 elif cov_type == CovType.DIAGONAL: 

368 shared_covariance = torch.zeros(self.emb_out_dim, device=self.device) 

369 else: 

370 raise ValueError( 

371 "Shared covariance can only be used with FULL or DIAGONAL (not UNIT) covariance types" 

372 ) 

373 

374 for label in class_cov_dict: 

375 num_class_support = class_cov_dict[label].shape[0] 

376 shared_covariance = ( 

377 shared_covariance + (num_class_support - 1) * class_cov_dict[label] 

378 ) # undo N-1 div from cov 

379 

380 shared_covariance = shared_covariance / ( 

381 total_support - 1 

382 ) # redo N-1 div for shared cov 

383 

384 return shared_covariance 

385 

386 @icontract.require(lambda X_embed, mu: X_embed.shape[-1] == mu.shape[-1]) 

387 @icontract.ensure(lambda result: torch.all(result >= 0)) 

388 def compute_distance( 

389 self, X_embed: torch.Tensor, mu: torch.Tensor, cov: torch.Tensor 

390 ) -> torch.Tensor: 

391 """ 

392 Method to compute the distances to class prototypes for the given embeddings. 

393 

394 Parameters 

395 ---------- 

396 X_embed : torch.Tensor 

397 The embeddings of the query examples. 

398 mu : torch.Tensor 

399 The class prototypes (means of the support embeddings). 

400 cov : torch.Tensor 

401 The support covariance matrix. 

402 

403 Returns 

404 ------- 

405 torch.Tensor 

406 The calculated distances from each of the class prototypes for the given embeddings. 

407 """ 

408 _queries = torch.unsqueeze(X_embed, 1) # examples x 1 x dimension 

409 diff = torch.sub(mu, _queries) 

410 

411 if len(cov.shape) == 2: # (diagonal covariance) 

412 # examples x classes x dimension 

413 sq_diff = diff**2 

414 dist = torch.div(sq_diff.to(self.device), cov.to(self.device)) 

415 dist = torch.sum(dist, dim=2) # examples x classes 

416 dist = dist.squeeze(dim=1) 

417 dist = torch.sqrt(dist + self.epsilon) # examples x classes 

418 else: # len(cov.shape) == 3: (full covariance) 

419 diff = diff.permute(1, 2, 0) # classes x dimension x examples 

420 dist = _mahalanobis_from_factor(diff, _cholesky_with_jitter(cov)) 

421 dist = torch.sqrt(dist.permute(1, 0) + self.epsilon) # examples x classes 

422 dist = dist.squeeze(dim=1) 

423 return dist 

424 

425 def compute_classes(self, distances: torch.Tensor) -> torch.Tensor: 

426 """ 

427 Method to compute predicted classes from distances via a softmax function. 

428 

429 Parameters 

430 ---------- 

431 distances : torch.Tensor 

432 The distances of embeddings to class prototypes. 

433 

434 Returns 

435 ------- 

436 torch.Tensor 

437 Class probabilities: the softmax of the negated distances. 

438 """ 

439 softmax = torch.nn.functional.softmax(torch.neg(distances), dim=-1) 

440 return softmax 

441 

442 def forward(self, X: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]: 

443 """ 

444 Protonet forward function, generates class probability predictions and distances from prototypes. 

445 

446 Parameters 

447 ---------- 

448 X : torch.Tensor 

449 Input tensor of queries for generating predictions. 

450 

451 Returns 

452 ------- 

453 tuple[torch.Tensor, torch.Tensor] 

454 tuple containing class probability predictions, and class distances from prototypes. 

455 

456 Raises 

457 ------ 

458 ValueError 

459 If the model has no support, or, in eval mode, the embeddings of 

460 ``X`` hold a NaN or infinite value. 

461 """ 

462 classes, distances, _ = self._forward_with_embeddings(X) 

463 return classes, distances 

464 

465 def _forward_with_embeddings( 

466 self, X: torch.Tensor 

467 ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: 

468 """ 

469 ``forward`` that also returns the embeddings it computed. 

470 

471 Returns 

472 ------- 

473 tuple[torch.Tensor, torch.Tensor, torch.Tensor] 

474 Class probability predictions, class distances from prototypes, 

475 and the embeddings (``compute_embeddings(X)``, single examples 

476 unsqueezed to a batch of one). 

477 

478 Raises 

479 ------ 

480 ValueError 

481 If the model has no support, or, in eval mode, the embeddings of 

482 ``X`` hold a NaN or infinite value. 

483 """ 

484 if len(self.support) == 0 or len(self.support_embeddings) == 0: 

485 raise ValueError( 

486 "No support examples found. Protonet Model requires model support to \ 

487 be set with the 'update_support()' method before calling forward." 

488 ) 

489 

490 X_embed = self.compute_embeddings(X) 

491 if X_embed.shape == torch.Size([self.emb_out_dim]): 

492 X_embed = X_embed.unsqueeze(dim=0) # handle single examples 

493 if not self.training: 

494 _require_finite_embeddings(X_embed) 

495 distances = self.compute_distance(X_embed, self.prototypes, self.covariance) 

496 classes = self.compute_classes(distances) 

497 

498 return classes, distances, X_embed 

499 

500 def update_support( 

501 self, 

502 support: OrderedDict[int, torch.Tensor], 

503 *, 

504 _global_moments: bool = True, 

505 ) -> None: 

506 """ 

507 Method to update the support examples, and all the calculations that rely on them. 

508 

509 The global moments of the support embeddings (used for the OOD score) 

510 are computed whatever mode the caller left the model in (via 

511 ``train()``/``eval()``). The covariance type depends on the 

512 mode: ``PRED_COV_TYPE`` in eval mode, ``cov_type`` in training mode. 

513 

514 Parameters 

515 ---------- 

516 support : OrderedDict 

517 Ordered dict containing class labels and their associated support examples. 

518 _global_moments : bool, optional 

519 Private, keyword-only. False skips the global moments; only the episode loop 

520 of ``EquineProtonet.train_model`` passes it. 

521 """ 

522 # Through the model boundary: on the device and, for floating support, in the 

523 # embedding's dtype. 

524 self.support = OrderedDict( 

525 (label, _input_to_model(x, self.embedding_model, self.device)) 

526 for label, x in support.items() 

527 ) # TODO torch.nn.ParameterDict(support) 

528 

529 support_embs = OrderedDict().fromkeys(support.keys(), torch.Tensor()) 

530 for label in self.support: 

531 support_embs[label] = self.compute_embeddings(self.support[label]) 

532 

533 self.support_embeddings = ( 

534 support_embs # TODO torch.nn.ParameterDict(support_embs) 

535 ) 

536 

537 self.prototypes: torch.Tensor = self.compute_prototypes() 

538 if _global_moments: 

539 self.compute_global_moments() 

540 

541 if self.training is False: 

542 self.covariance: torch.Tensor = self.compute_covariance( 

543 cov_type=PRED_COV_TYPE 

544 ) 

545 else: 

546 self.covariance: torch.Tensor = self.compute_covariance( 

547 cov_type=self.cov_type 

548 ) 

549 

550 @icontract.require(lambda self: len(self.support_embeddings) > 0) 

551 def compute_global_moments(self) -> None: 

552 """Method to calculate the global moments of the support embeddings for use in OOD score generation""" 

553 embeddings = torch.cat(list(self.support_embeddings.values())) 

554 self.global_covariance = torch.unsqueeze( 

555 self.compute_covariance_by_type(OOD_COV_TYPE, embeddings), dim=0 

556 ) 

557 global_reg_input = OrderedDict().fromkeys([0], torch.Tensor()) 

558 global_reg_input[0] = self.global_covariance 

559 self.global_covariance: torch.Tensor = self.regularize_covariance( 

560 global_reg_input, OOD_COV_TYPE, "epsilon" 

561 )[0] 

562 self.global_mean: torch.Tensor = torch.mean(embeddings, dim=0) 

563 

564 

565def _require_examples_per_class( 

566 y: torch.Tensor, labels: list[int], part: str, minimum: int 

567) -> None: 

568 """ 

569 Refuse a ``calib_frac`` split that leaves a class with too few examples. 

570 

571 Parameters 

572 ---------- 

573 y : torch.Tensor 

574 Labels of one side of the split. 

575 labels : list[int] 

576 Every class the model is given. 

577 part : str 

578 The side of the split, named in the message. 

579 minimum : int 

580 The fewest examples each class needs on this side. 

581 

582 Raises 

583 ------ 

584 ValueError 

585 If a class in ``labels`` has fewer than ``minimum`` examples in ``y``. 

586 """ 

587 for label in labels: 

588 count = int((y == label).sum()) 

589 if count < minimum: 

590 raise ValueError( 

591 f"Class {_label_text(label)} has {count} {part} example(s) after the " 

592 f"calib_frac split; it needs at least {minimum}." 

593 ) 

594 

595 

596############################################### 

597@beartype 

598class EquineProtonet(Equine): 

599 """ 

600 A class representing an EQUINE model that utilizes protonets and (optionally) relative Mahalanobis distances 

601 to generate OOD and model confidence scores. This wraps any pytorch embedding neural network 

602 and provides the `forward`, `predict`, `save`, and `load` methods required by Equine. 

603 """ 

604 

605 def __init__( 

606 self, 

607 embedding_model: torch.nn.Module, 

608 emb_out_dim: int, 

609 cov_type: CovType = CovType.UNIT, 

610 relative_mahal: bool = True, 

611 use_temperature: bool = False, 

612 init_temperature: float = 1.0, 

613 device: str = "cpu", 

614 feature_names: list[str] | None = None, 

615 label_names: list[str] | None = None, 

616 ood_distance: str = "rmd_sq", 

617 ) -> None: 

618 """ 

619 EquineProtonet class constructor 

620 

621 Parameters 

622 ---------- 

623 embedding_model : torch.nn.Module 

624 Neural Network feature embedding model. 

625 emb_out_dim : int 

626 The number of output features from the embedding model. 

627 cov_type : CovType, optional 

628 The type of covariance to use when training the protonet [UNIT, DIAG, FULL], by default CovType.UNIT. 

629 relative_mahal : bool, optional 

630 Use relative mahalanobis distance for OOD calculations. If false, uses standard mahalanobis distance instead, by default True. 

631 use_temperature : bool, optional 

632 Whether to use temperature scaling after training, by default False. 

633 init_temperature : float, optional 

634 What to use as the initial temperature (1.0 has no effect), by default 1.0. 

635 device : str, optional 

636 The device to train the equine model on (defaults to cpu). 

637 feature_names : list[str], optional 

638 List of strings of the names of the tabular features (ex ["duration", "fiat_mean", ...]) 

639 label_names : list[str], optional 

640 List of strings of the names of the labels (ex ["streaming", "voip", ...]) 

641 ood_distance : str, optional 

642 The OOD statistic used when ``relative_mahal`` is True, by default 

643 ``"rmd_sq"``: the squared Mahalanobis distance to the predicted class 

644 prototype minus the squared Mahalanobis distance to the mean of the 

645 support embeddings, both computed without the temperature. 

646 ``"rmd_sqrt"`` subtracts the distances themselves, and with 

647 ``use_temperature`` divides the class distance by the temperature 

648 first. A model file without this setting loads as ``"rmd_sqrt"``. 

649 The outlier-score KDEs are fitted for the statistic in use: after 

650 changing ``ood_distance``, refit them with ``update_support`` or 

651 ``train_model``. 

652 

653 Raises 

654 ------ 

655 ValueError 

656 If ``ood_distance`` is not ``"rmd_sq"`` or ``"rmd_sqrt"``. 

657 """ 

658 if ood_distance not in _OOD_DISTANCES: 

659 raise ValueError( 

660 f"ood_distance must be one of {list(_OOD_DISTANCES)}; got " 

661 f"{_shown(ood_distance)}." 

662 ) 

663 super().__init__( 

664 embedding_model, 

665 device=device, 

666 feature_names=feature_names, 

667 label_names=label_names, 

668 ) 

669 self.cov_type = cov_type 

670 self.cov_reg_type = COV_REG_TYPE 

671 self.relative_mahal = relative_mahal 

672 self.ood_distance = ood_distance 

673 self.emb_out_dim = emb_out_dim 

674 self.epsilon = DEFAULT_EPSILON 

675 self.outlier_score_kde: OrderedDict[int, gaussian_kde] = OrderedDict() 

676 self.model_summary: dict[str, Any] = dict() 

677 self.use_temperature = use_temperature 

678 self.init_temperature = init_temperature 

679 self.register_buffer( 

680 "temperature", torch.Tensor(self.init_temperature * torch.ones(1)) 

681 ) 

682 

683 self.model: Protonet = Protonet( 

684 embedding_model, 

685 self.emb_out_dim, 

686 self.cov_type, 

687 self.cov_reg_type, 

688 self.epsilon, 

689 device=device, 

690 ) 

691 # Moves the temperature buffer onto the model's device. 

692 self.to(self.device) 

693 

694 @property 

695 def support(self) -> OrderedDict[int, torch.Tensor]: 

696 """ 

697 The support examples of each class, keyed by label: the dict that 

698 ``get_support()`` returns, empty before the first support update. 

699 Read-only. 

700 """ 

701 return self.model.support 

702 

703 @property 

704 def support_embeddings(self) -> OrderedDict[int, torch.Tensor]: 

705 """ 

706 The embeddings of the support examples, keyed by label; empty before the 

707 first support update. Read-only. 

708 """ 

709 return self.model.support_embeddings 

710 

711 @property 

712 def prototypes(self) -> torch.Tensor: 

713 """ 

714 The class prototypes: the tensor that ``get_prototypes()`` returns, an 

715 empty tensor before the first support update. Read-only. 

716 """ 

717 return self.model.__dict__.get("prototypes", torch.Tensor()) 

718 

719 def __setstate__(self, state: dict[str, Any]) -> None: 

720 """ 

721 Restore a pickled model; a pickle without ``ood_distance`` uses 

722 ``"rmd_sqrt"``. ``support``, ``support_embeddings`` and ``prototypes`` 

723 entries in its instance dict are dropped: these names are read-only 

724 properties. 

725 """ 

726 state.setdefault("ood_distance", "rmd_sqrt") 

727 for name in ("support", "support_embeddings", "prototypes"): 

728 state.pop(name, None) 

729 super().__setstate__(state) 

730 

731 def forward(self, X: torch.Tensor) -> torch.Tensor: 

732 """ 

733 Generates class probabilities based on the input tensor. 

734 

735 Parameters 

736 ---------- 

737 X : torch.Tensor 

738 The input tensor for generating predictions. 

739 

740 Returns 

741 ------- 

742 torch.Tensor 

743 Class probabilities: the softmax of the negated distances to the 

744 class prototypes. 

745 

746 Raises 

747 ------ 

748 ValueError 

749 If the model has no support, or, in eval mode, the embeddings of 

750 ``X`` hold a NaN or infinite value. 

751 """ 

752 preds, _ = self.model(X) 

753 return preds 

754 

755 @icontract.require(lambda calib_frac: calib_frac > 0 and calib_frac < 1) 

756 def train_model( 

757 self, 

758 dataset: TensorDataset, 

759 num_episodes: int, 

760 calib_frac: float = 0.2, 

761 support_size: int = 25, 

762 way: int = 3, 

763 episode_size: int = 100, 

764 loss_fn: Callable = torch.nn.functional.cross_entropy, 

765 opt_class: Callable = torch.optim.Adam, 

766 num_calibration_epochs: int = 2, 

767 calibration_lr: float = 0.01, 

768 ) -> dict[str, Any]: 

769 """ 

770 Train or fine-tune an EquineProtonet model. 

771 

772 Parameters 

773 ---------- 

774 dataset : TensorDataset 

775 Input pytorch TensorDataset of training data for model, with at least 

776 2 classes. 

777 num_episodes : int 

778 The desired number of episodes to use for training. 

779 calib_frac : float, optional 

780 Fraction of given training data to reserve for model calibration, by default 0.2. 

781 support_size : int, optional 

782 Number of support examples to generate for each class, by default 25. 

783 way : int, optional 

784 Number of classes to train on per episode, from 2 to the number of 

785 classes in ``dataset`` when ``num_episodes`` is positive, by default 3. 

786 episode_size : int, optional 

787 Upper bound on the number of query examples per episode, each class 

788 contributing up to ``episode_size // way``; at least ``way`` when 

789 ``num_episodes`` is positive, by default 100. 

790 loss_fn : Callable, optional 

791 A pytorch loss function, eg., torch.nn.CrossEntropyLoss(), by default torch.nn.functional.cross_entropy. 

792 opt_class : Callable, optional 

793 A pytorch optimizer, e.g., torch.optim.Adam, by default torch.optim.Adam. 

794 num_calibration_epochs : int, optional 

795 The desired number of epochs to use for temperature scaling, by default 2. 

796 calibration_lr : float, optional 

797 Learning rate for temperature scaling, by default 0.01. 

798 

799 Returns 

800 ------- 

801 dict[str, Any] 

802 ``"train_summary"``: the training summary (also kept as 

803 ``self.train_summary``); ``"calib_x"`` and ``"calib_y"``: the held 

804 out calibration data and labels as split from ``dataset`` (on its 

805 device and in its dtypes; the copies moved to the model device are 

806 internal). 

807 

808 Raises 

809 ------ 

810 ValueError 

811 If ``support_size`` is below 2 or ``dataset`` has fewer than 2 

812 classes; if ``num_episodes`` is positive and ``way`` is not between 2 

813 and the number of classes, or 

814 ``episode_size`` is below ``way``; or if the ``calib_frac`` split leaves a 

815 class with fewer than 2 calibration examples or too few training 

816 examples (more than ``support_size`` when ``num_episodes`` is 

817 positive, ``support_size`` otherwise); the model is then unchanged. Also, after 

818 training, if a calibration example's embedding or OOD distance holds 

819 a NaN or infinite value, or a class's calibration examples all have 

820 the same OOD distance; the model is then trained but its outlier 

821 scores are not refitted. 

822 """ 

823 if support_size < 2: 

824 raise ValueError( 

825 f"support_size must be at least 2, got {support_size}: the support's " 

826 "diagonal covariance needs 2 examples per class." 

827 ) 

828 X, Y = dataset[:] 

829 labels = torch.unique(Y).tolist() 

830 if len(labels) < 2: 

831 raise ValueError( 

832 f"dataset must hold at least 2 classes, got {len(labels)}." 

833 ) 

834 if num_episodes > 0: 

835 if not 2 <= way <= len(labels): 

836 raise ValueError( 

837 f"way must be between 2 and the number of classes ({len(labels)}) " 

838 f"when num_episodes is positive, got {way}." 

839 ) 

840 if episode_size < way: 

841 raise ValueError( 

842 f"episode_size must be at least way ({way}) when num_episodes " 

843 f"is positive, got {episode_size}." 

844 ) 

845 

846 self.validate_feature_label_names(X.shape[-1], len(labels)) 

847 

848 train_x, calib_x, train_y, calib_y = stratified_train_test_split( 

849 X, Y, test_size=calib_frac 

850 ) 

851 episode_queries = 1 if num_episodes > 0 else 0 

852 _require_examples_per_class( 

853 train_y, labels, "training", support_size + episode_queries 

854 ) 

855 _require_examples_per_class(calib_y, labels, "calibration", 2) 

856 

857 self.train() 

858 

859 if self.use_temperature: 

860 # Rounded through the default dtype, then widened to the buffer's dtype. 

861 self.temperature: torch.Tensor = torch.full( 

862 (1,), self.init_temperature, device=self.temperature.device 

863 ).to(self.temperature.dtype) 

864 

865 optimizer = opt_class(self.parameters()) 

866 

867 # Episodes and the support are sampled from train_x/train_y on the 

868 # dataset's device and cross to self.device at the model boundary. The 

869 # model uses the calibration split on self.device; the caller's is returned. 

870 model_calib_x = _input_to_model(calib_x, self.embedding_model, self.device) 

871 model_calib_y = calib_y.to(self.device) 

872 

873 for i in tqdm(range(num_episodes)): 

874 optimizer.zero_grad() 

875 

876 support, episode_x, episode_y = generate_episode( 

877 train_x, train_y, support_size, way, episode_size 

878 ) 

879 # Episodes read only the prototypes and the covariance; the 

880 # global moments are computed by the full-support update below. 

881 self.model.update_support(support, _global_moments=False) 

882 

883 _, dists = self.model(episode_x) 

884 loss_value = loss_fn( 

885 torch.neg(dists).to(self.device), episode_y.to(self.device) 

886 ) 

887 loss_value.backward() 

888 optimizer.step() 

889 

890 self.eval() 

891 full_support = generate_support( 

892 train_x, 

893 train_y, 

894 support_size, 

895 selected_labels=torch.unique(train_y).tolist(), 

896 ) 

897 

898 # Embedded without autograd: the result carries no graph. 

899 with torch.no_grad(): 

900 self.model.update_support( 

901 full_support 

902 ) # update support with final selected examples 

903 

904 # The OOD-calibration pass records no autograd graph. 

905 with torch.no_grad(): 

906 pred_probs, dists, X_embed = self.model._forward_with_embeddings( 

907 model_calib_x 

908 ) 

909 ood_dists = self._compute_ood_dist(X_embed, pred_probs, dists) 

910 self._fit_outlier_scores(ood_dists, model_calib_y) 

911 

912 if self.use_temperature: 

913 self.calibrate_temperature( 

914 model_calib_x, model_calib_y, num_calibration_epochs, calibration_lr 

915 ) 

916 

917 date_trained = datetime.now().strftime("%m/%d/%Y, %H:%M:%S") 

918 self.train_summary: dict[str, Any] = generate_train_summary( 

919 self, train_y, date_trained 

920 ) 

921 return_dict: dict[str, Any] = dict() 

922 return_dict["train_summary"] = self.train_summary 

923 return_dict["calib_x"] = calib_x 

924 return_dict["calib_y"] = calib_y 

925 return return_dict 

926 

927 def calibrate_temperature( 

928 self, 

929 calib_x: torch.Tensor, 

930 calib_y: torch.Tensor, 

931 num_calibration_epochs: int = 1, 

932 calibration_lr: float = 0.01, 

933 ) -> None: 

934 """ 

935 Fine-tune the temperature on the given examples. ``train_model`` calls this 

936 method when ``use_temperature`` is True. 

937 

938 Parameters 

939 ---------- 

940 calib_x : torch.Tensor 

941 Training data to be used for temperature calibration. 

942 calib_y : torch.Tensor 

943 Class labels corresponding to `calib_x`, each one of the support's 

944 labels. 

945 num_calibration_epochs : int, optional 

946 Number of epochs to tune temperature, by default 1. 

947 calibration_lr : float, optional 

948 Learning rate for temperature optimization, by default 0.01. 

949 

950 Returns 

951 ------- 

952 None 

953 

954 Raises 

955 ------ 

956 ValueError 

957 If the model has no support, `calib_y` holds a label that is not in 

958 the support, or, in eval mode, the embeddings of ``calib_x`` hold a 

959 NaN or infinite value. 

960 """ 

961 if len(self.model.support) == 0: 

962 raise ValueError( 

963 "No support examples found; call train_model or update_support " 

964 "before calibrate_temperature." 

965 ) 

966 targets = _labels_to_columns(calib_y, self._label_order()).to(self.device) 

967 self.temperature.requires_grad = True 

968 optimizer = torch.optim.Adam([self.temperature], lr=calibration_lr) 

969 for t in range(num_calibration_epochs): 

970 optimizer.zero_grad() 

971 with torch.no_grad(): 

972 pred_probs, dists = self.model(calib_x) 

973 dists = dists.to(self.device) / self.temperature.to(self.device) 

974 loss = torch.nn.functional.cross_entropy( 

975 torch.neg(dists).to(self.device), targets 

976 ) 

977 loss.backward() 

978 optimizer.step() 

979 self.temperature.requires_grad = False 

980 

981 @icontract.ensure(lambda self: len(self.model.support_embeddings) > 0) 

982 def _fit_outlier_scores( 

983 self, ood_dists: torch.Tensor, calib_y: torch.Tensor 

984 ) -> None: 

985 """ 

986 Private function to fit outlier scores with a kernel density estimate (KDE). 

987 

988 Replaces ``outlier_score_kde`` with one KDE per support label, keyed 

989 by label, in support order. 

990 

991 Parameters 

992 ---------- 

993 ood_dists : torch.Tensor 

994 Tensor of computed OOD distances. 

995 calib_y : torch.Tensor 

996 Tensor of class labels for `ood_dists` examples. Every class needs 

997 at least 2 examples. 

998 

999 Returns 

1000 ------- 

1001 None 

1002 

1003 Raises 

1004 ------ 

1005 ValueError 

1006 If a class's OOD distances include a NaN or infinite value or are all 

1007 equal, or fitting a KDE fails; no KDE is changed then. 

1008 """ 

1009 class_ood_dists = OrderedDict( 

1010 (label, ood_dists[calib_y == int(label)]) 

1011 for label in self.model.support_embeddings.keys() 

1012 ) 

1013 for label, dists in class_ood_dists.items(): 

1014 if not bool(torch.isfinite(dists).all()): 

1015 raise ValueError( 

1016 f"A calibration example of class {label} has a NaN or infinite " 

1017 "OOD distance; fitting its outlier score needs finite values." 

1018 ) 

1019 if bool((dists == dists[0]).all()): 

1020 raise ValueError( 

1021 f"Every calibration example of class {label} has the same OOD " 

1022 f"distance ({dists[0].item()}); fitting its outlier score needs " 

1023 "at least 2 distinct values." 

1024 ) 

1025 # TODO convert to torch func 

1026 fitted = OrderedDict( 

1027 (label, gaussian_kde(dists.cpu().detach().numpy())) 

1028 for label, dists in class_ood_dists.items() 

1029 ) 

1030 self.outlier_score_kde = fitted 

1031 

1032 def _compute_outlier_scores(self, ood_dists, predictions) -> torch.Tensor: 

1033 """ 

1034 Private function to compute OOD scores using the calculated kernel density estimate (KDE). 

1035 

1036 Each example is scored with the KDE of its predicted label: column 

1037 ``j`` of ``predictions`` is the ``j``-th support label. 

1038 

1039 Parameters 

1040 ---------- 

1041 ood_dists : torch.Tensor 

1042 Tensor of computed OOD distances. 

1043 predictions : torch.Tensor 

1044 Tensor of model protonet predictions. 

1045 

1046 Returns 

1047 ------- 

1048 torch.Tensor 

1049 Tensor of OOD scores for the given examples. 

1050 

1051 Raises 

1052 ------ 

1053 ValueError 

1054 If a support label has no outlier-score KDE, or the KDE of a 

1055 predicted label has more than one dimension. 

1056 """ 

1057 label_order = self._label_order() 

1058 missing = [ 

1059 label for label in label_order if label not in self.outlier_score_kde 

1060 ] 

1061 if missing: 

1062 raise ValueError( 

1063 f"No outlier-score KDE for support labels {missing}; refit the " 

1064 "outlier scores with EquineProtonet.update_support." 

1065 ) 

1066 dists = ood_dists.detach().cpu() 

1067 columns = torch.argmax(predictions, dim=1).cpu() 

1068 ood_scores = torch.zeros(len(dists), dtype=torch.float64) 

1069 for column, label in enumerate(label_order): 

1070 rows = torch.where(columns == column)[0] 

1071 if len(rows) == 0: 

1072 continue 

1073 kde = self.outlier_score_kde[label] 

1074 if kde.d != 1: 

1075 raise ValueError( 

1076 f"The outlier-score KDE of support label {label} has {kde.d} " 

1077 "dimensions; it must have one." 

1078 ) 

1079 data = torch.from_numpy(kde.dataset[0]) 

1080 weights = torch.from_numpy(kde.weights) 

1081 uniform = bool((weights == weights[0]).all()) 

1082 bandwidth = float(np.sqrt(kde.covariance[0, 0])) 

1083 # 1 minus the KDE's mass above each distance, for at most 2**22 

1084 # (distance, KDE point) pairs at a time 

1085 for chunk in rows.split(max(1, 2**22 // len(data))): 

1086 z = (dists[chunk, None] - data).double() / bandwidth 

1087 upper = 1.0 - torch.special.ndtr(z) 

1088 if uniform: 

1089 tail = upper.mean(dim=1) 

1090 else: 

1091 tail = (upper @ weights).clamp(0.0, 1.0) 

1092 ood_scores[chunk] = 1.0 - tail 

1093 

1094 return ood_scores.to(dtype=ood_dists.dtype, device=ood_dists.device) 

1095 

1096 @icontract.ensure(lambda result: len(result) > 0) 

1097 def _compute_ood_dist( 

1098 self, 

1099 X_embeddings: torch.Tensor, 

1100 predictions: torch.Tensor, 

1101 distances: torch.Tensor, 

1102 ) -> torch.Tensor: 

1103 """ 

1104 Private function to compute OOD distances using a distance function. 

1105 

1106 With ``relative_mahal``, the distance to the predicted class minus the 

1107 distance to the global mean (``ood_distance="rmd_sqrt"``) or the 

1108 difference of their squares (``"rmd_sq"``); otherwise the distance to 

1109 the predicted class. 

1110 

1111 Parameters 

1112 ---------- 

1113 X_embeddings : torch.Tensor 

1114 Tensor of example embeddings. 

1115 predictions : torch.Tensor 

1116 Tensor of model protonet predictions for the given embeddings. 

1117 distances : torch.Tensor 

1118 Tensor of calculated protonet distances for the given embeddings. 

1119 

1120 Returns 

1121 ------- 

1122 torch.Tensor 

1123 Tensor of OOD distances for the given embeddings. 

1124 """ 

1125 preds = torch.argmax(predictions, dim=1) 

1126 preds = preds.unsqueeze(dim=-1) 

1127 # Calculate (Relative) Mahalanobis Distance: 

1128 if self.relative_mahal: 

1129 null_distance = self.model.compute_distance( 

1130 X_embeddings, self.model.global_mean, self.model.global_covariance 

1131 ) 

1132 null_distance = null_distance.unsqueeze(dim=-1) 

1133 class_distance = distances.gather(1, preds) 

1134 if self.ood_distance == "rmd_sq": 

1135 ood_dist = class_distance**2 - null_distance**2 

1136 else: 

1137 ood_dist = class_distance - null_distance 

1138 else: 

1139 ood_dist = distances.gather(1, preds) 

1140 

1141 ood_dist = torch.reshape(ood_dist, (-1,)) 

1142 return ood_dist 

1143 

1144 def predict(self, X: torch.Tensor) -> EquineOutput: 

1145 """Predict function for EquineProtonet, inherited and implemented from Equine. 

1146 

1147 Computes in eval mode and leaves the model in the mode the caller had it in (via 

1148 ``train()``/``eval()``); a prediction is the same whatever mode the caller left 

1149 the model in. Every submodule's mode is restored; an embedding frozen with 

1150 ``model.embedding_model.eval()`` during fine-tuning stays frozen. 

1151 

1152 Parameters 

1153 ---------- 

1154 X : torch.Tensor 

1155 Input tensor. It is moved to the model device and cast to the embedding 

1156 model's parameter dtype; a float64 input to a float32 model is accepted. 

1157 

1158 Returns 

1159 ------- 

1160 EquineOutput 

1161 Output object containing prediction probabilities, OOD scores and 

1162 embeddings. Column ``j`` of the probabilities is the ``j``-th label 

1163 of ``get_support()``; ``train_model`` and ``update_support`` put 

1164 the labels in ascending order. Computed under ``torch.no_grad()``: 

1165 the tensors carry no autograd graph but are ordinary tensors (not 

1166 inference-mode tensors), which a caller can use in autograd. 

1167 

1168 Raises 

1169 ------ 

1170 ValueError 

1171 If ``X`` is empty, its embeddings hold a NaN or infinite value, or a 

1172 support label has no outlier-score KDE. 

1173 """ 

1174 _require_examples(X) 

1175 # One embedding pass, under no_grad. 

1176 with _eval_mode(self), torch.no_grad(): 

1177 preds, dists, X_embed = self.model._forward_with_embeddings(X) 

1178 if self.use_temperature: 

1179 scaled = dists / self.temperature 

1180 preds = torch.softmax(torch.negative(scaled), dim=1) 

1181 # The relative "rmd_sq" statistic reads the unscaled distances; 

1182 # the other statistics read the scaled ones. 

1183 if not (self.relative_mahal and self.ood_distance == "rmd_sq"): 

1184 dists = scaled 

1185 ood_dist = self._compute_ood_dist(X_embed, preds, dists) 

1186 ood_scores = self._compute_outlier_scores(ood_dist, preds) 

1187 

1188 self.validate_feature_label_names(X.shape[-1], preds.shape[-1]) 

1189 

1190 return EquineOutput(classes=preds, ood_scores=ood_scores, embeddings=X_embed) 

1191 

1192 @icontract.require( 

1193 lambda calib_frac: ( 

1194 not isinstance(calib_frac, (int, float)) or 0 < calib_frac < 1 

1195 ) 

1196 ) 

1197 def update_support( 

1198 self, 

1199 support_x: torch.Tensor, 

1200 support_y: torch.Tensor, 

1201 *args: Any, 

1202 calib_frac: float | None = None, 

1203 label_names: list[str] | None = None, 

1204 ) -> None: 

1205 """Function to update protonet support examples with given examples. 

1206 

1207 Computes in eval mode and leaves the model in the mode the caller had it in (via 

1208 ``train()``/``eval()``); it works on a freshly constructed model, which is in 

1209 training mode. Every submodule's mode is restored; an embedding frozen with 

1210 ``model.embedding_model.eval()`` during fine-tuning stays frozen. 

1211 

1212 Parameters 

1213 ---------- 

1214 support_x : torch.Tensor 

1215 Tensor containing support examples for protonet. 

1216 support_y : torch.Tensor 

1217 Tensor containing labels for given support examples, of at least 2 

1218 classes. 

1219 *args : Any 

1220 Deprecated: ``calib_frac`` and ``label_names`` passed by position, in 

1221 that order. Emits a ``DeprecationWarning`` and is then handled as the 

1222 keywords. 

1223 calib_frac : float 

1224 Fraction of given support data to use for OOD calibration. Required, 

1225 keyword-only. 

1226 label_names : list[str], optional 

1227 List of strings of the names of the labels (ex ["streaming", "voip", ...]). 

1228 Keyword-only. 

1229 

1230 Raises 

1231 ------ 

1232 TypeError 

1233 If ``calib_frac`` is missing, an option is passed both by position and 

1234 by keyword, or more than two options are passed by position. 

1235 ValueError 

1236 If ``support_y`` has fewer than 2 classes, the ``calib_frac`` split 

1237 leaves a class with fewer than 2 support or 2 calibration examples, a 

1238 calibration example's embedding or OOD distance holds a NaN or 

1239 infinite value, or a class's calibration examples all have the same 

1240 OOD distance. A failed update leaves the model as it was. 

1241 """ 

1242 if len(args) > 2: 

1243 raise TypeError( 

1244 "EquineProtonet.update_support() takes at most 2 options by " 

1245 f"position (calib_frac, label_names) but {len(args)} were given" 

1246 ) 

1247 if args: 

1248 if calib_frac is not None or (len(args) == 2 and label_names is not None): 

1249 name = "calib_frac" if calib_frac is not None else "label_names" 

1250 raise TypeError( 

1251 "EquineProtonet.update_support() got multiple values for " 

1252 f"argument '{name}'" 

1253 ) 

1254 warnings.warn( 

1255 "Passing calib_frac or label_names to EquineProtonet.update_support " 

1256 "by position is deprecated and will stop working in the next " 

1257 "release: pass calib_frac=... and label_names=... by keyword.", 

1258 DeprecationWarning, 

1259 # Past the icontract and beartype wrappers (none under -O), to the 

1260 # caller's line. 

1261 stacklevel=2 + (0 if sys.flags.optimize else 2), 

1262 ) 

1263 EquineProtonet.update_support( 

1264 self, 

1265 support_x, 

1266 support_y, 

1267 calib_frac=args[0], 

1268 label_names=args[1] if len(args) == 2 else label_names, 

1269 ) 

1270 return 

1271 if calib_frac is None: 

1272 raise TypeError( 

1273 "EquineProtonet.update_support() missing required keyword argument: " 

1274 "'calib_frac'" 

1275 ) 

1276 with _eval_mode(self): 

1277 all_labels = torch.unique(support_y).tolist() 

1278 if len(all_labels) < 2: 

1279 raise ValueError( 

1280 f"support_y must hold at least 2 classes, got {len(all_labels)}." 

1281 ) 

1282 support_x, calib_x, support_y, calib_y = stratified_train_test_split( 

1283 support_x, support_y, test_size=calib_frac 

1284 ) 

1285 _require_examples_per_class(support_y, all_labels, "support", 2) 

1286 _require_examples_per_class(calib_y, all_labels, "calibration", 2) 

1287 # Restored if a later step raises. 

1288 state, model_state = dict(vars(self)), dict(vars(self.model)) 

1289 try: 

1290 labels, counts = torch.unique(support_y, return_counts=True) 

1291 if label_names is not None: 

1292 self.label_names = label_names 

1293 self.validate_feature_label_names(support_x.shape[-1], labels.shape[0]) 

1294 

1295 shuffled_idxs = _get_shuffle_idxs_by_class(support_y, labels.tolist()) 

1296 support = OrderedDict() 

1297 for label, count in list(zip(labels.tolist(), counts.tolist())): 

1298 class_support = generate_support( 

1299 support_x, 

1300 support_y, 

1301 support_size=count, 

1302 selected_labels=[label], 

1303 shuffled_indexes={label: shuffled_idxs[label]}, 

1304 ) 

1305 support.update(class_support) 

1306 

1307 # The support and the calibration pass record no autograd graph. 

1308 with torch.no_grad(): 

1309 self.model.update_support(support) 

1310 preds, dists, X_embed = self.model._forward_with_embeddings(calib_x) 

1311 ood_dists = self._compute_ood_dist(X_embed, preds, dists) 

1312 self._fit_outlier_scores(ood_dists, calib_y) 

1313 except Exception: 

1314 vars(self).clear() 

1315 vars(self).update(state) 

1316 vars(self.model).clear() 

1317 vars(self.model).update(model_state) 

1318 raise 

1319 

1320 @icontract.require(lambda self: len(self.model.support) > 0) 

1321 def get_support(self) -> OrderedDict[int, torch.Tensor]: 

1322 """ 

1323 Get the support examples for the model. 

1324 

1325 Returns 

1326 ------- 

1327 OrderedDict[int, torch.Tensor] 

1328 The support examples for the model. 

1329 """ 

1330 return self.model.support 

1331 

1332 def _label_order(self) -> list[int]: 

1333 """ 

1334 The class label of each column of ``predict``'s ``classes``: the 

1335 support's labels, in support order. 

1336 

1337 Returns 

1338 ------- 

1339 list[int] 

1340 The support's labels. 

1341 """ 

1342 return list(self.model.support_embeddings) 

1343 

1344 @icontract.require(lambda self: len(self.model.prototypes) > 0) 

1345 def get_prototypes(self) -> torch.Tensor: 

1346 """ 

1347 Get the prototypes for the model (the class means of the support embeddings). 

1348 

1349 Returns 

1350 ------- 

1351 torch.Tensor 

1352 The prototpes for the model. 

1353 """ 

1354 return self.model.prototypes 

1355 

1356 def save(self, path: str) -> None: 

1357 """ 

1358 Save all model parameters to a file. 

1359 

1360 The embedding model is stored as a *recipe* (registered architecture 

1361 name plus constructor arguments) and a ``state_dict``, so the file holds 

1362 only data. 

1363 

1364 Parameters 

1365 ---------- 

1366 path : str 

1367 Filename to write the model. 

1368 

1369 Raises 

1370 ------ 

1371 ValueError 

1372 If the embedding model is not a registered architecture. 

1373 RuntimeError 

1374 If the model has no support examples (neither ``train_model`` nor 

1375 ``update_support`` has run). 

1376 """ 

1377 if len(self.model.support) == 0: 

1378 raise RuntimeError( 

1379 "The model has no support examples to save; call train_model or " 

1380 "update_support first." 

1381 ) 

1382 torch.save(self._to_checkpoint(), path) 

1383 

1384 def _to_checkpoint(self) -> dict[str, Any]: 

1385 """Build the checkpoint dictionary that ``save`` writes and ``_from_checkpoint`` reads.""" 

1386 model_settings = { 

1387 "cov_type": self.cov_type.value, 

1388 "emb_out_dim": self.emb_out_dim, 

1389 "use_temperature": self.use_temperature, 

1390 "init_temperature": self.temperature.item(), 

1391 "relative_mahal": self.relative_mahal, 

1392 "ood_distance": self.ood_distance, 

1393 "device": self.device, 

1394 } 

1395 # Plain values only, so load_checkpoint can read it with weights_only=True. 

1396 save_data: dict[str, Any] = { 

1397 "equine_format_version": EQUINE_FORMAT_VERSION, 

1398 **_embedding_checkpoint(self.model.embedding_model), 

1399 "feature_names": _plain_names(self.feature_names), 

1400 "label_names": _plain_names(self.label_names), 

1401 "model_head_save": self.model.model_head.state_dict(), 

1402 "outlier_kde": { 

1403 int(label): _kde_to_state(kde) 

1404 for label, kde in self.outlier_score_kde.items() 

1405 }, 

1406 "settings": model_settings, 

1407 "support": { 

1408 int(label): x.detach().clone() 

1409 for label, x in self.model.support.items() 

1410 }, 

1411 "train_summary": _plain_train_summary(self.train_summary), 

1412 } 

1413 return save_data 

1414 

1415 @classmethod 

1416 def load( 

1417 cls, 

1418 path: str, 

1419 device: str | None = None, 

1420 *, 

1421 embedding_model: torch.nn.Module | None = None, 

1422 ) -> Self: 

1423 """ 

1424 Load a previously saved EquineProtonet model. 

1425 

1426 Loading runs no code from the file: it is read with 

1427 ``torch.load(weights_only=True)`` and the embedding model is rebuilt from its 

1428 recipe through the architecture registry. 

1429 

1430 Parameters 

1431 ---------- 

1432 path : str 

1433 The filename of the saved model. 

1434 device : str | None 

1435 The device to load the model onto. Overrides the device recorded 

1436 in the file; by default the model lands on the saved device. 

1437 embedding_model : torch.nn.Module | None 

1438 Keyword-only. Use this module as the embedding architecture instead 

1439 of rebuilding it from the file's recipe; the file's weights are 

1440 loaded into it, and its floating-point tensors take their stored 

1441 dtypes. 

1442 

1443 Returns 

1444 ------- 

1445 EquineProtonet 

1446 The reconstituted EquineProtonet object. 

1447 

1448 Raises 

1449 ------ 

1450 ValueError 

1451 If the file is not in the current EQUINE format or stores its 

1452 embedding model as TorchScript (both are rewritten once with 

1453 ``python -m equine.upgrade``), or names an unregistered 

1454 architecture. If ``device`` is unavailable here, names an index at 

1455 or above its device count, or lacks a dtype the file holds (float64 

1456 on MPS: load such a file with ``device="cpu"``). If the file's 

1457 support holds one class. 

1458 """ 

1459 model_save = _load_checkpoint_for_device(path, device) 

1460 _refuse_torchscript(model_save, path) 

1461 return cls._from_checkpoint(model_save, device, embedding_model=embedding_model) 

1462 

1463 @classmethod 

1464 def _from_checkpoint( 

1465 cls, 

1466 model_save: dict[str, Any], 

1467 device: str | None = None, 

1468 embedding_model: torch.nn.Module | None = None, 

1469 ) -> Self: 

1470 """ 

1471 Rebuild an EquineProtonet from an already-loaded checkpoint dictionary. 

1472 

1473 Parameters 

1474 ---------- 

1475 model_save : dict[str, Any] 

1476 The dictionary returned by ``utils.load_checkpoint``. 

1477 device : str | None 

1478 Device override for the reconstituted model. 

1479 embedding_model : torch.nn.Module | None 

1480 Use this module as the embedding architecture instead of the file's 

1481 recipe; the file's weights are loaded into it, and its 

1482 floating-point tensors take their stored dtypes. 

1483 

1484 Returns 

1485 ------- 

1486 EquineProtonet 

1487 The reconstituted EquineProtonet object. 

1488 """ 

1489 # The embedding is rebuilt first. 

1490 embedding = _rebuild_embedding(model_save, embedding_model) 

1491 _require_entries( 

1492 model_save, 

1493 ("settings", "support", "train_summary", "outlier_kde", "model_head_save"), 

1494 cls, 

1495 ) 

1496 support = _support_from_file(model_save["support"]) 

1497 if len(support) == 0: 

1498 raise ValueError( 

1499 "Model file's support is empty; an EquineProtonet needs at least one " 

1500 "labelled support example." 

1501 ) 

1502 if len(support) == 1: 

1503 raise ValueError( 

1504 "Model file's support holds one class; an EquineProtonet needs at " 

1505 "least 2." 

1506 ) 

1507 for label, rows in support.items(): 

1508 if rows.shape[0] < 2: 

1509 raise ValueError( 

1510 f"Model file's support holds {rows.shape[0]} example(s) of class " 

1511 f"{label}; an EquineProtonet needs at least 2 per class." 

1512 ) 

1513 outlier_kde = _outlier_kde_from_file(model_save["outlier_kde"]) 

1514 for key in ("feature_names", "label_names"): 

1515 _require_names(model_save.get(key), key) 

1516 head_save = model_save["model_head_save"] 

1517 if isinstance(head_save, dict) and set(head_save) == {"weight", "bias"}: 

1518 raise ValueError( 

1519 "Model file's model_head_save holds the weights of a Linear head, " 

1520 "which EQUINE <= 0.1.6 saved; the head is now an Identity. Rewrite " 

1521 "the file with `python -m equine.upgrade`, which drops those weights." 

1522 ) 

1523 

1524 settings = _checked_settings(cls, model_save["settings"]) 

1525 # The model is built from the file's settings and then gets the file's 

1526 # ood_distance, or "rmd_sqrt" for a file without it. 

1527 ood_distance = settings.get("ood_distance", "rmd_sqrt") 

1528 # emb_out_dim must be an int >= 1, not a bool. 

1529 _positive_int( 

1530 settings.get("emb_out_dim"), "Model file's settings['emb_out_dim']" 

1531 ) 

1532 if "cov_type" in settings: 1532 ↛ 1542line 1532 didn't jump to line 1542 because the condition on line 1532 was always true

1533 cov_type = settings["cov_type"] 

1534 try: 

1535 settings["cov_type"] = CovType(cov_type) 

1536 except (ValueError, TypeError) as err: 

1537 raise ValueError( 

1538 f"Model file's settings['cov_type'] ({_shown(cov_type)}) is not " 

1539 f"one of {[member.value for member in CovType]}." 

1540 ) from err 

1541 # Allow the user to override the saved device state dynamically 

1542 if device is not None: 

1543 settings["device"] = device 

1544 else: 

1545 _require_device(settings, hint=" (pass device= to choose another)") 

1546 

1547 # The head is an Identity, which has no weights. 

1548 _require_matching_weights({}, head_save, "model_head_save") 

1549 try: 

1550 eq_model = cls(embedding, **settings) 

1551 except Exception as err: 

1552 raise ValueError( 

1553 f"Could not build {cls.__name__} from the model file's settings " 

1554 f"({_truncate(_describe_error(err), 200)})." 

1555 ) from err 

1556 eq_model.ood_distance = ood_distance 

1557 

1558 eq_model.model.model_head.load_state_dict(head_save) 

1559 eq_model.eval() 

1560 support_error = ( 

1561 "Model file's support could not be passed through its embedding model " 

1562 "({}); the file is inconsistent or was tampered with." 

1563 ) 

1564 # emb_out_dim must be 1 or the embedding's output width. 

1565 try: 

1566 with torch.no_grad(): 

1567 probe = eq_model.model.compute_embeddings( 

1568 next(iter(support.values()))[:1] 

1569 ) 

1570 except Exception as err: 

1571 raise ValueError( 

1572 support_error.format(_truncate(_describe_error(err), 200)) 

1573 ) from err 

1574 width = probe.shape[-1] if probe.dim() > 0 else 1 

1575 if eq_model.emb_out_dim not in (1, width): 

1576 raise ValueError( 

1577 "Model file's settings['emb_out_dim'] is neither 1 nor the " 

1578 f"{width} features its embedding model outputs; the file is " 

1579 "inconsistent or was tampered with." 

1580 ) 

1581 try: 

1582 with torch.no_grad(): 

1583 eq_model.model.update_support(support) 

1584 except Exception as err: 

1585 raise ValueError( 

1586 support_error.format(_truncate(_describe_error(err), 200)) 

1587 ) from err 

1588 

1589 eq_model.feature_names = model_save.get("feature_names") 

1590 eq_model.label_names = model_save.get("label_names") 

1591 eq_model.outlier_score_kde = outlier_kde 

1592 eq_model.train_summary = cast(dict[str, Any], model_save.get("train_summary")) 

1593 

1594 return eq_model