Tree and graph autoencoders¶
The declarations syntax, encoder, decoder, and loss define neural encoders and decoders
over terms and graphs, which the library calls structural compression. A signature fixes the
well-formed terms. An encoder folds a term into a vector, one learned function per constructor,
as recursive autoencoders and tree-structured networks do (Pollack, 1990; Tai et al., 2015).
A decoder maps a vector to a probability distribution over terms, and a loss is a scalar objective
attached to one of these computations
(Tree and graph autoencoders: signatures and encoders).
For a list with constructors Nil and Cons, encoding Cons(a, Nil) encodes a, takes the vector
of Nil, and applies the learned function for Cons to the two vectors. The recursion follows the
shape of the term, and the learned functions decide how its parts are represented. This kind of
recursion is a catamorphism (§2.2).
1. Signatures¶
A syntax declaration
in which each argument \(A_i\) is a sort \(s_i\), a labeled sort \((\ell_i : s_i)\), or a sort under
binders \((x_{i,1} : v_{i,1} [: \ell], \dots, x_{i,m_i} : v_{i,m_i}).s_i\), declares a many-sorted
second-order binding signature (Fiore et al., 1999; Fiore and Hur, 2010). Each argument has its own
binding arity: the list of variables, each with a sort, that are in scope in that argument and
nowhere else, so one constructor may mix bound and unbound arguments
(Let : Term, (x : Term).Term -> Term). A bound variable may carry an annotation \(\ell\), the label of
an earlier unbound argument of the same constructor (Lam : (ty : Type), (x : Term : ty).Term -> Term).
Its terms are the term algebra over the signature,
extended with bound variables. A binding signature is not a
generalized algebraic theory, whose
sorts may depend on terms (Cartmell, 1986): here the sorts are a fixed finite set.
1.1 Sorts¶
Each sort has one of three kinds:
| Kind | Role | Terms of the sort |
|---|---|---|
object |
a sort the encoder folds recursively | the terms built from constructors and variables |
data |
leaves whose values are opaque tokens, optionally a closed vocabulary vocab { ... } |
the tokens |
index |
a de Bruijn index into the bound variables | \(\mathbb{N}\) |
Write \(S = S_{\mathrm{obj}} \sqcup S_{\mathrm{dat}} \sqcup S_{\mathrm{idx}}\) for the sorts. The option
dim d gives a sort a default dimension \(d_s\), which an encoder or decoder may override.
1.2 Contexts and terms¶
A de Bruijn index names a bound variable by the number of binders between its occurrence and its binder, so that renaming bound variables does not change a term and an inner variable is told apart from an outer one with the same name (de Bruijn, 1972). A context is a finite list
of the variables in scope, each with its sort \(v_i \in S\) and an optional annotation term \(a_i\). We
write \(\Gamma\langle i \rangle\) for the entry at index \(i\), counting from \(0\) for the innermost, most
recently bound variable, as the runtime class Context does. Indices run over one space shared by
every sort. The encoder keeps, beside \(\Gamma\), a list
\(\varepsilon = (\varepsilon_0, \dots, \varepsilon_{k-1})\) of embeddings with
\(\varepsilon_i \in \mathbb{R}^{d_{v_i}}\), where \(\varepsilon_i\) is the vector the encoder's var_init
rule computed at the binder (§2.1).
The terms of sort \(s\) in context \(\Gamma\), written \(\Gamma \vdash_\Sigma t : s\), are generated by three rules. They are closed terms when \(\Gamma\) is empty and open terms otherwise.
- Data leaf. If \(s \in S_{\mathrm{dat}}\) and \(d\) is in the vocabulary of \(s\) (any value when \(s\) has no vocabulary), then \(\Gamma \vdash_\Sigma \mathrm{Data}_s(d) : s\).
- Bound variable. If \(\Gamma\langle i \rangle = (s, a)\), then \(\Gamma \vdash_\Sigma \mathrm{BoundVar}(i) : s\).
- Constructor. For a constructor \(c : A_1, \dots, A_n \to t\) whose argument \(i\) binds \((x_{i,1} : v_{i,1}, \dots, x_{i,m_i} : v_{i,m_i})\) over sort \(s_i\), if \(\Gamma \cdot (v_{i,1}, \alpha_{i,1}) \cdots (v_{i,m_i}, \alpha_{i,m_i}) \vdash_\Sigma u_i : s_i\) for each \(i\), where \(\alpha_{i,j}\) is the argument the annotation of \(x_{i,j}\) names (none when it has no annotation), then \(\Gamma \vdash_\Sigma c(u_1, \dots, u_n) : t\). An unbound argument has \(m_i = 0\), and the last variable of a binding list is index \(0\) in its scope.
The terms form the family of sets
indexed by contexts and sorts. With the constructors as its operations, \(T_\Sigma\) is the
initial algebra of the signature in
the sense of Fiore, Plotkin, and Turi (Fiore et al., 1999): for every algebra there is exactly one map
from \(T_\Sigma\) to it that respects the operations. Each \(T_\Sigma(\Gamma, s)\) is infinite when a sort
has a recursive constructor, since terms of every depth exist. The tags Data and BoundVar are
reserved for the two kinds of leaf. Each object sort is also an ordinary checked family Σ.s of the
module, whose constructors are the signature's constructors and whose variables are written
Σ.s.var(i), so programs build, match, and pass terms like any other value.
1.2.1 Renaming, substitution, and the generated operations¶
Because every term is in de Bruijn form, alpha-equivalence is equality of terms, and the structural operations are defined once for every signature by recursion on \(T_\Sigma\), as in Autosubst and the Fiore and Szamozvancev formalization (Stark et al., 2019; Fiore and Szamozvancev, 2022). Write \(\uparrow^k_c t\) for the term in which every free index \(i \geq c\) of \(t\) becomes \(i + k\); under a binding list of length \(m\) the cutoff grows by \(m\). Substitution \(t[u/j]\) replaces index \(j\) by \(u\), weakening \(u\) past every binder it passes and lowering the free indices above \(j\) by one; instantiation of a scope \((x_1, \dots, x_m).t\) by \(u_1, \dots, u_m\) substitutes the innermost variable first. These satisfy the usual laws: shifting by \(0\) is the identity, shifts compose additively, and \((\uparrow^1_j t)[u/j] = t\).
The functions of quivers.structural.binding implement them on the host, together with free
variables, alpha-equality, a hash and a total order that agree with it, printing with fresh names, and
a generic fold whose algebra receives each bound argument as a Scoped value. The compiler also
generates them as checked computations of the module, one per object sort \(s\) (§Generated
computations):
Σ.s.shift, Σ.s.subst.v for each variable sort \(v\), Σ.s.instantiate.v, Σ.s.occurs,
Σ.s.eq, Σ.s.ord, Σ.s.hash, and Σ.s.show. Each generated operation agrees with the host
function on every term; the agreement is checked differentially by the test suite.
1.3 Graph signatures¶
A signature may declare kinds of vertices and edges instead of, or beside, constructors:
A vertex kind is the type of a vertex, and an edge kind is a binary relation
\(\varepsilon \subseteq K_{\mathrm{src}} \times K_{\mathrm{tgt}}\), directed for -> and undirected for --.
The values of such a signature are finite graphs whose vertices and edges have these kinds, with data
attached to each vertex. Encoders read them by message passing (§2.4) instead of by recursion.
1.4 Parametric signatures¶
The optional parameter list \(\Pi\) introduces sort parameters \(\pi_1, \dots, \pi_m\) that may occur in the sorts and constructors of the signature. The signature then stands for one signature \(\Sigma(\sigma)\) for each substitution \(\sigma\) of declared sorts of the module for the parameters, with its own terms \(T_{\Sigma(\sigma)}\).
2. Encoders¶
An encoder declaration
encoder C : Σ(σ_args)
dim s = d_s
iterations n
readout |-> body_R
op op_1(args_1) recurrent state |-> body_1
init κ(arg) |-> body_init_κ
message[ε](s,t) |-> body_msg_ε
update[K](v,m) |-> body_upd_K
var_init v_i from A_i as ty |-> body_var_i
denotes a function from the terms (or graphs) of the signature to vectors.
2.1 The target algebra¶
The encoder's vectors live in the family of Euclidean spaces
one for each object and data sort, with \(d_s\) from the clause dim s = d_s, or from the signature's
dim when the encoder gives none, and a compile error when neither does. Index sorts have no vector.
The encoder gives one function for each constructor \(c : A_1, \dots, A_n \to t\) whose arguments have
sorts \(s_1, \dots, s_n\),
given by its rule body. A bound argument contributes the vector of its body, encoded with its variables in scope.
With these functions \(\mathcal A_C\) is an algebra for the signature. A var_init rule
gives, for a variable sort \(v\) and the sort \(A\) of the argument a bound variable's annotation names, a function \(\mathrm{init}_{v, A} : \mathbb{R}^{d_A} \to \mathbb{R}^{d_v}\) that computes the vector of the bound variable from the vector of its annotation. A bound variable without an annotation gets one learnable vector per variable sort.
2.2 Denotation: structural recursion¶
The encoder denotes the unique map that respects the operations,
computed by recursion on terms with the embeddings of the bound variables carried alongside. For a term \(\Gamma \vdash_\Sigma t : s\) and embeddings \(\varepsilon\) for \(\Gamma\), the value \(\llbracket C \rrbracket(t \mid \Gamma, \varepsilon) \in \mathbb{R}^{d_s}\) is
where, for an argument \(i\) binding \((x_{i,1} : v_{i,1}, \dots, x_{i,m_i} : v_{i,m_i})\) with annotations naming the arguments \(\alpha_{i,j}\) of sorts \(A_{i,j}\),
so each bound argument is encoded with the vectors of its own variables in scope, and an unbound argument (\(m_i = 0\)) in \(\Gamma\) itself. A closed term is encoded in the empty context: \(\llbracket C \rrbracket(t) = \llbracket C \rrbracket(t \mid \varnothing, \varnothing)\).
The map \(\mathrm{embed}_s\) from the tokens of a data sort to \(\mathbb{R}^{d_s}\) is part of the encoder. By default it is a learnable table that creates a vector the first time it sees a token, which works for closed and open vocabularies.
This map is a catamorphism, or fold: the unique map out of the initial algebra into the algebra \(\mathcal A_C\) (Meijer et al., 1991). Initiality gives one such map for each choice of the functions \(\widehat c\), \(\mathrm{init}\), and \(\mathrm{embed}\), and the recursion computes it on every finite term. Lambek's lemma states that the operations of an initial algebra form an isomorphism (Lambek, 1968).
2.3 Modes for list constructors¶
A constructor rule may have the mode recurrent state or attention prefix, for a binary constructor
such as Cons whose second argument has the same sort as its result.
-
Recurrent. The rule \(\mathrm{Cons}(h, t)\ \mathrm{recurrent}\ \mathrm{state} \mapsto \mathrm{body}(h, \mathrm{state})\) binds
stateto the vector of the recursive argument, so it is the fold of §2.2:\[ \llbracket C \rrbracket\bigl(\mathrm{Cons}(h_1, \mathrm{Cons}(h_2, \dots, \mathrm{Cons}(h_n, \mathrm{Nil})))\bigr) = \mathrm{body}\bigl(h_1, \mathrm{body}(h_2, \dots \mathrm{body}(h_n, \llbracket C \rrbracket(\mathrm{Nil})) \dots)\bigr). \] -
Attention. The rule \(\mathrm{Cons}(h, t)\ \mathrm{attention}\ \mathrm{prefix} \mapsto \mathrm{body}(h, \mathrm{prefix})\) walks the list from the outermost
Consinward. With \(o_0 = \llbracket C \rrbracket(\mathrm{Nil})\), step \(i\) computes \(o_i = \mathrm{body}\bigl(h_i, [\llbracket C \rrbracket(h_1), \dots, \llbracket C \rrbracket(h_{i-1})], o_{i-1}\bigr)\), and the encoder returns \(o_n\), the output of the innermost step.
The recurrent mode is a fold of the Cons rule into \(\mathbb{R}^{d}\). The attention mode is not: it
processes the heads in the opposite order and carries the list of earlier heads as extra state, so it is
a left-to-right fold over the list of heads and not the catamorphism of §2.2.
2.4 Graph encoders¶
For a graph signature the encoder runs \(T\) rounds of
message passing, \(T\) given by iterations
(Gilmer et al., 2017; Battaglia et al., 2018):
An undirected edge sends messages both ways, a directed edge only in its direction. When the functions are shared across vertices of one kind and the aggregation does not depend on the order of the messages, the vertex states are equivariant under relabeling of the vertices, and a readout that does not depend on order gives the same graph vector for every labeling (Battaglia et al., 2018). A function of the inputs that depends on their order need not have these properties.
3. Decoders¶
A decoder maps a vector to a distribution over terms. At a list position it chooses Nil or Cons,
and choosing Cons requires generating a head and a tail. A depth bound limits how deep a term may grow,
and at the bound only productions without recursive arguments may be chosen.
A decoder D : Σ [depth=d] declaration denotes, for each object sort \(s\) and context \(\Gamma\), a Markov
kernel
a morphism of the Kleisli category of the Giry monad that sends each vector to a probability distribution on the terms of sort \(s\) in \(\Gamma\). It generates a term top down, one production at a time, following the polynomial functor of the signature,
whose summands are the productions at sort \(s\). A decoder is not an F-coalgebra, a map \(A \to F(A)\) on one carrier: it is a kernel from vectors to terms. Every term in the support of \(\llbracket D \rrbracket_{s, \Gamma}(v)\) has depth at most \(d\). The support is a subset of the infinite set \(T_\Sigma(\Gamma, s)\), and it is finite when the vocabularies of the data sorts are finite.
3.1 The four heads¶
A decoder body gives four functions of the vector of the current sort, each a let expression:
| Head | Type | Role |
|---|---|---|
| \(\mathrm{structure}_s(v)\) | \(\mathbb{R}^{d_s} \to \Delta^{\lvert K_s\rvert + [\mathrm{BoundVar}]_s - 1}\) | a distribution over the productions at \(s\): its constructors \(K_s\), and BoundVar when \(\Gamma\) has a variable of sort \(s\) |
| \(\mathrm{primitive}_s(v)\) | \(\mathbb{R}^{d_s} \to \Delta^{\lvert \mathrm{Vocab}_s\rvert - 1}\) | a distribution over the tokens of a data sort, which must have a vocabulary, declared in the signature or registered at run time |
| \(\mathrm{factor}_s(v)\) | \(\mathbb{R}^{d_s} \to \prod_i \mathbb{R}^{d_{s_i}}\) | the vectors of the arguments of the chosen production |
| \(\mathrm{binder\_select}_s(v)\) | \(\mathbb{R}^{d_s} \to \Delta^{\lvert \Gamma_s\rvert - 1}\) | a distribution over the variables in scope of sort \(s\), \(\Gamma_s\) the entries of \(\Gamma\) of that sort |
Here \(\Delta^{n-1}\) is the probability simplex on \(n\)
outcomes. The required clause body |-> recursive selects this top-down generation, and recursive is
the only body keyword.
3.2 Denotation: generation top down¶
For a vector \(v \in \mathbb{R}^{d_s}\), a context \(\Gamma\), and a remaining depth \(d\), the kernel \(\llbracket D \rrbracket(v, \Gamma, d)\) generates a term of sort \(s\) as follows. The procedure is the same as ancestral sampling in a program, where a sampled constructor decides which subterms come next (Programs as kernels §2.1).
- If \(s \in S_{\mathrm{dat}}\), draw a token \(d^\star \sim \mathrm{primitive}(v)\) and return \(\mathrm{Data}_s(d^\star)\).
- Otherwise draw a production \(k \sim \mathrm{structure}(v)\).
- If \(k = \mathrm{BoundVar}\), draw \(i \sim \mathrm{binder\_select}(v)\) among the variables of sort \(s\) in \(\Gamma\) and return \(\mathrm{BoundVar}(i)\).
- If \(k\) is a constructor \(c : A_1, \dots, A_n \to s\), compute \((v_1, \dots, v_n) = \mathrm{factor}(v)\), draw the arguments in order, \(u_i \sim \llbracket D \rrbracket(v_i, \Gamma_i, d - 1)\), where \(\Gamma_i\) is \(\Gamma\) extended by the variables argument \(i\) binds and their annotations (§2.2), which name earlier arguments, and return \(c(u_1, \dots, u_n)\).
- At \(d = 0\), restrict \(\mathrm{structure}(v)\) to the productions whose arguments all have data or
index sorts, and to
BoundVarwhen \(\Gamma_s\) is not empty. If no such production exists at the sort, the runtime raises an error.
The log probability of a given term under the decoder,
is computed by the same recursion, with each draw replaced by the log probability of the branch the term takes. It is a function to the reals, not a kernel.
3.3 Reconstruction¶
For an encoder and a decoder over one signature, the composite of \(\llbracket C \rrbracket\) and \(\llbracket D \rrbracket\) is the kernel from terms to distributions over terms that sends \(t\) to \(\llbracket D \rrbracket(\llbracket C \rrbracket(t))\). The reconstruction loss (§4.2) trains both so that this distribution puts high probability on \(t\). Exact reconstruction, \(\llbracket D \rrbracket(\llbracket C \rrbracket(t)) = \delta_t\) for every \(t\), is impossible when two different terms have the same vector, since the decoder then receives the same input for both.
4. Losses¶
A loss attaches a scalar objective to a computation: a reconstruction loss asks the decoder to give high
probability to the encoded input, and a supervised loss asks an attached computation to predict a label.
A loss declaration has an option block and one indented let expression:
The options say where the loss is evaluated and how it is weighted, and the body is the scalar.
4.1 Attachment¶
The option on attaches the loss to one kind of computation, and without it the loss is global:
| Attachment | Evaluated | Value passed to body |
|---|---|---|
global |
once per training step | the module's environment \(E\) |
program P |
at each run of \(P\) | the execution trace of the run, its draws and scores (Wingate et al., 2011) |
deduction Δ |
at each evaluation of \(\Delta\) | the chart \(\alpha_\Delta : I \to K\) |
encoder C |
at each call of \(C\) | the pair \((t, \llbracket C \rrbracket(t))\) |
decoder D |
at each call of \(D\) | the pair \((v, t)\) with \(t\) drawn from \(\llbracket D \rrbracket(v)\) |
rule R in Δ |
at each firing of \(R\) while \(\Delta\) builds its chart | the premises and the conclusion of the firing |
chart of Δ |
once on the finished chart of \(\Delta\) | the chart \(\alpha_\Delta\) |
4.2 Denotation¶
For a loss \(L\) with weight \(w\) (a let expression in the attached value), attachment \(\kappa\), target \(T\),
and body \(\mathrm{body}_L\), the denotation is the function
on the values \(\mathrm{Val}_{\kappa, T}\) passed at that attachment. The total loss of a training step is the sum over every evaluation of every loss in the step:
Typical bodies are -D(C(input)).log_prob(input) (reconstruction), cross_entropy(p, q) (agreement of
two distributions), -chart.goal_weight() (likelihood under a parser), and
bce_with_logits(pred, target) (supervised prediction).
4.3 Losses and inference¶
The inference driver adds the total loss to its objective and passes it to the optimizer. The losses change the parameters that are fitted, not the denotation of a program at fixed parameters, which is the kernel of Programs as kernels. The role of conditioning in the inference layer is in Programs as kernels §6.
Cited sources¶
Jordan B. Pollack. Recursive Distributed Representations. Artificial Intelligence, 46(1–2):77–105, 1990. doi:10.1016/0004-3702(90)90005-K.
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.
Marcelo Fiore, Gordon Plotkin, and Daniele Turi. Abstract Syntax and Variable Binding. In Proceedings of the 14th Symposium on Logic in Computer Science (LICS), 193–202. IEEE Computer Society, 1999. doi:10.1109/LICS.1999.782615.
Marcelo Fiore and Chung-Kil Hur. Second-Order Equational Logic (Extended Abstract). In Computer Science Logic (CSL 2010), volume 6247 of Lecture Notes in Computer Science, 320–335. Springer, 2010. doi:10.1007/978-3-642-15205-4_26.
John Cartmell. Generalised Algebraic Theories and Contextual Categories. Annals of Pure and Applied Logic, 32:209–243, 1986. doi:10.1016/0168-0072(86)90053-9.
N. G. de Bruijn. Lambda Calculus Notation with Nameless Dummies, a Tool for Automatic Formula Manipulation, with Application to the Church-Rosser Theorem. Indagationes Mathematicae (Proceedings), 75(5):381–392, 1972. doi:10.1016/1385-7258(72)90034-0.
Kathrin Stark, Steven Schäfer, and Jonas Kaiser. Autosubst 2: Reasoning with Multi-Sorted de Bruijn Terms and Vector Substitutions. In Proceedings of the 8th ACM SIGPLAN International Conference on Certified Programs and Proofs, 166–180. ACM, 2019. doi:10.1145/3293880.3294101.
Marcelo Fiore and Dmitrij Szamozvancev. Formal Metatheory of Second-Order Abstract Syntax. Proceedings of the ACM on Programming Languages, 6(POPL):1–29, 2022. doi:10.1145/3498715.
Erik Meijer, Maarten Fokkinga, and Ross Paterson. Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire. In Functional Programming Languages and Computer Architecture (FPCA), Lecture Notes in Computer Science, 124–144. Springer, 1991. doi:10.1007/3540543961_7.
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.
Justin Gilmer, Samuel S. Schoenholz, Patrick F. Riley, Oriol Vinyals, and George E. Dahl. Neural Message Passing for Quantum Chemistry. 2017. Published at ICML 2017. arXiv:1704.01212, doi:10.48550/arXiv.1704.01212.
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.
David Wingate, Andreas Stuhlmueller, and Noah Goodman. Lightweight Implementations of Probabilistic Programming Languages Via Transformational Compilation. In Proceedings of the Fourteenth International Conference on Artificial Intelligence and Statistics, volume 15 of Proceedings of Machine Learning Research, 770–778. PMLR, 2011. URL: https://proceedings.mlr.press/v15/wingate11a.html.