Skip to content

Encoders

An encoder folds a term into a vector by combining its children's vectors into a vector for their parent. Encoder is a torch.nn.Module that implements this fold, the catamorphism \(T_\Sigma \to \mathrm{Vec}_D\) out of the initial algebra of terms over a signature (Lambek, 1968), as in recursive and tree-structured neural encoders (Tai et al., 2015). The framework gives the recursion, and the function for each operation is either given by the analyst or generated by the compiler as a two-layer MLP whose input dimensions follow the operation's arguments. The learned functions determine which distinctions of the input the vector keeps.

For binders, the framework threads a typed context Γ of de Bruijn indices through the recursion. It compresses each binder's annotations in the outer context, creates variable embeddings with var_init_fns, and recurses over the scoped arguments in the extended context.

forward_graph encodes graph signatures as a message-passing network (Battaglia et al., 2018). It applies an initial embedder for each vertex kind, a fixed number of rounds of message passing with functions indexed by edge and vertex kind, and a readout that reduces the final vertex embeddings to one vector for the graph.

encoder

Encoder runtime: F-algebra homomorphisms T_Σ -> Vec_D.

A Encoder is a torch.nn.Module that, given a closed Term over a signature, returns its vector embedding. The recursion structure is supplied by the framework (algebra homomorphism); per-operation parametric functions are supplied by the user (declared in a encoder { … } DSL block) or by the default scaffolding.

Canonical term form

A term over Σ has exactly one of three argument shapes at each position, determined by the codomain sort's kind:

  • object: the argument is a Term whose op is a constructor of Σ or the reserved built-in "BoundVar".
  • data: the argument is a raw Python value (string, int, float, …) consumed by the encoder's per-data-sort embedder.
  • index: the argument is a non-negative integer denoting a de-Bruijn index into the current scope context Γ.

No Term("Data", …) or other wrappings are accepted at runtime; the canonical form is the only form.

The reserved "BoundVar" op is the built-in de-Bruijn reference: Term("BoundVar", (i,)) at an object position reads the i-th in-scope variable's embedding from Γ.

Binding constructors thread a Context of in-scope variables: each entry records the variable's sort, its embedding, and the annotation term captured at binding. Compressing a constructor whose arguments bind variables visits its arguments in order. For each argument it:

  1. Mints a fresh embedding for each variable the argument binds, via the encoder's var_init function, from the embedding of the variable's annotating argument when it has one.
  2. Pushes the new entries onto Γ and compresses the argument under the extended context, so an unbound argument sees the outer context.

Graph-shaped signatures are compressed by forward_graph: per-vertex-kind init seeds initial embeddings, finitely many message_passing rounds alternate per-edge-kind message and per-vertex-kind update functions, and a readout reduces the final per-vertex embeddings to one fixed-length vector.

PerOpFn didactic-model

PerOpFn(*, op: str, mode: PerOpMode, args: tuple[str, ...], fn: Callable[..., Tensor] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), state_var: str | None = None, prefix_var: str | None = None)

Bases: ValueModel

A per-operation parametric function.

mode is "plain" (algebra-hom), "recurrent" (left-fold across a list-shaped signature) or "attention" (each step sees a running prefix list). For plain rules, fn is called with one positional argument per child embedding; for recurrent / attention the framework threads state / prefix arguments alongside the children.

Function identity participates in equality and hashing. Copying or updating the record retains the callable and its live parameters.

PARAMETER DESCRIPTION
op

The constructor name the function interprets.

TYPE: str

mode

How the function combines its children.

TYPE: PerOpMode

args

The names of the operation's arguments, in positional order.

TYPE: tuple[str, ...]

fn

The function mapping child embeddings to the operation's embedding.

TYPE: Callable[..., Tensor] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

state_var

The name of the threaded state argument in "recurrent" mode.

TYPE: str or None DEFAULT: None

prefix_var

The name of the running-prefix argument in "attention" mode.

TYPE: str or None DEFAULT: None

Encoder

