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

400 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""" 

5Rewrite model files whose embedding model is stored as TorchScript. 

6 

7 python -m equine.upgrade MODEL.eq [-o OUT.eq] --recipe JSON [--import MODULE] 

8 [--check-inputs FILE | --no-check] 

9 

10Files saved by earlier EQUINE releases hold pickled Python objects, which 

11``torch.load(weights_only=True)`` refuses, and store the embedding model as 

12TorchScript, which EQUINE does not load. The upgrade reads such a file with 

13unrestricted unpickling and loads its TorchScript archive; both run code 

14embedded in the file, so only upgrade files you trust. Every file is first 

15read with the safe loader: a current-format file that holds a TorchScript 

16archive is upgraded from that read, and a file from an earlier release is 

17unpickled only after every argument that does not need the file has been 

18checked. 

19 

20The caller supplies the embedding architecture: an instance of a registered architecture 

21(``@equine.embedding_architecture``), or on the command line its recipe. The archive's 

22weights are copied into it and the model is written as a data-only file. Before anything 

23replaces the original, the written file is loaded back and its embedding must reproduce 

24the archive's outputs on the file's support rows and on ``check_inputs`` 

25(``--check-inputs``). A file with neither is refused before its archive is loaded, 

26unless the comparison is waived with ``allow_unchecked=True`` (``--no-check``). 

27 

28Reading these files is deprecated. 

29""" 

30 

31import argparse 

32import contextlib 

33import importlib 

34import io 

35import itertools 

36import json 

37import os 

38import stat 

39import sys 

40import warnings 

41from collections.abc import Iterator 

42from enum import Enum 

43from secrets import token_hex 

44from typing import Any, BinaryIO 

45 

46import numpy as np 

47import torch 

48from scipy.stats import gaussian_kde 

49 

50from .equine_gp import EquineGP 

51from .equine_protonet import EquineProtonet, _kde_to_state 

52from .registry import ( 

53 _describe_error, 

54 _truncate, 

55 build_from_recipe, 

56 embedding_recipe, 

57 registered_architectures, 

58) 

59from .utils import ( 

60 EQUINE_FORMAT_VERSION, 

61 LegacyFormatError, 

62 _embedding_checkpoint, 

63 _holds_torchscript, 

64 _is_extra_state_key, 

65 _unalias_support, 

66 load_checkpoint, 

67) 

68 

69_DEPRECATION = ( 

70 "Reading model files that store the embedding model as TorchScript is " 

71 "deprecated and will be removed in a later release; upgrade your files now." 

72) 

73 

74_HEAD_NOTE = ( 

75 "The file held the weights of a Linear head, which EQUINE <= 0.1.6 saved; the " 

76 "head is now an Identity, so those weights were dropped and " 

77 "predictions can differ from those of the EQUINE version that saved the file." 

78) 

79 

80_NOTHING_TO_COMPARE_ERROR = ( 

81 "'{path}' stores no support rows, so there are no inputs on which to check " 

82 "that the rebuilt embedding reproduces the file's TorchScript one; nothing " 

83 "was written. Pass inputs to compare on, one per row: check_inputs= from " 

84 "Python, or --check-inputs FILE (a tensor saved with torch.save) on the " 

85 "command line. To upgrade without the comparison, pass allow_unchecked=True, " 

86 "or --no-check." 

87) 

88 

89_NOT_COMPARED_NOTE = ( 

90 "The file stores no support rows and no check inputs were given, so the " 

91 "rebuilt embedding was not compared with the file's TorchScript one." 

92) 

93 

94# Windows does not replace a read-only file; POSIX renames ignore the target's mode. 

95_RENAME_NEEDS_A_WRITABLE_TARGET = os.name == "nt" 

96 

97_RTOL = 1e-4 

98_ATOL = 1e-5 

99 

100# Random names tried for the file written before it replaces the original. 

101_PARTIAL_ATTEMPTS = 100 

102 

103 

104def _plain(value: Any) -> Any: 

105 """``value`` with numpy scalars and strings, at any depth, as Python values.""" 

106 if isinstance(value, dict): 

107 return {_plain(k): _plain(v) for k, v in value.items()} 

108 if isinstance(value, (list, tuple)): 

109 return type(value)(_plain(v) for v in value) 

110 if isinstance(value, np.generic): 

111 return value.item() 

112 return value 

113 

114 

115def _archive_bytes(archive: torch.Tensor) -> bytes: 

