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

87 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 

4 

5import contextlib 

6from abc import ABC, abstractmethod 

7from collections import OrderedDict 

8from collections.abc import Callable 

9from itertools import chain 

10from typing import Any, Self, TypeVar 

11 

12import icontract 

13import torch 

14from torch.utils.data import TensorDataset 

15 

16from .equine_output import EquineOutput 

17 

18 

19@contextlib.contextmanager 

20def _eval_mode(module: torch.nn.Module): 

21 """Run the body with ``module`` in eval mode, then restore every submodule's mode. 

22 

23 The mode of every submodule is recorded and ``module.eval()`` is called. On the way 

24 out, each submodule whose class overrides ``train()`` is given ``train()`` with its 

25 recorded mode, which undoes what its ``train(False)`` did on the way in (loralib's 

26 ``merge_weights=True`` layers, for example, merge their LoRA weights in eval mode 

27 and unmerge them in training mode). Then every submodule's flag is set back 

28 individually (``m.training = ...``, which does not propagate). A frozen embedding 

29 (``model.train(); model.embedding_model.eval()``, which keeps BatchNorm statistics 

30 and dropout fixed while the head trains) is still frozen afterwards, and so is any 

31 other mix the caller set. 

32 """ 

33 modes = {m: m.training for m in module.modules()} 

34 module.eval() 

35 try: 

36 yield 

37 finally: 

38 for m, training in modes.items(): 

39 if type(m).train is not torch.nn.Module.train: 

40 m.train(training) 

41 for m, training in modes.items(): 

42 m.training = training 

43 

44 

45# A type variable for Equine objects 

46AnyEquine = TypeVar("AnyEquine", bound="Equine") 

47 

48 

49def _named_device(name: str) -> torch.device | None: 

50 """The device a tensor created with ``device=name`` lands on; None if this process has no such device.""" 

51 try: 

52 return torch.empty(0, dtype=torch.uint8, device=name).device 

53 except Exception: # by backend: AssertionError, RuntimeError or ImportError 

54 return None 

55 

56 

57def _apply_to_stored_tensors( 

58 module: torch.nn.Module, 

59 fn: Callable[[torch.Tensor], torch.Tensor], 

60 recurse: bool = True, 

61) -> None: 

62 """ 

63 Apply ``fn`` to the tensors ``module`` keeps outside its parameters and buffers. 

64 

65 ``nn.Module._apply``, which ``to``, ``cpu``, ``cuda`` and the dtype casts call, 

66 reaches parameters and buffers only. The model classes call this from their 

67 ``_apply``, after ``nn.Module._apply`` with the same ``recurse``. It applies ``fn`` 

68 to the plain tensor attributes ``prototypes``, ``covariance``, ``global_mean`` and 

69 ``global_covariance`` and to every tensor in ``support`` and ``support_embeddings``. 

70 

71 ``module.device`` then names the device the tensors are on (that of its 

72 first parameter, buffer or stored tensor): it is kept as given when it 

73 names that device, and otherwise becomes that device's name (``"mps:0"`` 

74 after ``to("mps")`` from the CPU; ``"cpu"`` after ``cpu()`` or ``float()`` 

75 on a CPU model whose ``device`` names a device this process lacks). A 

76 module without tensors applies ``fn`` to an empty tensor on ``device`` 

77 instead, or on the CPU when this process lacks ``device``. 

78 """ 

79 stored: list[torch.Tensor] = [] 

80 for name in ("prototypes", "covariance", "global_mean", "global_covariance"): 

81 value = module.__dict__.get(name) 

82 if isinstance(value, torch.Tensor): 

83 moved = fn(value) 

84 setattr(module, name, moved) 

85 stored.append(moved) 

86 for name in ("support", "support_embeddings"): 

87 value = module.__dict__.get(name) 

88 if isinstance(value, dict): 

89 moved_dict = OrderedDict((label, fn(x)) for label, x in value.items()) 

90 setattr(module, name, moved_dict) 

91 stored.extend(moved_dict.values()) 

92 device = module.__dict__.get("device") 

93 if isinstance(device, str): 

94 named = _named_device(device) 

95 held = chain( 

96 module.parameters(recurse=recurse), module.buffers(recurse=recurse), stored 

97 ) 