Encoder(name: str, signature: Signature, sort_dims: dict[str, int], op_fns: dict[str, PerOpFn], var_init_fns: dict[tuple[str, str] | str, Callable[[Tensor | None], Tensor]], data_embedders: dict[str, Callable[[DataLeaf], Tensor]], modules_owned: list[Module] | None = None, iterations: int = 0, init_fns: dict[str, Callable[[DataLeaf], Tensor]] | None = None, message_fns: dict[str, Callable[..., Tensor]] | None = None, update_fns: dict[str, Callable[..., Tensor]] | None = None, readout: Callable[[list[Tensor]], Tensor] | None = None)

Bases: Module

An F-algebra homomorphism T_Σ -> Vec_D realised as an nn.Module.

The graph-specific parameters (iterations, init_fns, message_fns, update_fns, readout) are used only by forward_graph on a graph-shaped signature.

PARAMETER DESCRIPTION
name

Identifier used in diagnostics.

TYPE: str

signature

The Σ whose terms this encoder consumes.

TYPE: Signature

sort_dims

Per-sort embedding dimension.

TYPE: dict[str, int]

op_fns

One entry per constructor of Σ. The DSL compiler scaffolds defaults for omitted ops.

TYPE: dict[str, PerOpFn]

var_init_fns

Variable initialisers called at every binding argument to mint a fresh embedding for each variable it introduces. An annotated variable is keyed by (var_sort, annot_sort) and receives the annotation's embedding; an unannotated one is keyed by var_sort and receives None.

TYPE: dict[tuple[str, str] | str, Callable]

data_embedders

One entry per data sort: (raw_value) -> embedding.

TYPE: dict[str, Callable[[DataLeaf], Tensor]]

modules_owned

Modules holding the parameters of the per-op functions, registered as submodules so their parameters train.

TYPE: list[Module] or None DEFAULT: None

iterations

Number of message-passing rounds in forward_graph.

TYPE: int DEFAULT: 0

init_fns

Per-vertex-kind initial embedders.

TYPE: dict[str, Callable[[DataLeaf], Tensor]] or None DEFAULT: None

message_fns

Per-edge-kind (src_e, tgt_e) -> message functions.

TYPE: dict[str, Callable[..., Tensor]] or None DEFAULT: None

update_fns

Per-vertex-kind (self_e, aggregated_msg) -> next_e.

TYPE: dict[str, Callable[..., Tensor]] or None DEFAULT: None

readout

(list[Vec_D]) -> Vec_D reducer.

TYPE: Callable[[list[Tensor]], Tensor] or None DEFAULT: None

Source code in src/quivers/structural/encoder.py
def __init__(
    self,
    name: str,
    signature: Signature,
    sort_dims: dict[str, int],
    op_fns: dict[str, PerOpFn],
    var_init_fns: dict[
        tuple[str, str] | str,
        Callable[[torch.Tensor | None], torch.Tensor],
    ],
    data_embedders: dict[str, Callable[[DataLeaf], torch.Tensor]],
    modules_owned: list[nn.Module] | None = None,
    iterations: int = 0,
    init_fns: dict[str, Callable[[DataLeaf], torch.Tensor]] | None = None,
    message_fns: dict[str, Callable[..., torch.Tensor]] | None = None,
    update_fns: dict[str, Callable[..., torch.Tensor]] | None = None,
    readout: Callable[[list[torch.Tensor]], torch.Tensor] | None = None,
) -> None:
    super().__init__()
    self.name = name
    self.signature = signature
    self.sort_dims = dict(sort_dims)
    self.op_fns = dict(op_fns)
    # Keyed by `(var_sort, annot_sort)` for annotated binders or
    # by `var_sort` (a plain string) for unannotated ones.
    self.var_init_fns: dict[
        tuple[str, str] | str,
        Callable[[torch.Tensor | None], torch.Tensor],
    ] = dict(var_init_fns)
    self.data_embedders = dict(data_embedders)
    self.iterations = iterations
    self.init_fns = dict(init_fns or {})
    self.message_fns = dict(message_fns or {})
    self.update_fns = dict(update_fns or {})
    self.readout = readout
    for i, m in enumerate(modules_owned or []):
        self.add_module(f"_op_{i}", m)

forward

forward(term: Term, ctx: Context | None = None) -> Tensor

Encode a term to its embedding by structural recursion.

PARAMETER DESCRIPTION
term

The term to encode.

TYPE: Term

ctx