116 """ 

117 Return the exact bytes of a ``uint8`` archive tensor. 

118 

119 A non-full or offset view yields exactly that view's bytes, not the whole backing 

120 storage: ``.numpy()`` operates on the tensor's own data (respecting its shape, 

121 stride and storage offset). 

122 """ 

123 return archive.detach().cpu().contiguous().numpy().tobytes() 

124 

125 

126def _load_archive(archive: Any) -> torch.nn.Module: 

127 """ 

128 The TorchScript module stored in a checkpoint, loaded on the CPU. 

129 

130 Accepts the ``uint8`` tensor of a current-format file and the ``bytes`` and 

131 ``io.BytesIO`` forms of files from earlier releases. 

132 """ 

133 load = getattr(getattr(torch, "jit", None), "load", None) 

134 if load is None: 

135 raise ValueError( 

136 "This torch build has no torch.jit.load, which the upgrade needs to " 

137 "read the file's TorchScript archive; run the upgrade with a torch " 

138 "release that still ships TorchScript." 

139 ) 

140 if isinstance(archive, torch.Tensor): 

141 buffer = io.BytesIO(_archive_bytes(archive)) 

142 elif isinstance(archive, (bytes, bytearray)): 

143 buffer = io.BytesIO(archive) 

144 elif isinstance(archive, io.BytesIO): 

145 buffer = archive 

146 else: 

147 raise ValueError( 

148 "The file's embed_jit_save is not a TorchScript archive " 

149 f"({type(archive).__name__})." 

150 ) 

151 buffer.seek(0) 

152 try: 

153 with warnings.catch_warnings(): 

154 warnings.simplefilter("ignore", FutureWarning) # torch's own notice 

155 return load(buffer, map_location="cpu") 

156 except Exception as err: 

157 raise ValueError( 

158 "The file's TorchScript archive could not be loaded " 

159 f"({_describe_error(err)})." 

160 ) from err 

161 

162 

163def _current_layout(checkpoint: dict[str, Any]) -> tuple[dict[str, Any], list[str]]: 

164 """The checkpoint rewritten with plain values only, minus its embedding, plus notes.""" 

165 out = dict(checkpoint) 

166 notes: list[str] = [] 

167 out.pop("embed_jit_save", None) 

168 out.pop("contains_executable", None) 

169 out["equine_format_version"] = EQUINE_FORMAT_VERSION 

170 settings = dict(out.get("settings", {})) 

171 if isinstance(settings.get("cov_type"), Enum): 

172 settings["cov_type"] = settings["cov_type"].value 

173 if "laplace_model_save" in out: 

174 # EquineGP takes no use_temperature; init_temperature holds the value. 

175 settings.pop("use_temperature", None) 

176 if out.get("support") is None: # absent or None when no support was set 

177 out["support"] = {} 

178 out["settings"] = _plain(settings) 

179 if isinstance(out.get("support"), dict): 179 ↛ 181line 179 didn't jump to line 181 because the condition on line 179 was always true

180 out["support"] = {int(label): x for label, x in out["support"].items()} 

181 if isinstance(out.get("outlier_kde"), dict): 

182 out["outlier_kde"] = { 

183 int(label): _kde_to_state(kde) if isinstance(kde, gaussian_kde) else kde 

184 for label, kde in out["outlier_kde"].items() 

185 } 

186 head = out.get("model_head_save") 

187 if isinstance(head, dict) and set(head) == {"weight", "bias"}: 

188 out["model_head_save"] = {} 

189 notes.append(_HEAD_NOTE) 

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

191 names = out.get(key) 

192 if isinstance(names, (list, tuple)) or ( 

193 isinstance(names, np.ndarray) and names.ndim == 1 

194 ): # anything else is left for the loader to report 

195 out[key] = [str(name) for name in names] 

196 if "train_summary" in out: 196 ↛ 198line 196 didn't jump to line 198 because the condition on line 196 was always true

197 out["train_summary"] = _plain(out["train_summary"]) 

198 _unalias_support(out) # each label gets its own copy of its support and KDE data 

199 return out, notes 

200 

201 

202def _attribute_tensor(module: Any, key: str) -> torch.Tensor | None: 

203 """The tensor reached by attribute access along dotted ``key``, if any.""" 

204 value = module 

205 for part in key.split("."): 

206 try: 

207 value = getattr(value, part) 

208 except (AttributeError, RuntimeError): 

209 return None 

210 return value if isinstance(value, torch.Tensor) else None 

211 

212 

213def _weights_from_archive( 

214 scripted: torch.nn.Module, target: torch.nn.Module 

215) -> dict[str, Any]: 

