Tree and Graph Autoencoders: Signatures and Encoders¶
An encoder turns a structured value, such as a syntax tree, into a fixed-length
vector, and a decoder
assigns probabilities to structures given such a vector. Together they form an
autoencoder over terms, the design of
recursive autoencoders (Pollack, 1990), tree-LSTM encoders
(Tai et al., 2015), and message-passing graph encoders
(Gilmer et al., 2017; Battaglia et al., 2018). quivers.structural and the QVR
declarations syntax, encoder, decoder, and loss implement them.
Decoders and losses covers the last
two.
A signature \(\Sigma\) lists sorts and the constructors that build terms of each sort, and \(T_\Sigma\) is the set of terms it generates. An encoder gives each constructor \(\mathrm{op} : s_1 \times \dots \times s_n \to s\) a learnable function \(\widehat C_{\mathrm{op}}\) on vectors and computes the code of a term bottom-up:
To encode App(Const("dog"), Const("cat")), for instance, it encodes the two
constants and applies the learned App function to their vectors. One function is
reused at every occurrence of a constructor, in trees of any size. In algebraic terms
the functions \(\widehat C_{\mathrm{op}}\) make the vector space \(\mathrm{Vec}_D\) an
algebra for the signature,
and \(C\) is the unique map from the term algebra \(T_\Sigma\) that respects every
constructor, the catamorphism or fold
(Meijer et al., 1991). Different terms can receive the same vector, and the decoder
models which terms are likely given a vector.
Signature blocks¶
A syntax declaration gives a signature: the sorts, the constructors with the
variables each argument binds, and, for graphs, the vertex and edge kinds. In the example, Const builds a Term from a Name, and
App builds a Term from two Terms. Term and Type admit different
constructors even though both are vectors in the end, and the dim options give the
vector length of each sort.
syntax LF
sorts
Term : object [dim=64]
Type : object [dim=32]
Name : data [dim=32, vocab=["dog", "cat", "every", "some"]]
constructors
Const : Name -> Term
App : Term, Term -> Term
constructors
Lam : (ty : Type), (x : Term : ty).Term -> Term
All : (ty : Type), (x : Term : ty).Term -> Term
A sort is one of three kinds:
object: a sort whose terms are encoded and decoded recursively;data: leaves that carry a string, integer, float, byte string, or Boolean, each embedded by an embedder for its sort. A data sort may list a closed vocabulary with the optionvocab=[...], and the decoder then samples and scores leaves of that sort from exactly those values;index: positions for de Bruijn indices (de Bruijn, 1972).
A constructor with no arguments is written with an empty domain, Leaf : -> Tree.
The names BoundVar and Data are reserved for the library's own constructors and
cannot be declared.
Binding arities, de Bruijn context, and type annotations¶
An argument written (x : Term).Term binds a variable x of sort Term inside that
argument only, so each argument has its own binding arity and one constructor may
mix bound and unbound arguments, as in Let : Term, (x : Term).Term -> Term. A
de Bruijn index names a bound
variable by its distance from the innermost binder, so index 0 is the most recently
bound variable, and renaming a bound variable does not change the representation. The
constructor Lam : (ty : Type), (x : Term : ty).Term -> Term builds a Term from a
labeled argument ty of sort Type and a body in which x, of sort Term, is bound
and annotated by ty. Signatures of this kind are second-order binding signatures
(Fiore et al., 1999); the
language reference lists
the argument forms.
The encoder and the decoder both carry a context \(\Gamma\) of bound variables. Each
entry is a triple (var_sort, embedding, type_term) of the variable's sort, its
vector, and its annotation, and BoundVar(i) in a position of object sort reads the
entry at depth i. The encoder's var_init rule, below, computes a variable's vector
from its annotation.
Every sort that a constructor mentions must be declared under sorts, and
every sort without a dim option must receive one from each encoder and decoder over
the signature. The compiler raises an error otherwise.
Checked interpretations of a binding signature¶
An interpret declaration can fold a syntax with binding through named QVR
computations. The [structure=cartesian] option explicitly grants exchange,
weakening, and contraction. A scoped rule operation receives a pair of the body
proof and captured environment. Its generated application takes one value for
each bound variable in the order the argument binds them. The rule operation
can omit the application or call it several times with different values.
syntax Scope
sorts
Expr : object
constructors
Bind : (x : Expr).Expr -> Expr
interpret evaluate [structure=cartesian] : Scope -> Real
rule Bind = choose
define choose[Env : Type](body : Scope.ScopedProof_Expr[Real, Scope.ScopedFrame_Expr[Env, Real]] * Env) : Real !{} =
let first <- evaluate.apply_Bind_0[Env](body, 2.0)
let second <- evaluate.apply_Bind_0[Env](body, 5.0)
return first + second
define binding_example() : Real !{} =
let x = (Scope.ScopedHere_Expr[Real, Scope.ScopedEmpty]() : Scope.ScopedMember_Expr[Real, Scope.ScopedFrame_Expr[Scope.ScopedEmpty, Real]])
let body = (Scope.ScopedHypothesis_Expr[Real, Scope.ScopedFrame_Expr[Scope.ScopedEmpty, Real]](x) : Scope.ScopedProof_Expr[Real, Scope.ScopedFrame_Expr[Scope.ScopedEmpty, Real]])
let proof = (Scope.ScopedRule_Bind[Real, Scope.ScopedEmpty](body) : Scope.ScopedProof_Expr[Real, Scope.ScopedEmpty])
evaluate(proof)
Here the proof body refers to the most recent hypothesis. The two
applications interpret it at 2 and at 5, so binding_example() returns 7.
A frame type records the previous environment and the carrier of its
newest hypothesis. The proof's bracketed arguments record the semantic
carrier and the precise environment type. With several object sorts, the
authored interpretation uses the declared carrier for each sort. Rule operations
are pure by default. With one object sort, an interpretation can declare a closed
row by naming lexical effect instances, as in
interpret evaluate [structure=cartesian, effects=[score]] : Scope -> Real.
A caller handles the row in the usual QVR scope. Each application runs its
body’s effects once, and an application that the rule skips emits no requests.
Eager premises run in the order written, including those of ordinary rules
such as a binary constructor. If a binding rule applies its body twice and each
application flips a fair coin, the results agree with probability \(1/2\).
If it applies its body once and uses that result twice, they agree
with probability \(1\). Reusing the captured proof and environment leaves
the choice between these two computations to the authored operation.
The checked Python adapter
also accepts distinct carriers and closed effect rows by judgment.
Encoder blocks¶
An encoder gives the vector length of each sort and a body for each constructor. A body is a let-expression over the children's vectors, and an omitted body
defaults to a learned two-layer MLP with the right input and output lengths:
Here App sums its children's vectors and applies GELU, and Const, Lam, and All
take the default MLPs. For a constructor with bound arguments the library proceeds
argument by argument, in declaration order:
- an argument that binds nothing is encoded in the outer context \(\Gamma\);
- for an argument that binds variables, each variable annotated by an earlier labeled
argument gets its vector from the matching
var_init <var_sort> from <annot_sort> as <name> |-> bodyrule applied to that argument's vector, and(var_sort, embedding, annot_term)is pushed onto a copy of \(\Gamma\); the argument is then encoded in the extended context; - the constructor's body receives the vectors of all its arguments, in declaration order.
An encoder may give one var_init rule for each (var_sort, annot_sort) pair its
signature's annotated variables use. A pair without a rule gets a learned two-layer MLP, and an
unannotated variable gets a learned constant vector for its sort.
Primitives and user-defined callables in rule bodies¶
Rule bodies use the same primitives as let-expressions elsewhere in QVR, listed in the
primitive reference: the
activations of torch.nn.functional, the simplex maps, pointwise functions,
reductions over the last axis, layer_norm, and dropout. They can also call any
morphism, program, encoder, decoder, or deduction declared at the top level
of the module, as f(arg, ...).
A name in a body resolves first to a primitive, then to a top-level declaration, then
to a constructor. A constructor with a primitive's name, such as relu, is accepted,
but a call relu(x) in a body reaches the primitive.
The compiler checks the number of arguments at each call:
- a
MonadicProgramwith namedparamstakeslen(params)arguments; - a
MonadicProgramwithoutparamstakes one, its packed input; - a
Morphismtakes one, the domain tensor; - any other callable takes its positional parameters without defaults, and a
*argsparameter disables the check.
An error raised inside a called function is re-raised with the file, line, and column of the encoder call that reached it.
object Hidden : Real 64
program embed(x : Real[Fin 64]) : Hidden -> Hidden
let h = relu(layer_norm(x))
return h
encoder C_embed : LF
dim Term = 64
dim Type = 32
op App(f, x) |-> gelu(embed(f) + embed(x))
The program embed has one named parameter, so each call passes it one vector.
Factory form¶
An encoder can instead name a factory from quivers.structural.shapes (the
encoder API). The bracketed options other than
factory are passed to it and checked against its parameters. One declaration uses
either a body or a factory, and a module may mix both kinds of declaration.
syntax Seq0
sorts
A : data [dim=16, vocab=["a", "b"]]
Seq : object [dim=16]
constructors
Nil : -> Seq
Cons : A, Seq -> Seq
encoder rnn_enc : Seq0 [factory=rnn_encoder, dim=16]
encoder tfm_enc : Seq0 [factory=transformer_encoder, dim=16]
encoder bow_enc : Seq0 [factory=bow_encoder]
| Factory | Signature | What it computes |
|---|---|---|
rnn_encoder(sig, dim) |
sequence | a right fold over the list with a GRU cell (Cho et al., 2014) |
transformer_encoder(sig, dim, heads, layers) |
sequence | a transformer encoder (Vaswani et al., 2017): the element embeddings plus sinusoidal position encodings pass through layers layers of multi-head self-attention and a position-wise feed-forward network, with residual connections and layer normalization, and the sequence vector is the mean over positions |
bow_encoder(sig, dim) |
sequence | the sum of the element embeddings, which ignores order |
tree_lstm_encoder(sig, dim) |
tree | a child-sum tree-LSTM over binary trees (Tai et al., 2015) |
gnn_encoder(sig, iterations, dim, readout) |
graph | message passing with one MLP per edge kind, one GRU update per vertex kind, and a mean, sum, or max readout |
transformer_encoder uses the attention form of the next section: the step at the
innermost Cons receives every element's embedding and attends over all of them, and the
empty sequence embeds as a learned vector. heads must divide dim. Every factory returns an
Encoder, the same runtime value an explicit body produces.
Shorthand for sequences¶
For sequence signatures, \(\mathrm{Seq} = \mathrm{Nil} \mid \mathrm{Cons}(A, \mathrm{Seq})\),
a Cons rule can take one of two extra forms:
object State : Real 16
morphism gru_step : State * State -> State [role=function, param_source=mlp(16), output=tanh]
morphism tfm_step : State * State -> State [role=function, param_source=mlp(16), output=tanh]
encoder RNN : Seq0
dim Seq = 16
op Nil |-> 0.0
op Cons(head, tail) recurrent state |-> gru_step(head, state)
encoder Tfm : Seq0
dim Seq = 16
op Nil |-> 0.0
op Cons(head, tail) attention prefix |-> tfm_step(head, prefix)
recurrent <state>binds the named variable to the tail's vector, so the body is the step function of an ordinary right fold.attention <prefix>walks the list from the outside in. At step \(i\) the body receivesprefix = [head_0, ..., head_{i-1}], the vectors of the heads already passed, and the encoder returns the output of the innermost step. Any attention over the prefix is computed by the body, and the form itself computes no attention weights.
gru_step and tfm_step are learned functions of the
module, each an MLP from a pair of vectors to a vector.
Shorthand for graphs¶
Graphs can contain cycles, so there is no bottom-up order. Message passing instead
updates every vertex's vector for a fixed number of rounds: each edge sends a message
from its source to its target, each vertex combines its incoming messages with its
current vector, and a readout pools the final vectors (Gilmer et al., 2017). A graph
signature declares vertex_kinds and edge_kinds, and the encoder gives the
initialization, message, update, and readout functions:
syntax Mol
vertex_kinds
Atom : data [dim=32]
Bond : data [dim=32]
edge_kinds
bonded : Atom -- Atom
in_bond : Atom -> Bond
object Vertex : Real 32
object Message : Real 64
morphism atom_embed : Vertex -> Vertex [role=function, param_source=mlp(32)]
morphism bond_embed : Vertex -> Vertex [role=function, param_source=mlp(32)]
morphism mlp_msg : Message -> Vertex [role=function, param_source=mlp(32)]
morphism mlp_in : Message -> Vertex [role=function, param_source=mlp(32)]
morphism gru_update_atom : Vertex * Vertex -> Vertex [role=function, param_source=mlp(32), output=tanh]
morphism gru_update_bond : Vertex * Vertex -> Vertex [role=function, param_source=mlp(32), output=tanh]
encoder GNN : Mol
iterations 4
init Atom(a) |-> atom_embed(a)
init Bond(b) |-> bond_embed(b)
message[bonded](src, tgt) |-> mlp_msg([src, tgt])
message[in_bond](src, tgt) |-> mlp_in([src, tgt])
update[Atom](self, msgs) |-> gru_update_atom(self, mean(msgs))
update[Bond](self, msgs) |-> gru_update_bond(self, mean(msgs))
readout |-> mean_pool
An undirected edge kind (Atom -- Atom) sends messages both ways, and a directed one
(Atom -> Bond) only in its declared direction. The embeddings, message functions, and
updates named in the bodies are learned functions of the module, and a message function reads
the source and target vectors joined into one.
Stdlib shapes¶
quivers.structural.shapes provides signatures to go with the factories above:
seq_signature(name, dim): \(\mathrm{Seq} = \mathrm{Nil} \mid \mathrm{Cons}(A, \mathrm{Seq})\);tree_signature(name, dim): \(\mathrm{Tree} = \mathrm{Leaf}(L) \mid \mathrm{Node}(B, \mathrm{Tree}, \mathrm{Tree})\);graph_signature(name, vertex_kinds, edge_kinds): a graph signature with the given vertex and edge kinds.
They run on the same Encoder and
Decoder classes as declared encoders and decoders.
See also¶
- Decoders and losses: the decoder, a Markov kernel from vectors to terms, and the loss declarations.
- Weighted Deduction Systems: the chart parser, to which an encoder
can attach to expose
chart.embedding(item)as a differentiable value. - Tree autoencoders tutorial: running entries, gradients, and checkpoints.
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.
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.
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.
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.
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.
Kyunghyun Cho, Bart van Merriënboer, Caglar Gulcehre, Dzmitry Bahdanau, Fethi Bougares, Holger Schwenk, and Yoshua Bengio. Learning Phrase Representations using RNN Encoder–Decoder for Statistical Machine Translation. In Proceedings of the 2014 Conference on Empirical Methods in Natural Language Processing (EMNLP), 1724–1734. Association for Computational Linguistics, 2014. URL: https://aclanthology.org/D14-1179/, doi:10.3115/v1/D14-1179.
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, and Illia Polosukhin. Attention is All you Need. In Advances in Neural Information Processing Systems, volume 30. 2017. URL: https://papers.nips.cc/paper/2017/hash/3f5ee243547dee91fbd053c1c4a845aa-Abstract.html.