12. Tree autoencoders¶
A tree autoencoder encodes a tree into a vector by combining the vectors of each node's children from the leaves up, and decodes a vector into a distribution over trees (Pollack, 1990; Tai et al., 2015). The encoder is a fold over the tree, a catamorphism (Meijer et al., 1991). The package quivers.structural implements them: the trees are terms of a typed signature with binders, and the loss is the negative log probability that the decoder assigns to the original term. Run that loss as a computation of the Quivers Indexed Effect Core (QIEC), the typed core language of QVR, on the reference machine, the library's interpreter for QIEC (chapter 9), and differentiate through it.
The gallery program term_autoencoder.qvr declares a signature for simply typed lambda terms, an encoder Enc, a decoder Dec, and a loss reconstruct. Its elaboration to QIEC records which encoder and decoder each step calls and the types they accept, as Compute requests. The encoder and decoder themselves are PyTorch modules, which Program.run binds to those requests as attachments: values held only in the running Python process and never serialized with the module. The returned loss keeps its autograd history (PyTorch Contributors, 2021), so .backward() reaches the parameters of both modules.
1. Compile and inspect the entry points¶
import torch
from quivers.dsl import load
from quivers.structural import bound_var, make_term
torch.manual_seed(0)
structural = load("docs/examples/source/term_autoencoder.qvr")
names = [entry.name for entry in structural.entry_points()]
generated = [name for name in names if name.startswith("STLC.")]
assert "STLC.Term.subst.Term" in generated and "STLC.Term.show" in generated
assert names[len(generated):] == ["Enc", "Dec", "Dec.nll", "reconstruct"]
print(names[len(generated):])
The entry points are listed in declaration order, under their qualified names. The signature STLC comes first: its declaration generates operations on its terms, such as capture-avoiding substitution (STLC.Term.subst.Term) and printing (STLC.Term.show), and each is an entry point of its own (Generated term operations). Enc, Dec, and Dec.nll (the decoder's negative log likelihood) are entry points answered by attachments. reconstruct is the loss, which calls Enc and then Dec.nll.
2. Construct a typed term¶
Build the term \(\lambda x : \mathit{base}.\ \mathit{plus}\ x\) with the Python constructors of quivers.structural:
term = make_term(
"Lam",
make_term("Base", "base"),
make_term("App", make_term("Const", "plus"), bound_var(0)),
)
bound_var(0) is a de Bruijn index: it refers to the nearest enclosing binder. While folding the term, the encoder checks each constructor, the number of its arguments, the scope of each bound variable, and the vocabulary of each data leaf.
3. Run the loss¶
run = structural.run("reconstruct", term)
assert torch.is_tensor(run.value)
assert run.value.shape == ()
assert run.result.runtime == "core+structural"
classic_loss = structural.losses.evaluate({"term": term})
torch.testing.assert_close(run.value, classic_loss)
print(float(run.value.detach()))
The reference machine and the loss registry (structural.losses) of the compiled runtime, the PyTorch implementation of the module, give the same scalar. The runtime label names both providers: core runs the QIEC computation, and structural answers the encoder and decoder requests.
4. Differentiate through the run¶
for parameter in structural.parameters():
parameter.grad = None
run.value.backward()
assert any(parameter.grad is not None for parameter in structural.parameters())
print(len(structural.state_dict()), "checkpoint tensors")
The handler for the attachments returns PyTorch tensors unchanged, so the autograd graph to both modules survives the run on the reference machine. The encoder and decoder are registered under fixed names, so an optimizer over structural.parameters() and a checkpoint from structural.state_dict() include them.
5. Serialization and transpile targets¶
Serializing structural.qiec writes the descriptors of the attachments, their identifiers, and their checked types, but not the PyTorch modules. Another process may load the serialized module, but it must compile or attach compatible encoder and decoder providers before running reconstruct.
No probabilistic programming target supports these attachments. Checking against one reports qiec:capability:neural-attachment:<entry>:
The term autoencoder example develops the encoder and decoder rules. The reference on generated computations specifies how attachments are bound.
Next¶
Chapter 13 checks a module against its targets, inspects its entry points, and verifies the editor tooling before a release.
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.
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.
PyTorch Contributors. Automatic differentiation with torch.autograd. PyTorch Tutorials, 2021. Created February 10, 2021; updated January 16, 2024. URL: https://docs.pytorch.org/tutorials/beginner/basics/autogradqs_tutorial.html (visited on 2026-11-06).