216 """ 

217 A ``state_dict`` for ``target`` taken from the TorchScript module. 

218 

219 Each entry comes from the archive's ``state_dict`` or, failing that, from the tensor 

220 attribute of the same dotted name. Extra-state entries keep the target's values. 

221 Archive entries the target does not store are allowed only for the target's 

222 non-persistent buffers. 

223 """ 

224 source = scripted.state_dict() 

225 expected = target.state_dict() 

226 weights: dict[str, Any] = {} 

227 missing: list[str] = [] 

228 wrong_shape: list[str] = [] 

229 for key, reference in expected.items(): 

230 if _is_extra_state_key(key): 

231 weights[key] = reference 

232 continue 

233 value = source[key] if key in source else _attribute_tensor(scripted, key) 

234 if value is None: 

235 missing.append(key) 

236 elif tuple(value.shape) != tuple(reference.shape): 

237 wrong_shape.append( 

238 f"{key} {tuple(value.shape)} vs {tuple(reference.shape)}" 

239 ) 

240 else: 

241 weights[key] = value 

242 non_persistent = {name for name, _ in target.named_buffers()} - set(expected) 

243 extra = sorted(set(source) - set(expected) - non_persistent) 

244 problems = [] 

245 if missing: 

246 problems.append(f"not in the archive: {', '.join(missing[:5])}") 

247 if wrong_shape: 

248 problems.append(f"different shapes: {'; '.join(wrong_shape[:5])}") 

249 if extra: 

250 problems.append(f"not in the supplied architecture: {', '.join(extra[:5])}") 

251 if problems: 

252 raise ValueError( 

253 f"The supplied embedding_model ({type(target).__name__}) does not match " 

254 f"the file's TorchScript embedding ({'; '.join(problems)})." 

255 ) 

256 return weights 

257 

258 

259def _first_float_dtype(module: torch.nn.Module) -> torch.dtype | None: 

260 for tensor in itertools.chain(module.parameters(), module.buffers()): 260 ↛ 263line 260 didn't jump to line 263 because the loop on line 260 didn't complete

261 if tensor.is_floating_point(): 261 ↛ 260line 261 didn't jump to line 260 because the condition on line 261 was always true

262 return tensor.dtype 

263 return None 

264 

265 

266def _embed(module: torch.nn.Module, rows: torch.Tensor) -> torch.Tensor: 

267 """``module``'s eval-mode output for ``rows`` on the CPU, in its own dtype.""" 

268 dtype = _first_float_dtype(module) 

269 x = rows.detach().cpu() 

270 if dtype is not None and x.is_floating_point(): 

271 x = x.to(dtype) 

272 module.eval() 

273 with torch.no_grad(): 

274 out = module(x) 

275 if not isinstance(out, torch.Tensor): 275 ↛ 276line 275 didn't jump to line 276 because the condition on line 275 was never true

276 raise TypeError(f"the module returned a {type(out).__name__}, not a tensor") 

277 return out 

278 

279 

280def _require_same_embedding( 

281 scripted: torch.nn.Module, rebuilt: torch.nn.Module, rows: torch.Tensor 

282) -> None: 

283 """Raise unless the rebuilt embedding reproduces the archive's outputs.""" 

284 try: 

285 expected = _embed(scripted, rows) 

286 actual = _embed(rebuilt, rows) 

287 except Exception as err: 

288 raise ValueError( 

289 "The upgrade could not compare the supplied architecture's embedding " 

290 f"with the file's ({_describe_error(err)})." 

291 ) from err 

292 if actual.shape != expected.shape: 

293 raise ValueError( 

294 "The supplied architecture does not reproduce the file's embedding: " 

295 f"its output shape {tuple(actual.shape)} differs from " 

296 f"{tuple(expected.shape)}." 

297 ) 

298 actual = actual.to(expected.dtype) 

299 if not torch.allclose(actual, expected, rtol=_RTOL, atol=_ATOL): 

300 largest = (actual - expected).abs().max().item() 

301 raise ValueError( 

302 "The supplied architecture does not reproduce the file's embedding: " 

303 f"its outputs differ from the TorchScript module's by up to {largest:.3g}." 

304 ) 

305 

306 

307def _has_rows(value: Any) -> bool: 

308 """Whether ``value`` is a tensor with at least one row.""" 

309 return isinstance(value, torch.Tensor) and value.dim() > 0 and len(value) > 0 

310 

311 

