Coverage for /opt/hostedtoolcache/Python/3.12.16/x64/lib/python3.12/site-packages/equine/registry.py: 100%
212 statements
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-20 23:10 +0000
« prev ^ index » next coverage.py v7.17.4, created at 2026-11-20 23:10 +0000
1# Copyright 2024, MASSACHUSETTS INSTITUTE OF TECHNOLOGY
2# Subject to FAR 52.227-11 – Patent Rights – Ownership by the Contractor (May 2014).
3# SPDX-License-Identifier: MIT
4"""
5Registry of embedding-model architectures.
7An EQUINE model file describes its embedding model as a *recipe*: the name of
8a registered architecture plus the plain-valued constructor arguments it was
9built with. ``load()`` rebuilds the module by calling only a registered
10constructor, so a model file never names an import path and never carries
11executable content.
13Recipes are recorded per exact class (a subclass must register itself to get its own
14recipe) and are deep-copied both when recorded and when handed back. Neither the
15constructor nor the caller can mutate a module's stored recipe. Registration is
16thread-safe.
17"""
19from __future__ import annotations
21import copy
22import functools
23import inspect
24import reprlib
25import threading
26import warnings
27from collections import OrderedDict
28from collections.abc import Callable, Iterator, Mapping
29from typing import Any, TypeVar
31import torch
33__all__ = [
34 "embedding_architecture",
35 "embedding_recipe",
36 "register_embedding_architecture",
37 "registered_architectures",
38]
40_M = TypeVar("_M", bound=torch.nn.Module)
42_REGISTRY: dict[str, type[torch.nn.Module]] = {}
43_REGISTRY_LOCK = threading.Lock()
44_RECIPE_ATTR = "_equine_recipe"
45_REGISTERED_AS_ATTR = "_equine_registered_as"
47_PLAIN_SCALAR_TYPES = (int, float, str, bool, type(None))
48_PLAIN_CONTAINER_TYPES = (list, tuple)
49_PLAIN_KEY_TYPES = (str, int)
50# Deepest nesting of lists, tuples and dicts accepted in a plain value.
51_MAX_PLAIN_DEPTH = 100
53# Shows real builder names in full and cuts a long name from a file short.
54_ERROR_REPR = reprlib.Repr()
55_ERROR_REPR.maxstring = 200
56_ERROR_REPR.maxother = 200
59def _message_or_type(err: BaseException) -> str:
60 """``err``'s message, or its type name when it has no message."""
61 return str(err) or type(err).__name__
64def _describe_error(err: BaseException) -> str:
65 """``err`` as ``TypeName: message``, or as ``TypeName`` when it has no message."""
66 message = str(err)
67 return f"{type(err).__name__}: {message}" if message else type(err).__name__
70def _truncate(text: str, limit: int = 500) -> str:
71 """Bound ``text`` to at most ``limit`` characters plus a truncation marker."""
72 if len(text) <= limit:
73 return text
74 return f"{text[:limit]}...(truncated)"
77def _positive_int(value: object, name: str) -> int:
78 """
79 Return ``value`` if it is exactly an ``int`` (``bool`` is refused) >= 1.
81 Otherwise raise a ValueError naming ``name``. The value is shown only when it is a
82 small int.
83 """
84 if type(value) is int and value >= 1:
85 return value
86 shown = f" {value}" if type(value) is int and value > -(10**6) else ""
87 raise ValueError(
88 f"{name} must be a positive integer (an int >= 1, not a bool); got "
89 f"{type(value).__name__}{shown}."
90 )
93def _shown_key(key: Any) -> str:
94 """A bounded repr of a dict key or sequence index for an error message."""
95 try:
96 return _ERROR_REPR.repr(key)
97 except ValueError: # an int with too many digits to convert to str
98 return f"<{type(key).__name__}>"
101def _check_plain(
102 values: Mapping[str, Any],
103 *,
104 allow_tensors: bool = False,
105 what: str = "Constructor argument",
106 owner: str = "a registered embedding architecture",
107 key_types: tuple[type, ...] = _PLAIN_KEY_TYPES,
108) -> None:
109 """
110 Require each of ``values`` to be built only from exact plain types, with
111 lists, tuples and dicts nested at most ``_MAX_PLAIN_DEPTH`` levels deep.
113 With ``allow_tensors`` (for a module's extra state, which lives in its
114 state_dict), tensors that are not quantized and carry no Python attributes,
115 ``torch.Size`` and ``OrderedDict`` are accepted too: the safe loader reads all
116 three. ``what`` and ``owner`` name the kind of value and what it belongs to in the
117 error message, which locates an offending value starting from its key in
118 ``values``. Dict keys must be exactly one of ``key_types``.
120 Values read from a model file can share one container between many places, within
121 one value or across several, or contain themselves. The walk is iterative and checks
122 each distinct container once for all of ``values``. The depth is the longest chain
123 of nested containers, whichever way a shared container is reached, and a container
124 that contains itself is refused. The location of an offending value is formatted
125 only for the error message, and is bounded.
126 """
127 # The key in ``values`` being checked, then the key or index leading to
128 # each container on the current chain, then to the item being checked.
129 keys: list[Any] = []
130 key_names = ["None" if kind is type(None) else kind.__name__ for kind in key_types]
132 def where() -> str:
133 path = keys[0] + "".join(f"[{_shown_key(key)}]" for key in keys[1:])
134 return _truncate(path, 200)
136 def items_of(item: Any) -> Iterator[tuple[Any, Any]] | None:
137 """The ``(key, item)`` pairs of a plain container; None for a plain leaf."""
138 item_type = type(item)
139 if item_type in _PLAIN_SCALAR_TYPES:
140 return None
141 if allow_tensors and item_type in (
142 torch.Tensor,
143 torch.nn.Parameter,
144 torch.Size,
145 ):
146 if item_type is torch.Size or not (item.is_quantized or vars(item)):
147 return None
148 if item_type in _PLAIN_CONTAINER_TYPES:
149 return enumerate(item)
150 if item_type is dict or (allow_tensors and item_type is OrderedDict):
151 return iter(item.items())
152 allowed = (
153 "int, float, str, bool, None, list, tuple, dict or OrderedDict (with "
154 f"{'/'.join(key_names)} keys), torch.Tensor, or torch.Size"
155 if allow_tensors
156 else "int, float, str, bool, None, list, tuple, or dict (with "
157 f"{'/'.join(key_names)} keys)"
158 )
159 if item_type in (set, frozenset):
160 hint = "use a sorted list, e.g. sorted(x)"
161 elif isinstance(item, torch.Tensor) and item.is_quantized:
162 hint = "a quantized tensor; store x.dequantize()"
163 elif isinstance(item, torch.Tensor):
164 hint = "a tensor with Python attributes; store x.detach().clone()"
165 else:
166 hint = "e.g. convert with float(x) or int(x)"
167 raise TypeError(
168 f"{what} {where()!r} of {owner} must be a "
169 f"plain value of exactly one of these types: {allowed}, or a nested "
170 "combination of those, so it can be stored in a model file; got "
171 f"{item_type.__name__} ({hint})."
172 )
174 def too_deep() -> TypeError:
175 return TypeError(
176 f"{what} {where()!r} of {owner} nests "
177 f"lists, tuples and dicts more than {_MAX_PLAIN_DEPTH} levels deep; "
178 f"plain values may be nested at most {_MAX_PLAIN_DEPTH} levels deep."
179 )
181 # For each container checked so far, how many levels of containers it
182 # holds, itself included; 0 while it is still on the chain being walked.
183 heights: dict[int, int] = {}
184 for path, value in values.items():
185 if id(value) in heights: # a container checked under an earlier key
186 continue
187 keys.append(path)
188 root_items = items_of(value)
189 if root_items is None:
190 keys.pop()
191 continue
192 heights[id(value)] = 0
193 # The containers from ``value`` down to the one being walked: its id,
194 # its remaining items, and whether it is a dict.
195 chain = [(id(value), root_items, type(value) not in _PLAIN_CONTAINER_TYPES)]
196 # The deepest nesting found so far in each container on the chain.
197 deepest = [1]
198 while chain:
199 ident, items, is_dict = chain[-1]
200 entry = next(items, None)
201 if entry is None:
202 chain.pop()
203 heights[ident] = deepest.pop()
204 keys.pop()
205 if chain:
206 deepest[-1] = max(deepest[-1], heights[ident] + 1)
207 continue
208 key, item = entry
209 if is_dict and type(key) not in key_types:
210 raise TypeError(
211 f"{what} {where()!r} has a dict key {_shown_key(key)} of type "
212 f"{type(key).__name__}; dict keys must be exactly one of "
213 f"{', '.join(key_names[:-1])} or {key_names[-1]} (e.g. convert "
214 "with str(key))."
215 )
216 keys.append(key)
217 height = heights.get(id(item))
218 if height is None:
219 nested = items_of(item)
220 if nested is None:
221 keys.pop()
222 continue
223 if len(chain) >= _MAX_PLAIN_DEPTH:
224 raise too_deep()
225 heights[id(item)] = 0
226 chain.append(
227 (id(item), nested, type(item) not in _PLAIN_CONTAINER_TYPES)
228 )
229 deepest.append(1)
230 elif height == 0:
231 raise TypeError(
232 f"{what} {where()!r} of {owner} contains itself; plain values "
233 "must not refer back to a list, tuple or dict that encloses them."
234 )
235 elif len(chain) + height > _MAX_PLAIN_DEPTH:
236 raise too_deep()
237 else:
238 keys.pop()
239 deepest[-1] = max(deepest[-1], height + 1)
242def _validate_constructor_signature(
243 cls: type[torch.nn.Module], signature: inspect.Signature
244) -> str:
245 """Ensure ``signature`` can be recorded as a recipe; return the first parameter's name."""
246 if cls.__init__ is torch.nn.Module.__init__:
247 raise TypeError(
248 f"{cls.__qualname__} does not define its own __init__ (it inherits "
249 "torch.nn.Module.__init__ unchanged); a registered architecture must "
250 "define its own __init__ so its constructor arguments can be recorded "
251 "in a recipe."
252 )
253 param_names = list(signature.parameters)
254 first_param_name = param_names[0]
255 first_kind = signature.parameters[first_param_name].kind
256 if first_kind in (
257 inspect.Parameter.VAR_POSITIONAL,
258 inspect.Parameter.VAR_KEYWORD,
259 inspect.Parameter.KEYWORD_ONLY,
260 ):
261 raise TypeError(
262 f"{cls.__qualname__}.__init__'s first parameter {first_param_name!r} is "
263 "*args, **kwargs, or keyword-only, so its instance argument would be "
264 "silently absorbed; registered architectures need a plain first "
265 "parameter for the instance so later constructor arguments can be "
266 "recorded in a recipe."
267 )
268 for pname in param_names[1:]:
269 param = signature.parameters[pname]
270 if param.kind is inspect.Parameter.VAR_POSITIONAL:
271 raise TypeError(
272 f"{cls.__qualname__}.__init__ accepts *args; registered architectures "
273 "need named constructor arguments so they can be recorded in a recipe."
274 )
275 if param.kind is inspect.Parameter.POSITIONAL_ONLY:
276 raise TypeError(
277 f"{cls.__qualname__}.__init__ has positional-only parameter {pname!r}; "
278 "registered architectures need named (keyword-capable) constructor "
279 "arguments so they can be recorded in a recipe."
280 )
281 return first_param_name
284def _require_name(name: Any) -> None:
285 """Refuse an architecture name that is not a non-empty ``str``."""
286 if type(name) is not str:
287 raise TypeError(
288 "An embedding architecture name must be a str (it is stored in model "
289 f"files); got {type(name).__name__}."
290 )
291 if not name:
292 raise ValueError("An embedding architecture name must not be empty.")
295def _register(name: str, cls: type[_M], stacklevel: int) -> None:
296 """
297 Shared implementation for ``register_embedding_architecture`` and the
298 ``embedding_architecture`` decorator.
300 ``stacklevel`` is set per entry point and attributes a re-registration
301 ``UserWarning`` to the caller's source line.
302 """
303 with _REGISTRY_LOCK:
304 already_as = cls.__dict__.get(_REGISTERED_AS_ATTR)
305 if already_as is not None and already_as != name:
306 raise ValueError(
307 f"{cls.__module__}.{cls.__qualname__} is already registered as "
308 f"{already_as!r}; register each class under exactly one name "
309 f"(cannot also register it as {name!r})."
310 )
312 existing = _REGISTRY.get(name)
313 if existing is cls:
314 return # Already fully registered under this exact name; no-op.
316 is_redefinition = False
317 if existing is not None:
318 same_definition = (
319 existing.__module__ == cls.__module__
320 and existing.__qualname__ == cls.__qualname__
321 )
322 if not same_definition:
323 raise ValueError(
324 f"Embedding architecture name {name!r} is already registered to "
325 f"{existing.__module__}.{existing.__qualname__}; cannot register "
326 f"{cls.__module__}.{cls.__qualname__} under it."
327 )
328 is_redefinition = True
330 original_init: Callable[..., None] = cls.__init__
331 signature = inspect.signature(original_init)
332 first_param_name = _validate_constructor_signature(cls, signature)
334 if is_redefinition:
335 warnings.warn(
336 f"Embedding architecture {name!r} was re-registered: "
337 f"{cls.__module__}.{cls.__qualname__} replaces the previous "
338 "definition registered under that name (expected after a reload "
339 "or re-running a notebook cell).",
340 UserWarning,
341 stacklevel=stacklevel,
342 )
344 @functools.wraps(original_init)
345 def recording_init(self: torch.nn.Module, *args: Any, **kwargs: Any) -> None:
346 if type(self) is not cls:
347 original_init(self, *args, **kwargs)
348 return
349 bound = signature.bind(self, *args, **kwargs)
350 bound.apply_defaults()
351 recipe_kwargs: dict[str, Any] = {}
352 for key, value in bound.arguments.items():
353 if key == first_param_name:
354 continue
355 if signature.parameters[key].kind is inspect.Parameter.VAR_KEYWORD:
356 recipe_kwargs.update(value)
357 else:
358 recipe_kwargs[key] = value
359 _check_plain(recipe_kwargs)
360 snapshot = copy.deepcopy(recipe_kwargs)
361 original_init(self, *args, **kwargs)
362 setattr(self, _RECIPE_ATTR, {"builder": name, "kwargs": snapshot})
364 setattr(cls, "__init__", recording_init)
365 setattr(cls, _REGISTERED_AS_ATTR, name)
366 _REGISTRY[name] = cls
369def register_embedding_architecture(
370 name: str, cls: type[_M], *, _stacklevel: int = 3
371) -> None:
372 """
373 Register ``cls`` under ``name`` and make its instances carry a recipe.
375 Every instance of exactly ``cls`` (not an unregistered subclass) records the
376 arguments it was constructed with (defaults applied, ``**kwargs`` flattened in),
377 through a wrapper around the class's ``__init__``. Those
378 arguments must be plain values, with lists, tuples and dicts nested at
379 most 100 levels deep. Registering the exact same class object
380 under the same name again is a no-op. Re-registering under the same name
381 a *different* class object with the same ``__module__`` and
382 ``__qualname__`` (as happens after ``importlib.reload`` or re-running a
383 notebook cell that redefines the class) replaces the registration and
384 emits a ``UserWarning``; a genuinely different class raises
385 ``ValueError``. Registering one class object under two different names
386 also raises ``ValueError``. Concurrent registrations resolve deterministically: the
387 whole check-then-register sequence, including the two-names check, is serialized on
388 a module-level lock.
390 Parameters
391 ----------
392 name : str
393 Stable identifier stored in model files. Namespace it by project
394 (``"myproject.encoder"``). Never an import path.
395 cls : type[_M]
396 The architecture class. It must not inherit ``torch.nn.Module.__init__``
397 unchanged (an ``__init__`` inherited from a user-defined base class is
398 recorded with that base's signature). Its ``__init__`` needs a plain
399 first (instance) parameter and named, non-variadic-positional,
400 non-positional-only constructor arguments after it.
402 Raises
403 ------
404 TypeError
405 If ``name`` is not a ``str``, ``cls`` inherits
406 ``torch.nn.Module.__init__`` unchanged, or its ``__init__`` has an
407 unusable first parameter (absorbed into ``*args``/``**kwargs`` or
408 keyword-only) or a later ``*args``/positional-only parameter.
409 ValueError
410 If ``name`` is already registered to an unrelated class, or ``cls``
411 is already registered under a different name, or ``name`` is empty.
412 """
413 _require_name(name)
414 _register(name, cls, stacklevel=_stacklevel)
417def embedding_architecture(name: str) -> Callable[[type[_M]], type[_M]]:
418 """
419 Class-decorator form of ``register_embedding_architecture``.
421 Trust boundary: a saved model file replays this registration by calling the named
422 constructor with whatever plain-valued ``kwargs`` it recorded. Any registered
423 constructor must be safe to call with arbitrary plain input from an untrusted file —
424 it must not open a path, unpickle a blob, or fetch a URL from a constructor
425 argument, and should treat any size-like argument as attacker-controlled. The same
426 holds for ``forward``: the size of its output must be determined by the module's
427 weights or bounded in the constructor, not set by a constructor argument alone (for
428 example a ``repeat`` count, or a one-hot encoding over ``k`` classes).
430 Constructor requirements: the loader first builds the architecture on the meta
431 device (no memory) and checks its parameter names and shapes against the weights in
432 the file, and only then builds it for real. The constructor must be
433 buildable on the meta device: allocate tensors only through standard
434 factory functions and layers (``torch.zeros``, ``torch.nn.Linear``, ...)
435 without an explicit ``device=`` (the legacy ``torch.Tensor(n, m)``
436 constructor ignores the meta device), and do not read tensor values
437 (``.item()``) or move the module (``.to(...)``) while constructing. The
438 check calls ``state_dict()`` on that meta-device module, so a
439 ``get_extra_state`` it defines must not read tensor values either. Every tensor the
440 module owns must also be in its ``state_dict``; a non-persistent buffer must not be
441 sized from a constructor argument.
443 Every architectural choice must be a constructor argument. ``save()`` rebuilds the
444 recipe the same way and refuses a module it cannot rebuild, comparing the rebuild's
445 submodules (their names, classes and, for torch's own layers, hyper-parameters such
446 as an activation's options) and weights with the live module; a submodule replaced
447 or reconfigured after construction is refused.
449 If a registered class is also decorated with ``@beartype``, put
450 ``@embedding_architecture`` ABOVE ``@beartype`` (closer to the class statement runs
451 first).
453 Parameters
454 ----------
455 name : str
456 Stable identifier stored in model files, passed through to
457 ``register_embedding_architecture``.
459 Returns
460 -------
461 Callable[[type[_M]], type[_M]]
462 A decorator that registers and returns the class unchanged.
464 Raises
465 ------
466 TypeError
467 If ``name`` is not a ``str``. Applying the decorator raises the
468 errors of ``register_embedding_architecture``.
469 ValueError
470 If ``name`` is empty.
472 Examples
473 --------
474 >>> @equine.embedding_architecture("myproject.encoder")
475 ... class Encoder(torch.nn.Module):
476 ... def __init__(self, in_features: int, out_features: int) -> None: ...
478 >>> @equine.embedding_architecture("myproject.checked_encoder")
479 ... @beartype
480 ... class CheckedEncoder(torch.nn.Module):
481 ... def __init__(self, in_features: int, out_features: int) -> None: ...
482 """
484 _require_name(name)
486 def decorator(cls: type[_M]) -> type[_M]:
487 register_embedding_architecture(name, cls, _stacklevel=4)
488 return cls
490 return decorator
493def registered_architectures() -> list[str]:
494 """
495 List the embedding architecture names registered in this process.
497 Returns
498 -------
499 list[str]
500 Registered names, sorted.
501 """
502 with _REGISTRY_LOCK:
503 return sorted(_REGISTRY)
506def embedding_recipe(module: torch.nn.Module) -> dict[str, Any] | None:
507 """
508 Return the recipe recorded on ``module``, if any.
510 Parameters
511 ----------
512 module : torch.nn.Module
513 A module instance, possibly built by a registered architecture.
515 Returns
516 -------
517 dict[str, Any] or None
518 A deep copy of the recorded ``{"builder": str, "kwargs": dict}``
519 recipe, safe for the caller to mutate; ``None`` if ``module`` was not
520 built by a registered architecture.
521 """
522 recipe = getattr(module, _RECIPE_ATTR, None)
523 if recipe is None:
524 return None
525 return copy.deepcopy(recipe)
528def build_from_recipe(recipe: dict[str, Any]) -> torch.nn.Module:
529 """
530 Instantiate a registered architecture from a recipe read out of a model file.
532 Parameters
533 ----------
534 recipe : dict[str, Any]
535 A ``{"builder": str, "kwargs": dict}`` mapping, typically produced by
536 ``embedding_recipe`` and round-tripped through a model file.
537 ``"kwargs"`` may be omitted, defaulting to ``{}``.
539 Returns
540 -------
541 torch.nn.Module
542 A freshly constructed, untrained instance of the registered architecture.
544 Raises
545 ------
546 ValueError
547 If ``recipe`` is malformed, names an architecture not registered in
548 this process, holds ``kwargs`` that are not plain values, or its
549 constructor rejects them (for example because the class's signature
550 changed since the file was saved).
551 """
552 if type(recipe) is not dict:
553 raise ValueError(
554 "Malformed embedding recipe: expected a dict with a string 'builder' "
555 f"key; got a {type(recipe).__name__}."
556 )
557 builder = recipe.get("builder")
558 if type(builder) is not str:
559 raise ValueError(
560 "Malformed embedding recipe: expected a dict with a string 'builder' "
561 f"key; got 'builder' = {reprlib.repr(builder)}."
562 )
563 kwargs = recipe.get("kwargs", {})
564 if type(kwargs) is not dict:
565 raise ValueError(
566 f"Malformed embedding recipe: 'kwargs' must be a dict; got "
567 f"{type(kwargs).__name__}."
568 )
569 if any(type(key) is not str for key in kwargs):
570 raise ValueError(
571 "Malformed embedding recipe: the keys of 'kwargs' must be strings."
572 )
573 name = builder
574 cls = _REGISTRY.get(name)
575 if cls is None:
576 known = ", ".join(registered_architectures()) or "(none)"
577 raise ValueError(
578 f"This model file was saved with embedding architecture "
579 f"{_ERROR_REPR.repr(name)}, which is not registered in this process. "
580 f"Registered: {known}. Import the module that registers it "
581 f"(@equine.embedding_architecture({_ERROR_REPR.repr(name)})), or pass the "
582 f"architecture yourself with load(..., embedding_model=YourModule(...))."
583 )
584 try:
585 # Checked before the copy, which recurses through every nested value.
586 _check_plain(kwargs)
587 # A copy, so a constructor that mutates its arguments cannot change the recipe.
588 return cls(**copy.deepcopy(kwargs))
589 except Exception as error:
590 raise ValueError(
591 f"Could not build embedding architecture {_ERROR_REPR.repr(name)} from its "
592 f"recorded recipe: {_truncate(_message_or_type(error))}"
593 ) from error