The scope the term's free bound variables refer to; EMPTY_CONTEXT when omitted.

TYPE: Context or None DEFAULT: None

RETURNS DESCRIPTION
Tensor

The embedding of term.

RAISES DESCRIPTION
TypeError

If term is not a Term, or an argument does not match the kind of its sort.

RuntimeError

If the term uses an operation, sort, or bound-variable index the encoder cannot interpret.

Source code in src/quivers/structural/encoder.py
def forward(self, term: Term, ctx: Context | None = None) -> torch.Tensor:
    """Encode a term to its embedding by structural recursion.

    Parameters
    ----------
    term : Term
        The term to encode.
    ctx : Context or None
        The scope the term's free bound variables refer to;
        `EMPTY_CONTEXT` when omitted.

    Returns
    -------
    torch.Tensor
        The embedding of ``term``.

    Raises
    ------
    TypeError
        If ``term`` is not a `Term`, or an argument does not match
        the kind of its sort.
    RuntimeError
        If the term uses an operation, sort, or bound-variable
        index the encoder cannot interpret.
    """
    if not isinstance(term, Term):
        raise TypeError(
            f"encoder {self.name!r}: expected a Term at the root, got "
            f"{type(term).__name__} ({term!r}); construct one with "
            f"`make_term` or `bound_var`"
        )
    return self._compress_object(term, ctx or EMPTY_CONTEXT)

step

step(op: str, arguments: tuple[Tensor | DataLeaf, ...]) -> Tensor

Apply one constructor's function to embedded children.

This is the algebra map of the homomorphism at one node: the embedding of op(t_1, ..., t_n) from the embeddings of its object arguments and the raw values of its data arguments. Folding it over a term gives forward; folding it over a structure that shares subterms, such as a packed forest, computes each shared subterm's embedding once.

PARAMETER DESCRIPTION
op

A constructor of the signature.

TYPE: str

arguments

One per argument: the embedding at an object position, the raw value at a data position.

TYPE: tuple of torch.Tensor or DataLeaf

RETURNS DESCRIPTION
Tensor

The embedding.

RAISES DESCRIPTION
RuntimeError

If op is not a constructor, its arity differs, it has an index argument, or its function reads the whole chain of arguments (attention mode), which needs the term.

TypeError

If an argument does not match the kind of its sort.

Source code in src/quivers/structural/encoder.py
def step(
    self, op: str, arguments: tuple[torch.Tensor | DataLeaf, ...]
) -> torch.Tensor:
    """Apply one constructor's function to embedded children.

    This is the algebra map of the homomorphism at one node: the
    embedding of ``op(t_1, ..., t_n)`` from the embeddings of its
    object arguments and the raw values of its data arguments. Folding
    it over a term gives `forward`; folding it over a structure that
    shares subterms, such as a packed forest, computes each shared
    subterm's embedding once.

    Parameters
    ----------
    op : str
        A constructor of the signature.
    arguments : tuple of torch.Tensor or DataLeaf
        One per argument: the embedding at an object position, the
        raw value at a data position.

    Returns
    -------
    torch.Tensor
        The embedding.

    Raises
    ------
    RuntimeError
        If ``op`` is not a constructor, its arity differs, it has an
        index argument, or its function reads the whole chain of
        arguments (attention mode), which needs the term.
    TypeError
        If an argument does not match the kind of its sort.
    """
    constructor = self.signature.constructors.get(op)
    if constructor is None:
        raise RuntimeError(
            f"encoder {self.name!r}: {op!r} is not a constructor of "
            f"signature {self.signature.name!r}"
        )
    if len(arguments) != constructor.arity:
        raise RuntimeError(
            f"encoder {self.name!r}: constructor {op!r} expects "
            f"{constructor.arity} arguments, got {len(arguments)}"
        )
    rule = self._require_op_fn(op)
    if rule.mode == "attention":
        raise RuntimeError(
            f"encoder {self.name!r}: {op!r} attends over its whole chain "
            "of arguments, so it is encoded from the term"
        )
    children: list[torch.Tensor] = []
    for sort, argument in zip(constructor.domain, arguments, strict=True):
        kind = self.signature.sorts[sort].kind
        if kind == "object":
            if not isinstance(argument, torch.Tensor):
                raise TypeError(
                    f"encoder {self.name!r}: object-sorted argument of {op!r} "
                    f"at sort {sort!r} must be an embedding"
                )
            children.append(argument)
        elif kind == "data":
            if isinstance(argument, torch.Tensor):
                raise TypeError(
                    f"encoder {self.name!r}: data-sorted argument of {op!r} "
                    f"at sort {sort!r} must be a raw value"
                )
            children.append(self._compress_arg(argument, sort, EMPTY_CONTEXT))
        else:
            raise RuntimeError(
                f"encoder {self.name!r}: {op!r} has an index argument, "
                "which needs the scope of a term"
            )
    return rule.fn(*children)