312def _comparison_blocks( 

313 checkpoint: dict[str, Any], check_inputs: torch.Tensor | None 

314) -> list[torch.Tensor]: 

315 """The inputs to compare the embeddings on: each label's support rows and 

316 ``check_inputs``, each kept as its own block (dtypes and shapes may differ).""" 

317 support = checkpoint.get("support") 

318 blocks = list(support.values()) if isinstance(support, dict) else [] 

319 if check_inputs is not None: 

320 blocks.append(check_inputs) 

321 return [b for b in blocks if _has_rows(b)] 

322 

323 

324def _replaced_file(path: str, out_path: str | None) -> str: 

325 """ 

326 The path the upgrade writes its result to: ``out_path``, or ``path`` when 

327 it is not given; for a symbolic link, the file the link points to. 

328 """ 

329 target = out_path or path 

330 return os.path.realpath(target) if os.path.islink(target) else target 

331 

332 

333def _parent_directory(path: str) -> str: 

334 """ 

335 The directory that holds ``path``, spelled as ``path`` spells it. 

336 """ 

337 return os.path.dirname(path) or os.curdir 

338 

339 

340def _require_arguments( 

341 embedding_model: torch.nn.Module, 

342 check_inputs: torch.Tensor | None, 

343 target: str, 

344) -> None: 

345 """ 

346 Raise unless the arguments can drive an upgrade that writes ``target``; 

347 reads nothing from the file. 

348 """ 

349 if os.path.islink(target): 

350 raise ValueError( 

351 f"The output '{target}' is a symbolic link that cannot be followed." 

352 ) 

353 if os.path.isdir(target) or os.path.basename(target) in ("", os.curdir, os.pardir): 

354 raise ValueError( 

355 f"The output '{target}' names a directory; give the path of a file." 

356 ) 

357 directory = _parent_directory(target) 

358 if not os.path.isdir(directory): 

359 raise ValueError( 

360 f"The output '{target}' cannot be written: '{directory}' is not an " 

361 "existing directory." 

362 ) 

363 try: 

364 descriptor, probe = _create_partial(target) 

365 except OSError as err: 

366 raise ValueError(f"The output '{target}' cannot be written: {err}") from err 

367 os.close(descriptor) 

368 os.remove(probe) 

369 if embedding_recipe(embedding_model) is None: 

370 raise ValueError( 

371 f"The supplied embedding_model ({type(embedding_model).__name__}) is " 

372 "not a registered architecture; register its class with " 

373 "@equine.embedding_architecture and pass an instance." 

374 ) 

375 if check_inputs is not None and not _has_rows(check_inputs): 

376 raise ValueError( 

377 "check_inputs must be a tensor with at least one row (one row per input)." 

378 ) 

379 

380 

381def _read_safely(path: str) -> dict[str, Any] | None: 

382 """ 

383 ``path`` read with the safe loader, or None for a file from an earlier 

384 release, which only the unrestricted read in ``_read_legacy`` opens. 

385 """ 

386 try: 

387 return load_checkpoint(path) 

388 except LegacyFormatError: 

389 return None 

390 

391 

392def _read_legacy(path: str) -> dict[str, Any]: 

393 """A file from an earlier release, read with unrestricted unpickling.""" 

394 try: 

395 checkpoint = torch.load(path, map_location="cpu", weights_only=False) 

396 except Exception as err: 

397 raise ValueError( 

398 f"'{path}' could not be read as a PyTorch file ({_describe_error(err)})." 

399 ) from err 

400 if not isinstance(checkpoint, dict) or "train_summary" not in checkpoint: 

401 raise ValueError(f"'{path}' is not an EQUINE model file.") 

402 return checkpoint 

403 

404 

405def _temp_named_as(message: str, partial: str, path: str) -> str: 

406 """ 

407 ``message`` with the temp file ``partial`` named as ``path``. Where repr 

408 escapes ``partial`` (a Windows separator does), its repr, which is how 

409 ``OSError`` quotes file names, is replaced with ``path``'s repr first. 

410 """ 

411 quoted = repr(partial) 

412 if quoted[1:-1] != partial: 

413 message = message.replace(quoted, repr(path)) 

414 return message.replace(partial, path) 

415 

416 

417def _reason(err: Exception, partial: str, path: str) -> str: 

418 """ 

419 ``err`` as one sentence for an upgrade error: the temp file named as 

420 ``path``, the loader's upgrade hint and its tampering suspicion cut off, 

421 the type named unless it is a ValueError (or the message is empty), and a 

422 final period. 

423 """ 