98 reference = next(held, None) 

99 if reference is None: 

100 probe = torch.empty(0, dtype=torch.uint8, device=named or "cpu") 

101 reference = fn(probe) 

102 if reference.device != named: 

103 setattr(module, "device", str(reference.device)) 

104 

105 

106class Equine(torch.nn.Module, ABC): 

107 """EQUINE Abstract Base Class (ABC): 

108 EQUINE is set up to extend torch's nn.Module to enrich it with 

109 a method that enables uncertainty quantification and visualization. Most 

110 importantly, the `.predict()` method must be outfitted to return an 

111 EquineOutput object that contains both the class probabilities 

112 *and* an out-of-distribution (ood) score. 

113 

114 Parameters 

115 ---------- 

116 embedding_model : torch.nn.Module 

117 The embedding model to use. 

118 head_layers : int, optional 

119 The number of layers to use in the model head, by default 1. 

120 device : str, optional 

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

122 feature_names : list[str], optional 

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

124 label_names : list[str], optional 

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

126 

127 Attributes 

128 ---------- 

129 device : str 

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

131 embedding_model : torch.nn.Module 

132 The neural embedding model to enrich with uncertainty quantification. 

133 feature_names : list[str], optional 

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

135 head_layers : int 

136 The number of linear layers to append to the embedding model (default 1, not always used). 

137 label_names : list[str], optional 

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

139 train_summary : dict[str, Any] 

140 A dictionary containing information about the model training. 

141 

142 Raises 

143 ------ 

144 NotImplementedError 

145 If any of the abstract methods are not implemented. 

146 """ 

147 

148 def __init__( 

149 self, 

150 embedding_model: torch.nn.Module, 

151 head_layers: int = 1, 

152 device: str = "cpu", 

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

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

155 ) -> None: 

156 super().__init__() 

157 self.embedding_model = embedding_model 

158 self.head_layers = head_layers 

159 self.train_summary: dict[str, Any] = { 

160 "numTrainExamples": 0, 

161 "dateTrained": "", 

162 "modelType": "", 

163 } 

164 self.device = device 

165 self.to(device) 

166 self.embedding_model.to(device) 

167 self.feature_names = feature_names 

168 self.label_names = label_names 

169 

170 def _apply( 

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

172 ) -> "Equine": 

173 """ 

174 ``nn.Module._apply``, extended to the stored tensors listed in 

175 ``_apply_to_stored_tensors``. 

176 

177 ``to``, ``cpu``, ``cuda`` and the dtype casts call it. ``model.to(device)`` 

178 moves every tensor the model keeps and updates ``device`` (see 

179 ``_apply_to_stored_tensors``). 

180 """ 

181 super()._apply(fn, recurse) 

182 _apply_to_stored_tensors(self, fn, recurse) 

183 return self 

184 

185 @abstractmethod 

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

187 """ 

188 Forward pass of the model. This is to preserve the usual behavior 

189 of torch.nn.Module. 

190 

191 Parameters 

192 ---------- 

193 X : torch.Tensor 

194 The input data. 

195 

196 Returns 

197 ------- 

198 torch.Tensor 

199 The output of the model. 

200 

201 """ 

202 raise NotImplementedError 

203 

204 @abstractmethod 

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

206 """ 

207 Upon implementation, predicts the class probabilities and out-of-distribution (ood) scores for the 

208 given input data. 

209 

210 Parameters 

211 ---------- 

212 X : torch.Tensor 

213 The input data. 

214 

215 Returns 

216 ------- 

217 EquineOutput 

218 An EquineOutput object containing the class probabilities and OOD scores. 

219 """ 

220 raise NotImplementedError 

221 

222 @abstractmethod 

223 def train_model( 

224 self, dataset: TensorDataset, *args: Any, **kwargs: Any 

225 ) -> dict[str, Any]: 

226 """ 

227 Upon implementation, train the model on the given dataset. 

228 

229 Parameters 

230 ---------- 

231 dataset : TensorDataset 

232 TensorDataset containing the training data. 

233 **kwargs 

234 Additional keyword arguments to pass to the training function. 

235 

236 Returns 

237 ------- 

238 dict[str, Any] 

239 Dictionary containing summary training information and any other data 

240 Note that at least one key should be 'train_summary' 

241 """ 