forward_graph

forward_graph(vertices: list[tuple[str, DataLeaf]], edges: list[tuple[str, int, int]]) -> Tensor

Encode a graph by message passing followed by a readout.

Each vertex is initialised by its kind's initial embedder; each of iterations rounds sends a message along every edge (both ways for an undirected edge kind), averages each vertex's inbox, and applies its kind's update function.

PARAMETER DESCRIPTION
vertices

Each vertex's kind and payload.

TYPE: list[tuple[str, DataLeaf]]

edges

Each edge's kind, source index, and target index.

TYPE: list[tuple[str, int, int]]

RETURNS DESCRIPTION
Tensor

The readout of the final vertex embeddings.

RAISES DESCRIPTION
RuntimeError

If the signature is not graph-shaped, iterations is not positive, an edge references an out-of-range vertex or an unknown edge kind, or a needed initial, message, update, or readout function is missing.

Source code in src/quivers/structural/encoder.py
def forward_graph(
    self,
    vertices: list[tuple[str, DataLeaf]],
    edges: list[tuple[str, int, int]],
) -> torch.Tensor:
    """Encode a graph by message passing followed by a readout.

    Each vertex is initialised by its kind's initial embedder;
    each of ``iterations`` rounds sends a message along every edge
    (both ways for an undirected edge kind), averages each
    vertex's inbox, and applies its kind's update function.

    Parameters
    ----------
    vertices : list[tuple[str, DataLeaf]]
        Each vertex's kind and payload.
    edges : list[tuple[str, int, int]]
        Each edge's kind, source index, and target index.

    Returns
    -------
    torch.Tensor
        The readout of the final vertex embeddings.

    Raises
    ------
    RuntimeError
        If the signature is not graph-shaped, ``iterations`` is not
        positive, an edge references an out-of-range vertex or an
        unknown edge kind, or a needed initial, message, update, or
        readout function is missing.
    """
    if not self.signature.is_graph():
        raise RuntimeError(
            f"encoder {self.name!r}: forward_graph requires a graph signature"
        )
    if self.iterations <= 0:
        raise RuntimeError(
            f"encoder {self.name!r}: graph encoder requires `iterations` > 0"
        )

    embeds: list[torch.Tensor] = []
    for vkind, payload in vertices:
        init = self.init_fns.get(vkind)
        if init is None:
            raise RuntimeError(
                f"encoder {self.name!r}: no init for vertex_kind {vkind!r}"
            )
        embeds.append(init(payload))

    for _ in range(self.iterations):
        inboxes: list[list[torch.Tensor]] = [[] for _ in vertices]
        for ekind, src, tgt in edges:
            if src < 0 or tgt < 0 or src >= len(vertices) or tgt >= len(vertices):
                raise RuntimeError(
                    f"encoder {self.name!r}: edge {(ekind, src, tgt)} "
                    f"references out-of-range vertex"
                )
            edge_spec = self.signature.edge_kinds.get(ekind)
            if edge_spec is None:
                raise RuntimeError(
                    f"encoder {self.name!r}: unknown edge_kind {ekind!r}"
                )
            m_fn = self.message_fns.get(ekind)
            if m_fn is None:
                raise RuntimeError(
                    f"encoder {self.name!r}: no message fn for edge_kind {ekind!r}"
                )
            inboxes[tgt].append(m_fn(embeds[src], embeds[tgt]))
            if not edge_spec.directed:
                inboxes[src].append(m_fn(embeds[tgt], embeds[src]))

        new_embeds = list(embeds)
        for i, (vkind, _) in enumerate(vertices):
            upd = self.update_fns.get(vkind)
            if upd is None:
                raise RuntimeError(
                    f"encoder {self.name!r}: no update fn for vertex_kind {vkind!r}"
                )
            msgs = inboxes[i]
            if msgs:
                agg = torch.stack(msgs, dim=0).mean(dim=0)
            else:
                agg = torch.zeros_like(embeds[i])
            new_embeds[i] = upd(embeds[i], agg)
        embeds = new_embeds

    if self.readout is None:
        raise RuntimeError(
            f"encoder {self.name!r}: graph encoder requires a readout function"
        )
    return self.readout(embeds)