424 message = _temp_named_as(str(err), partial, path) 

425 for tail in ( 

426 ". Rewrite it once with", 

427 "; the file is inconsistent or was tampered", 

428 ): 

429 message = message.split(tail)[0] 

430 message = message.strip() 

431 if not message: 

432 message = type(err).__name__ 

433 elif not isinstance(err, ValueError): 

434 message = f"{type(err).__name__}: {message}" 

435 return message if message.endswith(".") else f"{message}." 

436 

437 

438def _create_partial(out_path: str) -> tuple[int, str]: 

439 """ 

440 Create the file the upgrade is written to before it replaces ``out_path``, and 

441 return its descriptor (open for writing) and path. It is a new file with a random 

442 name next to ``out_path``, created exclusively, and with the permission bits of the 

443 file it replaces plus owner read and write (those of a new file otherwise), less the 

444 umask. 

445 """ 

446 directory = _parent_directory(out_path) 

447 mode = ( 

448 (os.stat(out_path).st_mode & 0o777) | 0o600 

449 if os.path.exists(out_path) 

450 else 0o666 

451 ) 

452 flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0) 

453 for _ in range(_PARTIAL_ATTEMPTS): 

454 name = f".{os.path.basename(out_path)}.{token_hex(8)}.upgrading" 

455 partial = os.path.join(directory, name) 

456 try: 

457 return os.open(partial, flags, mode), partial 

458 except FileExistsError: 

459 continue 

460 except OSError as err: 

461 raise OSError( 

462 f"Could not write '{partial}' ({_describe_error(err)})." 

463 ) from err 

464 raise OSError( 

465 f"Could not create a file for the upgrade in '{directory}': each of " 

466 f"{_PARTIAL_ATTEMPTS} random names already exists." 

467 ) 

468 

469 

470@contextlib.contextmanager 

471def _closed_quietly_on_error(file: BinaryIO) -> Iterator[None]: 

472 """Close ``file`` when the block raises, ignoring an error from the close.""" 

473 try: 

474 yield 

475 except BaseException: 

476 with contextlib.suppress(OSError): 

477 file.close() 

478 raise 

479 

480 

481def _require_written_file(file: BinaryIO, partial: str, out_path: str) -> None: 

482 """Raise unless ``partial`` still names ``file``, the file written there.""" 

483 written = os.fstat(file.fileno()) 

484 named: os.stat_result | None 

485 try: 

486 named = os.lstat(partial) 

487 except FileNotFoundError: 

488 named = None 

489 if named is None or not os.path.samestat(named, written): 

490 raise OSError( 

491 "The upgraded file was replaced or removed before it could be moved " 

492 f"into place; '{out_path}' was left unchanged." 

493 ) 

494 

495 

496def _move_into_place( 

497 file: BinaryIO, partial: str, out_path: str, notes: list[str] 

498) -> None: 

499 """ 

500 Close ``file``, the upgraded file written at ``partial``, and move it to 

501 ``out_path``. It first gets the permission bits ``out_path`` had, read without 

502 following a link and set through ``file`` (through ``partial`` where ``os.fchmod`` 

503 is missing). The move is refused if ``out_path`` has become a symbolic link or, on 

504 POSIX, if ``partial`` no longer names ``file``. Where a rename needs a writable 

505 target (Windows), the file also gets owner write, and a read-only ``out_path`` gets 

506 its bits back once the move is done; a read-only ``out_path`` that is not a link is 

507 made writable for a second attempt and gets its bits back if that attempt fails too. 

508 """ 

509 

510 def note(err: OSError) -> None: 

511 notes.append( 

512 f"Could not copy the permission bits of '{out_path}' onto the " 

513 f"upgraded file ({_temp_named_as(str(err), partial, out_path)})." 

514 ) 

515 

516 target: os.stat_result | None 

517 try: 

518 target = os.lstat(out_path) 

519 except FileNotFoundError: 

520 target = None 

521 if target is not None and stat.S_ISLNK(target.st_mode): 

522 raise OSError( 

523 f"'{out_path}' became a symbolic link during the upgrade; it was left " 

524 "unchanged." 

525 ) 

526 mode: int | None = None if target is None else stat.S_IMODE(target.st_mode) 

527 moved_mode: int | None = None 

528 if mode is not None: 

529 moved_mode = mode | stat.S_IWUSR if _RENAME_NEEDS_A_WRITABLE_TARGET else mode 

530 try: 

531 if hasattr(os, "fchmod"): 

532 os.fchmod(file.fileno(), moved_mode) 

