Skip to content

registry

Registry of embedding-model architectures.

An EQUINE model file describes its embedding model as a recipe: the name of a registered architecture plus the plain-valued constructor arguments it was built with. load() rebuilds the module by calling only a registered constructor, so a model file never names an import path and never carries executable content.

Recipes are recorded per exact class (a subclass must register itself to get its own recipe) and are deep-copied both when recorded and when handed back. Neither the constructor nor the caller can mutate a module's stored recipe. Registration is thread-safe.

build_from_recipe(recipe) ¤

Instantiate a registered architecture from a recipe read out of a model file.

Parameters:

Name Type Description Default
recipe dict[str, Any]

A {"builder": str, "kwargs": dict} mapping, typically produced by embedding_recipe and round-tripped through a model file. "kwargs" may be omitted, defaulting to {}.

required

Returns:

Type Description
Module

A freshly constructed, untrained instance of the registered architecture.

Raises:

Type Description
ValueError

If recipe is malformed, names an architecture not registered in this process, holds kwargs that are not plain values, or its constructor rejects them (for example because the class's signature changed since the file was saved).

Source code in src/equine/registry.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def build_from_recipe(recipe: dict[str, Any]) -> torch.nn.Module:
    """
    Instantiate a registered architecture from a recipe read out of a model file.

    Parameters
    ----------
    recipe : dict[str, Any]
        A ``{"builder": str, "kwargs": dict}`` mapping, typically produced by
        ``embedding_recipe`` and round-tripped through a model file.
        ``"kwargs"`` may be omitted, defaulting to ``{}``.

    Returns
    -------
    torch.nn.Module
        A freshly constructed, untrained instance of the registered architecture.

    Raises
    ------
    ValueError
        If ``recipe`` is malformed, names an architecture not registered in
        this process, holds ``kwargs`` that are not plain values, or its
        constructor rejects them (for example because the class's signature
        changed since the file was saved).
    """
    if type(recipe) is not dict:
        raise ValueError(
            "Malformed embedding recipe: expected a dict with a string 'builder' "
            f"key; got a {type(recipe).__name__}."
        )
    builder = recipe.get("builder")
    if type(builder) is not str:
        raise ValueError(
            "Malformed embedding recipe: expected a dict with a string 'builder' "
            f"key; got 'builder' = {reprlib.repr(builder)}."
        )
    kwargs = recipe.get("kwargs", {})
    if type(kwargs) is not dict:
        raise ValueError(
            f"Malformed embedding recipe: 'kwargs' must be a dict; got "
            f"{type(kwargs).__name__}."
        )
    if any(type(key) is not str for key in kwargs):
        raise ValueError(
            "Malformed embedding recipe: the keys of 'kwargs' must be strings."
        )
    name = builder
    cls = _REGISTRY.get(name)
    if cls is None:
        known = ", ".join(registered_architectures()) or "(none)"
        raise ValueError(
            f"This model file was saved with embedding architecture "
            f"{_ERROR_REPR.repr(name)}, which is not registered in this process. "
            f"Registered: {known}. Import the module that registers it "
            f"(@equine.embedding_architecture({_ERROR_REPR.repr(name)})), or pass the "
            f"architecture yourself with load(..., embedding_model=YourModule(...))."
        )
    try:
        # Checked before the copy, which recurses through every nested value.
        _check_plain(kwargs)
        # A copy, so a constructor that mutates its arguments cannot change the recipe.
        return cls(**copy.deepcopy(kwargs))
    except Exception as error:
        raise ValueError(
            f"Could not build embedding architecture {_ERROR_REPR.repr(name)} from its "
            f"recorded recipe: {_truncate(_message_or_type(error))}"
        ) from error

embedding_architecture(name) ¤

Class-decorator form of register_embedding_architecture.

Trust boundary: a saved model file replays this registration by calling the named constructor with whatever plain-valued kwargs it recorded. Any registered constructor must be safe to call with arbitrary plain input from an untrusted file — it must not open a path, unpickle a blob, or fetch a URL from a constructor argument, and should treat any size-like argument as attacker-controlled. The same holds for forward: the size of its output must be determined by the module's weights or bounded in the constructor, not set by a constructor argument alone (for example a repeat count, or a one-hot encoding over k classes).

Constructor requirements: the loader first builds the architecture on the meta device (no memory) and checks its parameter names and shapes against the weights in the file, and only then builds it for real. The constructor must be buildable on the meta device: allocate tensors only through standard factory functions and layers (torch.zeros, torch.nn.Linear, ...) without an explicit device= (the legacy torch.Tensor(n, m) constructor ignores the meta device), and do not read tensor values (.item()) or move the module (.to(...)) while constructing. The check calls state_dict() on that meta-device module, so a get_extra_state it defines must not read tensor values either. Every tensor the module owns must also be in its state_dict; a non-persistent buffer must not be sized from a constructor argument.

Every architectural choice must be a constructor argument. save() rebuilds the recipe the same way and refuses a module it cannot rebuild, comparing the rebuild's submodules (their names, classes and, for torch's own layers, hyper-parameters such as an activation's options) and weights with the live module; a submodule replaced or reconfigured after construction is refused.

If a registered class is also decorated with @beartype, put @embedding_architecture ABOVE @beartype (closer to the class statement runs first).

Parameters:

Name Type Description Default
name str

Stable identifier stored in model files, passed through to register_embedding_architecture.

required

Returns:

Type Description
Callable[[type[_M]], type[_M]]

A decorator that registers and returns the class unchanged.

Raises:

Type Description
TypeError

If name is not a str. Applying the decorator raises the errors of register_embedding_architecture.

ValueError

If name is empty.

Examples:

>>> @equine.embedding_architecture("myproject.encoder")
... class Encoder(torch.nn.Module):
...     def __init__(self, in_features: int, out_features: int) -> None: ...
>>> @equine.embedding_architecture("myproject.checked_encoder")
... @beartype
... class CheckedEncoder(torch.nn.Module):
...     def __init__(self, in_features: int, out_features: int) -> None: ...
Source code in src/equine/registry.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
def embedding_architecture(name: str) -> Callable[[type[_M]], type[_M]]:
    """
    Class-decorator form of ``register_embedding_architecture``.

    Trust boundary: a saved model file replays this registration by calling the named
    constructor with whatever plain-valued ``kwargs`` it recorded. Any registered
    constructor must be safe to call with arbitrary plain input from an untrusted file —
    it must not open a path, unpickle a blob, or fetch a URL from a constructor
    argument, and should treat any size-like argument as attacker-controlled. The same
    holds for ``forward``: the size of its output must be determined by the module's
    weights or bounded in the constructor, not set by a constructor argument alone (for
    example a ``repeat`` count, or a one-hot encoding over ``k`` classes).

    Constructor requirements: the loader first builds the architecture on the meta
    device (no memory) and checks its parameter names and shapes against the weights in
    the file, and only then builds it for real. The constructor must be
    buildable on the meta device: allocate tensors only through standard
    factory functions and layers (``torch.zeros``, ``torch.nn.Linear``, ...)
    without an explicit ``device=`` (the legacy ``torch.Tensor(n, m)``
    constructor ignores the meta device), and do not read tensor values
    (``.item()``) or move the module (``.to(...)``) while constructing. The
    check calls ``state_dict()`` on that meta-device module, so a
    ``get_extra_state`` it defines must not read tensor values either. Every tensor the
    module owns must also be in its ``state_dict``; a non-persistent buffer must not be
    sized from a constructor argument.

    Every architectural choice must be a constructor argument. ``save()`` rebuilds the
    recipe the same way and refuses a module it cannot rebuild, comparing the rebuild's
    submodules (their names, classes and, for torch's own layers, hyper-parameters such
    as an activation's options) and weights with the live module; a submodule replaced
    or reconfigured after construction is refused.

    If a registered class is also decorated with ``@beartype``, put
    ``@embedding_architecture`` ABOVE ``@beartype`` (closer to the class statement runs
    first).

    Parameters
    ----------
    name : str
        Stable identifier stored in model files, passed through to
        ``register_embedding_architecture``.

    Returns
    -------
    Callable[[type[_M]], type[_M]]
        A decorator that registers and returns the class unchanged.

    Raises
    ------
    TypeError
        If ``name`` is not a ``str``. Applying the decorator raises the
        errors of ``register_embedding_architecture``.
    ValueError
        If ``name`` is empty.

    Examples
    --------
    >>> @equine.embedding_architecture("myproject.encoder")
    ... class Encoder(torch.nn.Module):
    ...     def __init__(self, in_features: int, out_features: int) -> None: ...

    >>> @equine.embedding_architecture("myproject.checked_encoder")
    ... @beartype
    ... class CheckedEncoder(torch.nn.Module):
    ...     def __init__(self, in_features: int, out_features: int) -> None: ...
    """

    _require_name(name)

    def decorator(cls: type[_M]) -> type[_M]:
        register_embedding_architecture(name, cls, _stacklevel=4)
        return cls

    return decorator

embedding_recipe(module) ¤

Return the recipe recorded on module, if any.

Parameters:

Name Type Description Default
module Module

A module instance, possibly built by a registered architecture.

required

Returns:

Type Description
dict[str, Any] or None

A deep copy of the recorded {"builder": str, "kwargs": dict} recipe, safe for the caller to mutate; None if module was not built by a registered architecture.

Source code in src/equine/registry.py
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def embedding_recipe(module: torch.nn.Module) -> dict[str, Any] | None:
    """
    Return the recipe recorded on ``module``, if any.

    Parameters
    ----------
    module : torch.nn.Module
        A module instance, possibly built by a registered architecture.

    Returns
    -------
    dict[str, Any] or None
        A deep copy of the recorded ``{"builder": str, "kwargs": dict}``
        recipe, safe for the caller to mutate; ``None`` if ``module`` was not
        built by a registered architecture.
    """
    recipe = getattr(module, _RECIPE_ATTR, None)
    if recipe is None:
        return None
    return copy.deepcopy(recipe)

register_embedding_architecture(name, cls, *, _stacklevel=3) ¤

Register cls under name and make its instances carry a recipe.

Every instance of exactly cls (not an unregistered subclass) records the arguments it was constructed with (defaults applied, **kwargs flattened in), through a wrapper around the class's __init__. Those arguments must be plain values, with lists, tuples and dicts nested at most 100 levels deep. Registering the exact same class object under the same name again is a no-op. Re-registering under the same name a different class object with the same __module__ and __qualname__ (as happens after importlib.reload or re-running a notebook cell that redefines the class) replaces the registration and emits a UserWarning; a genuinely different class raises ValueError. Registering one class object under two different names also raises ValueError. Concurrent registrations resolve deterministically: the whole check-then-register sequence, including the two-names check, is serialized on a module-level lock.

Parameters:

Name Type Description Default
name str

Stable identifier stored in model files. Namespace it by project ("myproject.encoder"). Never an import path.

required
cls type[_M]

The architecture class. It must not inherit torch.nn.Module.__init__ unchanged (an __init__ inherited from a user-defined base class is recorded with that base's signature). Its __init__ needs a plain first (instance) parameter and named, non-variadic-positional, non-positional-only constructor arguments after it.

required

Raises:

Type Description
TypeError

If name is not a str, cls inherits torch.nn.Module.__init__ unchanged, or its __init__ has an unusable first parameter (absorbed into *args/**kwargs or keyword-only) or a later *args/positional-only parameter.

ValueError

If name is already registered to an unrelated class, or cls is already registered under a different name, or name is empty.

Source code in src/equine/registry.py
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def register_embedding_architecture(
    name: str, cls: type[_M], *, _stacklevel: int = 3
) -> None:
    """
    Register ``cls`` under ``name`` and make its instances carry a recipe.

    Every instance of exactly ``cls`` (not an unregistered subclass) records the
    arguments it was constructed with (defaults applied, ``**kwargs`` flattened in),
    through a wrapper around the class's ``__init__``. Those
    arguments must be plain values, with lists, tuples and dicts nested at
    most 100 levels deep. Registering the exact same class object
    under the same name again is a no-op. Re-registering under the same name
    a *different* class object with the same ``__module__`` and
    ``__qualname__`` (as happens after ``importlib.reload`` or re-running a
    notebook cell that redefines the class) replaces the registration and
    emits a ``UserWarning``; a genuinely different class raises
    ``ValueError``. Registering one class object under two different names
    also raises ``ValueError``. Concurrent registrations resolve deterministically: the
    whole check-then-register sequence, including the two-names check, is serialized on
    a module-level lock.

    Parameters
    ----------
    name : str
        Stable identifier stored in model files. Namespace it by project
        (``"myproject.encoder"``). Never an import path.
    cls : type[_M]
        The architecture class. It must not inherit ``torch.nn.Module.__init__``
        unchanged (an ``__init__`` inherited from a user-defined base class is
        recorded with that base's signature). Its ``__init__`` needs a plain
        first (instance) parameter and named, non-variadic-positional,
        non-positional-only constructor arguments after it.

    Raises
    ------
    TypeError
        If ``name`` is not a ``str``, ``cls`` inherits
        ``torch.nn.Module.__init__`` unchanged, or its ``__init__`` has an
        unusable first parameter (absorbed into ``*args``/``**kwargs`` or
        keyword-only) or a later ``*args``/positional-only parameter.
    ValueError
        If ``name`` is already registered to an unrelated class, or ``cls``
        is already registered under a different name, or ``name`` is empty.
    """
    _require_name(name)
    _register(name, cls, stacklevel=_stacklevel)

registered_architectures() ¤

List the embedding architecture names registered in this process.

Returns:

Type Description
list[str]

Registered names, sorted.

Source code in src/equine/registry.py
493
494
495
496
497
498
499
500
501
502
503
def registered_architectures() -> list[str]:
    """
    List the embedding architecture names registered in this process.

    Returns
    -------
    list[str]
        Registered names, sorted.
    """
    with _REGISTRY_LOCK:
        return sorted(_REGISTRY)