make_default_op_fn

make_default_op_fn(op: str, arg_dims: tuple[int, ...], out_dim: int) -> tuple[Module, Callable[..., Tensor]]

Build a parametric per-op function as a 2-layer MLP over concatenated child embeddings.

arg_dims is the tuple of per-argument dimensions in the order in which the children are passed to the function, which is the order of the constructor's arguments whether or not they bind variables. A nullary operation gets a learned constant vector instead of an MLP.

PARAMETER DESCRIPTION
op

The operation name, used in parameter names and diagnostics.

TYPE: str

arg_dims

The embedding dimension of each child, in call order.

TYPE: tuple[int, ...]

out_dim

The dimension of the operation's output embedding.

TYPE: int

RETURNS DESCRIPTION
tuple[Module, Callable[..., Tensor]]

The module owning the parameters, and the function that maps the child embeddings to the output embedding.

RAISES DESCRIPTION
RuntimeError

Raised by the returned function when it is called with a number of children other than len(arg_dims).

Source code in src/quivers/structural/encoder.py
def make_default_op_fn(
    op: str,
    arg_dims: tuple[int, ...],
    out_dim: int,
) -> tuple[nn.Module, Callable[..., torch.Tensor]]:
    """Build a parametric per-op function as a 2-layer MLP over
    concatenated child embeddings.

    ``arg_dims`` is the tuple of per-argument dimensions in the
    order in which the children are passed to the function, which is
    the order of the constructor's arguments whether or not they bind
    variables. A nullary operation gets a learned constant vector
    instead of an MLP.

    Parameters
    ----------
    op : str
        The operation name, used in parameter names and diagnostics.
    arg_dims : tuple[int, ...]
        The embedding dimension of each child, in call order.
    out_dim : int
        The dimension of the operation's output embedding.

    Returns
    -------
    tuple[nn.Module, Callable[..., torch.Tensor]]
        The module owning the parameters, and the function that maps
        the child embeddings to the output embedding.

    Raises
    ------
    RuntimeError
        Raised by the returned function when it is called with a
        number of children other than ``len(arg_dims)``.
    """
    arity = len(arg_dims)
    if arity == 0:
        param = nn.Parameter(torch.randn(out_dim) * 0.1)
        mod = nn.Module()
        mod.register_parameter(f"const_{op}", param)

        def constant() -> torch.Tensor:
            """The constant's embedding.

            Returns
            -------
            torch.Tensor
                The parameter.
            """
            return param

        return mod, constant

    in_dim = sum(arg_dims)
    hidden = max(out_dim, 64)
    mlp = nn.Sequential(
        nn.Linear(in_dim, hidden),
        nn.Tanh(),
        nn.Linear(hidden, out_dim),
    )

    def call(*children: torch.Tensor) -> torch.Tensor:
        if len(children) != arity:
            raise RuntimeError(
                f"op {op!r}: expected {arity} children, got {len(children)}"
            )
        cat = torch.cat([c.reshape(-1) for c in children], dim=-1)
        return mlp(cat)

    return mlp, call

make_default_var_init

make_default_var_init(in_dim: int, out_dim: int) -> tuple[Module, Callable[[Tensor], Tensor]]

A parametric var_init(ty) function: an MLP mapping a type embedding to a fresh variable embedding.

PARAMETER DESCRIPTION
in_dim

The dimension of the type-annotation embedding.

TYPE: int

out_dim

The dimension of the variable embedding.

TYPE: int

RETURNS DESCRIPTION
tuple[Module, Callable[[Tensor], Tensor]]

The MLP owning the parameters, and the function that maps a type embedding to a variable embedding.