533 else: 

534 os.chmod(partial, moved_mode) 

535 except OSError as err: # a filesystem that rejects mode changes 

536 note(err) 

537 mode = None 

538 if os.name == "posix": 538 ↛ 540line 538 didn't jump to line 540 because the condition on line 538 was always true

539 _require_written_file(file, partial, out_path) 

540 try: 

541 file.close() 

542 except OSError as err: 

543 raise OSError(f"Could not write '{partial}' ({_describe_error(err)}).") from err 

544 try: 

545 os.replace(partial, out_path) 

546 except PermissionError: 

547 if ( 

548 not _RENAME_NEEDS_A_WRITABLE_TARGET 

549 or mode is None 

550 or mode & stat.S_IWUSR 

551 or os.path.islink(out_path) 

552 ): 

553 raise 

554 os.chmod(out_path, mode | stat.S_IWUSR) 

555 try: 

556 os.replace(partial, out_path) 

557 except BaseException: 

558 with contextlib.suppress(OSError): 

559 os.chmod(out_path, mode) 

560 raise 

561 if mode is not None and mode != moved_mode: 

562 try: 

563 os.chmod(out_path, mode) 

564 except OSError as err: 

565 note(err) 

566 

567 

568def _upgrade( 

569 path: str, 

570 checkpoint: dict[str, Any], 

571 embedding_model: torch.nn.Module, 

572 out_path: str | None, 

573 check_inputs: torch.Tensor | None, 

574 allow_unchecked: bool, 

575) -> tuple[str, list[str]]: 

576 """Write the upgraded file and return where, plus the notes to report.""" 

577 if "embed_jit_save" not in checkpoint: 

578 raise ValueError(f"'{path}' holds no TorchScript archive to upgrade from.") 

579 current, notes = _current_layout(checkpoint) 

580 blocks = _comparison_blocks(current, check_inputs) 

581 if not blocks: 

582 if not allow_unchecked: 

583 raise ValueError(_NOTHING_TO_COMPARE_ERROR.format(path=path)) 

584 notes.append(_NOT_COMPARED_NOTE) 

585 scripted = _load_archive(checkpoint["embed_jit_save"]) 

586 embedding_model.load_state_dict(_weights_from_archive(scripted, embedding_model)) 

587 current.update(_embedding_checkpoint(embedding_model)) 

588 

589 out_path = _replaced_file(path, out_path) 

590 descriptor, partial = _create_partial(out_path) 

591 try: 

592 with os.fdopen(descriptor, "wb") as file, _closed_quietly_on_error(file): 

593 try: 

594 torch.save(current, file) 

595 file.flush() 

596 except Exception as err: 

597 raise OSError( 

598 f"Could not write '{partial}' ({_describe_error(err)})." 

599 ) from err 

600 try: 

601 load_checkpoint(partial) 

602 except ValueError as err: 

603 raise ValueError( 

604 "The safe loader refuses the rewritten file: " 

605 f"{_reason(err, partial, path)} '{path}' holds a value the " 

606 "upgrade does not convert; it was left unchanged." 

607 ) from err 

608 # The class follows the file's layout. 

609 model_class = ( 

610 EquineGP if "laplace_model_save" in current else EquineProtonet 

611 ) 

612 try: 

613 rebuilt = model_class.load(partial, device="cpu") 

614 except Exception as err: 

615 raise ValueError( 

616 "The rewritten file does not load: " 

617 f"{_reason(err, partial, path)} '{path}' was left unchanged." 

618 ) from err 

619 for rows in blocks: 

620 _require_same_embedding(scripted, rebuilt.embedding_model, rows) 

621 _move_into_place(file, partial, out_path, notes) 

622 except BaseException: 

623 with contextlib.suppress(OSError): # the upgrade's error is reported 

624 if os.path.lexists(partial): 

625 os.remove(partial) 

626 raise 

627 return out_path, notes 

628 

629 

630def upgrade_model_file( 

631 path: str, 

632 embedding_model: torch.nn.Module, 

633 out_path: str | None = None, 

634 *, 

635 check_inputs: torch.Tensor | None = None, 

636 allow_unchecked: bool = False, 

637) -> str | None: 