242 raise NotImplementedError 

243 

244 @abstractmethod 

245 def update_support( 

246 self, 

247 support_x: torch.Tensor, 

248 support_y: torch.Tensor, 

249 *args: Any, 

250 **kwargs: Any, 

251 ) -> None: 

252 """ 

253 Upon implementation, replace the model's support with examples taken from 

254 the given ones. 

255 

256 Parameters 

257 ---------- 

258 support_x : torch.Tensor 

259 Tensor containing the examples to take the support from. 

260 support_y : torch.Tensor 

261 Tensor containing the label of each example in ``support_x``. 

262 *args, **kwargs 

263 The options of the implementation: ``calib_frac`` and ``label_names`` 

264 for ``EquineProtonet``, ``support_size`` for ``EquineGP``, each passed 

265 by keyword. 

266 """ 

267 raise NotImplementedError 

268 

269 @abstractmethod 

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

271 """ 

272 Upon implementation, returns the support examples. 

273 

274 Returns 

275 ------- 

276 OrderedDict[int, torch.Tensor] 

277 The support examples of each class, keyed by label. 

278 """ 

279 raise NotImplementedError 

280 

281 @abstractmethod 

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

283 """ 

284 Upon implementation, returns the prototype embeddings 

285 

286 Returns 

287 ------- 

288 torch.Tensor 

289 A torch tensor of the prototype embeddings 

290 """ 

291 raise NotImplementedError 

292 

293 @abstractmethod 

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

295 """ 

296 Upon implementation, save the model to the given file path. 

297 

298 Parameters 

299 ---------- 

300 path : str 

301 File path to save the model to. 

302 """ 

303 raise NotImplementedError 

304 

305 @classmethod 

306 def load(cls, path: str) -> Self: 

307 """ 

308 Upon implementation, load the model from the given file path. 

309 

310 Parameters 

311 ---------- 

312 path : str 

313 File path to load the model from. 

314 

315 Returns 

316 ------- 

317 Equine 

318 Loaded model object. 

319 """ 

320 raise NotImplementedError 

321 

322 def get_label_names(self) -> list[str] | None: 

323 """ 

324 Retrieve the label names used in the model. 

325 

326 Returns 

327 ------- 

328 list[str] | None 

329 A list of label names if available; otherwise, None. 

330 """ 

331 if hasattr(self, "label_names"): 

332 return self.label_names 

333 return None 

334 

335 def _label_order(self) -> list[int] | None: 

336 """ 

337 The class label of each column of ``predict``'s ``classes``. 

338 

339 Returns 

340 ------- 

341 list[int] | None 

342 None: column ``j`` holds label ``j``. 

343 """ 

344 return None 

345 

346 def get_feature_names(self) -> list[str] | None: 

347 """ 

348 Retrieve the feature names used in the model. 

349 

350 Returns 

351 ------- 

352 list[str] | None 

353 A list of feature names if available; otherwise, None. 

354 """ 

355 if hasattr(self, "feature_names"): 

356 return self.feature_names 

357 return None 

358 

359 @icontract.require( 

360 lambda num_features, num_classes: num_features > 0 and num_classes > 0 

361 ) 

362 def validate_feature_label_names(self, num_features: int, num_classes: int) -> None: 

363 """ 

364 Validate that the feature names and label names, if provided, match the expected counts. 

365 

366 Parameters 

367 ---------- 

368 num_features : int 

369 The expected number of features. 

370 num_classes : int 

371 The expected number of classes. 

372 

373 Raises 

374 ------ 

375 ValueError 

376 If the length of `feature_names` does not match `num_features`, or 

377 if the length of `label_names` does not match `num_classes`. 

378 """ 

379 feature_names = self.get_feature_names() 

380 if feature_names is not None and len(feature_names) != num_features: 

381 raise ValueError( 

382 f"The length of feature_names ({len(feature_names)}) does not match the number of data features ({num_features}). Update feature_names or set feature_names to None." 

383 ) 

384 

385 label_names = self.get_label_names() 

386 if label_names is not None and len(label_names) != num_classes: 

387 raise ValueError( 

388 f"The length of label_names ({len(label_names)}) does not match the number of classes ({num_classes}). Update label_names or set label_names to None." 

389 )