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
Termwhoseopis 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:
- Mints a fresh embedding for each variable the argument binds, via
the encoder's
var_initfunction, from the embedding of the variable's annotating argument when it has one. - 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:
|
mode
|
How the function combines its children.
TYPE:
|
args
|
The names of the operation's arguments, in positional order.
TYPE:
|
fn
|
The function mapping child embeddings to the operation's embedding.
TYPE:
|
state_var
|
The name of the threaded state argument in
TYPE:
|
prefix_var
|
The name of the running-prefix argument in
TYPE:
|
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:
|
signature
|
The Σ whose terms this encoder consumes.
TYPE:
|
sort_dims
|
Per-sort embedding dimension.
TYPE:
|
op_fns
|
One entry per constructor of Σ. The DSL compiler scaffolds defaults for omitted ops.
TYPE:
|
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
TYPE:
|
data_embedders
|
One entry per data sort: |
modules_owned
|
Modules holding the parameters of the per-op functions, registered as submodules so their parameters train.
TYPE:
|
iterations
|
Number of message-passing rounds in
TYPE:
|
init_fns
|
Per-vertex-kind initial embedders.
TYPE:
|
message_fns
|
Per-edge-kind
TYPE:
|
update_fns
|
Per-vertex-kind
TYPE:
|
readout
|
TYPE:
|
Source code in src/quivers/structural/encoder.py
forward
¶
Encode a term to its embedding by structural recursion.
| PARAMETER | DESCRIPTION |
|---|---|
term
|
The term to encode.
TYPE:
|
ctx
|
The scope the term's free bound variables refer to;
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The embedding of |
| RAISES | DESCRIPTION |
|---|---|
TypeError
|
If |
RuntimeError
|
If the term uses an operation, sort, or bound-variable index the encoder cannot interpret. |
Source code in src/quivers/structural/encoder.py
step
¶
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:
|
arguments
|
One per argument: the embedding at an object position, the raw value at a data position.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The embedding. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If |
TypeError
|
If an argument does not match the kind of its sort. |
Source code in src/quivers/structural/encoder.py
forward_graph
¶
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:
|
edges
|
Each edge's kind, source index, and target index.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tensor
|
The readout of the final vertex embeddings. |
| RAISES | DESCRIPTION |
|---|---|
RuntimeError
|
If the signature is not graph-shaped, |
Source code in src/quivers/structural/encoder.py
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 | |
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:
|
arg_dims
|
The embedding dimension of each child, in call order.
TYPE:
|
out_dim
|
The dimension of the operation's output embedding.
TYPE:
|
| 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 |
Source code in src/quivers/structural/encoder.py
make_default_var_init
¶
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:
|
out_dim
|
The dimension of the variable embedding.
TYPE:
|
| 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
encoder_draw_message
¶
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:
|
| RETURNS | DESCRIPTION |
|---|---|
str
|
The message. |
Source code in src/quivers/structural/encoder.py
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
¶
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
¶
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.