638 """ 

639 Rewrite a trusted model file whose embedding model is TorchScript as a 

640 data-only file. 

641 

642 Parameters 

643 ---------- 

644 path : str 

645 The file to upgrade: a file saved by an earlier EQUINE release, or a 

646 current-format file holding a TorchScript archive. It is first read 

647 with the safe loader; a file from an earlier release is then read with 

648 unrestricted unpickling, once the other arguments have been checked. 

649 Its archive is loaded. 

650 embedding_model : torch.nn.Module 

651 An instance of the registered architecture the file's embedding was 

652 built from. The archive's weights are copied into it. 

653 out_path : str | None 

654 Where to write the result; defaults to replacing ``path``. Its directory must 

655 exist and allow creating a file. The result is written to a new file with a 

656 random name next to it, created with the permission bits of the file it replaces 

657 plus owner read and write, and moved into place only after it has been loaded 

658 back and checked. A failed upgrade leaves the original as it was. A symbolic 

659 link is followed and its target is replaced; the replaced file keeps its 

660 permission bits where the filesystem allows it. A link that cannot be followed, 

661 such as one that loops, is refused; a link to a missing file creates that file. 

662 check_inputs : torch.Tensor | None 

663 Keyword-only. Inputs, one per row, on which the new embedding must 

664 reproduce the archive's outputs, in addition to the file's support 

665 rows. A file that stores no support rows (most ``EquineGP`` files) 

666 needs them unless ``allow_unchecked`` is True. 

667 allow_unchecked : bool 

668 Keyword-only. Upgrade a file that stores no support rows without 

669 ``check_inputs``; the new embedding is then not compared with the 

670 archive's. By default such a file is refused and nothing is written. 

671 

672 Returns 

673 ------- 

674 str | None 

675 The path of the written file, or None if ``path`` is already a 

676 data-only current-format file and nothing was written. 

677 

678 Raises 

679 ------ 

680 ValueError 

681 If the file is not an EQUINE model file, if the safe loader refuses it 

682 for a reason other than its age, if ``out_path`` names a directory, 

683 is a symbolic link that cannot be followed, or its directory does not 

684 exist or no file can be created in it, if 

685 ``embedding_model`` is not a registered architecture or does not match 

686 the archive's weights, if ``check_inputs`` is not a tensor with at 

687 least one row, if the file stores no support rows and neither 

688 ``check_inputs`` nor ``allow_unchecked`` is given, if the rewritten 

689 file does not load, or if its embedding does not reproduce the 

690 archive's outputs. 

691 OSError 

692 If writing the result or moving it into place fails. 

693 

694 Warns 

695 ----- 

696 FutureWarning 

697 Always: reading these files is deprecated. 

698 UserWarning 

699 When Linear-head weights were dropped, when ``allow_unchecked`` let 

700 the upgrade write a file whose embedding was not compared, or when 

701 the permission bits could not be copied. 

702 """ 

703 warnings.warn(_DEPRECATION, FutureWarning, stacklevel=2) 

704 checkpoint = _read_safely(path) 

705 if checkpoint is not None and not _holds_torchscript(checkpoint): 

706 return None 

707 _require_arguments(embedding_model, check_inputs, _replaced_file(path, out_path)) 

708 if checkpoint is None: 

709 checkpoint = _read_legacy(path) 

710 written, notes = _upgrade( 

711 path, checkpoint, embedding_model, out_path, check_inputs, allow_unchecked 

712 ) 

713 for note in notes: 

714 warnings.warn(note, UserWarning, stacklevel=2) 

715 return written 

716 

717 

718def _module_from_recipe(recipe_json: str, imports: list[str]) -> torch.nn.Module: 

719 """The architecture named by a JSON recipe, after importing ``imports``.""" 

720 for name in imports: 

721 try: 

722 importlib.import_module(name) 

723 except Exception as err: 

724 raise ValueError( 

725 f"Could not import {name!r} ({_describe_error(err)})." 

726 ) from err 

727 try: 

728 recipe = json.loads(recipe_json) 

729 except json.JSONDecodeError as err: 

730 raise ValueError(f"--recipe is not valid JSON ({err}).") from err 

731 builder = recipe.get("builder") if isinstance(recipe, dict) else None 

732 if not isinstance(builder, str): 

733 raise ValueError( 

734 '--recipe must be a JSON object with a "builder" string and optional ' 

735 '"kwargs".' 

736 ) 

737 if builder not in registered_architectures(): 

738 known = ", ".join(registered_architectures()) or "(none)" 

739 raise ValueError( 

740 f"--recipe names architecture {builder[:200]!r}, which is not " 

741 "registered; pass --import MODULE for the module that registers it " 

742 f"(registered: {known})." 

743 ) 

744 try: 

745 return build_from_recipe(recipe) 

746 except ValueError as err: 