Source code in src/quivers/structural/encoder.py
def make_default_var_init(
    in_dim: int, out_dim: int
) -> tuple[nn.Module, Callable[[torch.Tensor], torch.Tensor]]:
    """A parametric `var_init(ty)` function: an MLP mapping a type
    embedding to a fresh variable embedding.

    Parameters
    ----------
    in_dim : int
        The dimension of the type-annotation embedding.
    out_dim : int
        The dimension of the variable embedding.

    Returns
    -------
    tuple[nn.Module, Callable[[torch.Tensor], torch.Tensor]]
        The MLP owning the parameters, and the function that maps a
        type embedding to a variable embedding.
    """
    mlp = nn.Sequential(
        nn.Linear(in_dim, max(out_dim, 64)),
        nn.Tanh(),
        nn.Linear(max(out_dim, 64), out_dim),
    )

    def call(ty: torch.Tensor) -> torch.Tensor:
        return mlp(ty.reshape(-1))

    return mlp, call

encoder_draw_message

encoder_draw_message(name: str) -> str

The refusal of a program sample or observe from an encoder.

An encoder is a deterministic map from the terms of its signature to code vectors, so no program step draws from it.

PARAMETER DESCRIPTION
name

The encoder's name.

TYPE: str

RETURNS DESCRIPTION
str

The message.

Source code in src/quivers/structural/encoder.py
def encoder_draw_message(name: str) -> str:
    """The refusal of a program ``sample`` or ``observe`` from an encoder.

    An encoder is a deterministic map from the terms of its signature to
    code vectors, so no program step draws from it.

    Parameters
    ----------
    name : str
        The encoder's name.

    Returns
    -------
    str
        The message.
    """
    return (
        f"{name!r} is an encoder, a deterministic map from terms of its "
        "signature to code vectors, so no program step draws from it; call it "
        f"on a term in a loss body, as in `{name}(term)`"
    )

Type aliases and constants

Structural compression: signatures, encoders, decoders, losses.

Runtime substrate for QVR signatures, encoders, decoders, and attached losses: second-order binding signatures with their generated term operations, and a uniform algebraic interface for compressing structured objects to fixed-length vectors and decoding them under a learned distribution.

BOUND_VAR_OP module-attribute

BOUND_VAR_OP = 'BoundVar'

The reserved op name of a bound-variable term.

A Term whose op is this name refers to a variable a binding argument introduced. The signature compiler forbids it as a user-declared constructor name.

PerOpMode

PerOpMode = Literal['plain', 'recurrent', 'attention']

How a PerOpFn combines its children: "plain" applies the function once, "recurrent" left-folds it across a list-shaped signature, and "attention" gives each step the running prefix.

Cited sources

Joachim Lambek. A Fixpoint Theorem for Complete Categories. Mathematische Zeitschrift, 103:151–161, 1968. URL: https://link.springer.com/article/10.1007/BF01110627, doi:10.1007/BF01110627.

Kai Sheng Tai, Richard Socher, and Christopher D. Manning. Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks. In Proceedings of the 53rd Annual Meeting of the Association for Computational Linguistics and the 7th International Joint Conference on Natural Language Processing (Volume 1: Long Papers), 1556–1566. Association for Computational Linguistics, 2015. URL: https://aclanthology.org/P15-1150/, doi:10.3115/v1/P15-1150.

Peter W. Battaglia, Jessica B. Hamrick, Victor Bapst, Alvaro Sanchez-Gonzalez, Vinicius Zambaldi, Mateusz Malinowski, Andrea Tacchetti, David Raposo, Adam Santoro, Ryan Faulkner, Caglar Gulcehre, Francis Song, Andrew Ballard, Justin Gilmer, George Dahl, Ashish Vaswani, Kelsey Allen, Charles Nash, Victoria Langston, Chris Dyer, Nicolas Heess, Daan Wierstra, Pushmeet Kohli, Matt Botvinick, Oriol Vinyals, Yujia Li, and Razvan Pascanu. Relational Inductive Biases, Deep Learning, and Graph Networks. arXiv preprint arXiv:1806.01261, 2018. URL: https://arxiv.org/abs/1806.01261, doi:10.48550/arXiv.1806.01261.