747 raise ValueError(f"--recipe could not be built: {err}") from err 

748 

749 

750def _check_inputs_from_file(path: str) -> torch.Tensor: 

751 """The tensor of input rows in ``path``, read with ``weights_only=True``.""" 

752 try: 

753 rows = torch.load(path, map_location="cpu", weights_only=True) 

754 except Exception as err: 

755 raise ValueError( 

756 f"--check-inputs '{path}' could not be read " 

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

758 ) from err 

759 if not _has_rows(rows): 

760 held = ( 

761 f"a tensor of shape {tuple(rows.shape)}" 

762 if isinstance(rows, torch.Tensor) 

763 else f"a {type(rows).__name__}" 

764 ) 

765 raise ValueError( 

766 f"--check-inputs '{path}' must hold one tensor with at least one row " 

767 f"(one row per input); it holds {held}." 

768 ) 

769 return rows 

770 

771 

772def main(argv: list[str] | None = None) -> int: 

773 parser = argparse.ArgumentParser( 

774 prog="python -m equine.upgrade", 

775 description="Rewrite a model file whose embedding model is TorchScript " 

776 "(every file saved by an earlier EQUINE release) as a data-only file. " 

777 "Only upgrade files you trust: the file is unpickled without " 

778 "restrictions and its TorchScript archive is loaded, either of which can " 

779 "run code embedded in it.", 

780 ) 

781 parser.add_argument("path", help="the model file to upgrade") 

782 parser.add_argument( 

783 "-o", "--output", help="write the result here instead of replacing PATH" 

784 ) 

785 parser.add_argument( 

786 "--recipe", 

787 help="the embedding architecture as a recipe, for example " 

788 '\'{"builder": "equine.mlp", "kwargs": {"in_features": 6, ' 

789 '"hidden_sizes": [32], "out_features": 3}}\'', 

790 ) 

791 parser.add_argument( 

792 "--import", 

793 dest="imports", 

794 action="append", 

795 default=[], 

796 metavar="MODULE", 

797 help="import MODULE first, so the architectures it registers are known " 

798 "(repeatable)", 

799 ) 

800 comparison = parser.add_mutually_exclusive_group() 

801 comparison.add_argument( 

802 "--check-inputs", 

803 metavar="FILE", 

804 help="a file holding one tensor of input rows (written with torch.save) " 

805 "on which the rebuilt embedding must reproduce the file's TorchScript " 

806 "one, in addition to the file's support rows; a file that stores no " 

807 "support rows (most EquineGP files) needs this or --no-check", 

808 ) 

809 comparison.add_argument( 

810 "--no-check", 

811 action="store_true", 

812 help="upgrade a file that stores no support rows without comparing the " 

813 "rebuilt embedding with the file's TorchScript one (the support rows of a " 

814 "file that has them are still compared)", 

815 ) 

816 args = parser.parse_args(argv) 

817 try: 

818 with warnings.catch_warnings(): 

819 warnings.simplefilter("ignore") 

820 checkpoint = _read_safely(args.path) 

821 if checkpoint is not None and not _holds_torchscript(checkpoint): 

822 print(f"{args.path} is already in the current format; nothing written.") 

823 return 0 

824 if args.recipe is None: 

825 raise ValueError( 

826 "--recipe is required: the file's embedding is TorchScript, so " 

827 "the upgrade needs the registered architecture to rebuild it." 

828 ) 

829 module = _module_from_recipe(args.recipe, args.imports) 

830 check_inputs = ( 

831 None 

832 if args.check_inputs is None 

833 else _check_inputs_from_file(args.check_inputs) 

834 ) 

835 _require_arguments( 

836 module, check_inputs, _replaced_file(args.path, args.output) 

837 ) 

838 if checkpoint is None: 

839 checkpoint = _read_legacy(args.path) 

840 written, notes = _upgrade( 

841 args.path, checkpoint, module, args.output, check_inputs, args.no_check 

842 ) 

843 except (ValueError, OSError) as err: 

844 print(f"error: {err}", file=sys.stderr) 

845 return 1 

846 for note in notes: 

847 print(f"note: {note}", file=sys.stderr) 

848 if written == args.path: 

849 print(f"Upgraded {args.path} in place.") 

850 else: 

851 print(f"Upgraded {args.path} -> {written}") 

852 print(_DEPRECATION, file=sys.stderr) 

853 return 0 

854 

855 

856if __name__ == "__main__": 856 ↛ 857line 856 didn't jump to line 857 because the condition on line 856 was never true

857 sys.exit(main())