Tactics that compress#
In the previous part the script of the proof of lemma mann_44 had three tactics, and the proof checked by the kernel
had 48 nodes. A tactic is a program that writes a proof for us. A good tactic turns a long, repetitive fragment of a
proof into one word in the script — and this is the compression this chapter is about. The kernel still receives the
whole proof, so the tactic need not be trusted: if it makes a mistake, the kernel rejects the result.
For the Robbins proof we build four tactics, from the simplest to the cleverest:
Tactic |
What it does |
Kind |
|---|---|---|
|
closes a goal whose sides differ only by the order and brackets of sums |
decision procedure: always terminates, never guesses |
|
rewrites with an equation whose left side sits in the goal “mixed up” |
matching modulo A1, A2 |
|
rewrites with the given equations as long as possible, then |
simplification to the end |
|
finds the creative expansions with the Robbins equation by itself |
bounded search |
The tactic ac: a normal form with a proof#
Two terms are equal by commutativity A1 and associativity A2 exactly when they have the same summands, counted with multiplicity — inside every sum, also deep under \(n(\ldots)\). This is easy to check: in every sum we sort the summands in a fixed order and group them to the left. The result is the normal form:
from syntax import term, show
from ac import normal
for text in ["(b + a) + (c + a)", "a + (a + (c + b))", "n(b + a) + n(a + n(b + a))"]:
print(f"{text:28} -> {show(normal(term(text)))}")
(b + a) + (c + a) -> a + a + b + c
a + (a + (c + b)) -> a + a + b + c
n(b + a) + n(a + n(b + a)) -> n(a + b) + n(a + n(a + b))
Sorting alone is not a proof, though. The tactic ac sorts so that every move can be written down with kernel rules:
it merges two sorted sums into one, and then puts every summand in its place by swapping neighbours (insertion sort).
One swap of neighbours is three steps: A2, then A1 inside, then A2 backwards.
import inspect
import ac
print(inspect.getsource(ac._insert))
def _insert(steps, path, comm, assoc):
"""P + x with P a sorted chain: move x left to its place (insertion
sort; one swap of neighbours = A2, then A1, then A2 backwards)."""
P, x = at(steps.now, path)[1:]
if not is_sum(P):
if order_key(x) < order_key(P):
steps.fact(path, comm, (P, x)) # P + x = x + P
return
P1, y = P[1], P[2]
if order_key(x) >= order_key(y):
return
steps.fact(path, assoc, (P1, y, x)) # (P1 + y) + x
steps.fact(path + (2,), comm, (y, x)) # = P1 + (y + x)
steps.fact(path, assoc, (P1, x, y), backward=True) # = (P1 + x) + y
_insert(steps, path + (1,), comm, assoc)
Every steps.fact(...) adds to the proof an instance of an axiom put into the whole term by CongrArg. Let us look
at the successive terms in a short example:
from robbins import theory
from ac import Steps, ac_proof
K = theory() # a kernel with the axioms A1, A2, R
steps = Steps(K, term("c + (b + a)"))
ac._sort(steps, (), "A1", "A2")
print(show(steps.start))
for bit in steps.pieces:
print(" =", show(K.conclusion(bit)[1]))
print("rewrites:", steps.count)
c + (b + a)
= c + (a + b)
= c + a + b
= a + c + b
= a + (c + b)
= a + (b + c)
= a + b + c
rewrites: 6
Every line is the whole term after one rewrite: CongrArg puts the change of a subterm into the whole. The kernel
gets one proof out of it — the rewrites joined by Trans. How much does such bookkeeping cost? Let us count the nodes
of the proof for a sum of \(k\) different summands written in reverse order — the worst case of insertion sort:
from robbins import nodes
letters = "abcdefghijkl"
cost = {}
for k in range(2, 11):
backwards = " + ".join(reversed(letters[:k]))
in_order = " + ".join(letters[:k])
proof = ac_proof(K, term(backwards), term(in_order))
assert K.conclusion(proof) == (term(backwards), term(in_order))
cost[k] = nodes(proof)
print(f"k = {k:2}: {cost[k]:4} nodes, per pair of summands {cost[k] / (k * (k - 1) / 2):.1f}")
k = 2: 1 nodes, per pair of summands 1.0
k = 3: 13 nodes, per pair of summands 4.3
k = 4: 36 nodes, per pair of summands 6.0
k = 5: 69 nodes, per pair of summands 6.9
k = 6: 112 nodes, per pair of summands 7.5
k = 7: 165 nodes, per pair of summands 7.9
k = 8: 228 nodes, per pair of summands 8.1
k = 9: 301 nodes, per pair of summands 8.4
k = 10: 384 nodes, per pair of summands 8.5
The cost grows like \(k^2\): each of the \(k(k-1)/2\) pairs of summands has to be swapped, every swap is three rewrites,
and every rewrite is three nodes in the proof (Inst, CongrArg, Trans) — hence the number of nodes per pair,
which approaches 9. The script, on the other hand, always has one word: ac. The longer the sums, the bigger the
compression.
Is ac correct? We do not have to prove it. If the tactic has a bug, the kernel rejects its proof. If the normal forms
of the two sides differ, the tactic fails — rightly so, because then the equation does not follow from A1 and A2. Let
us also test the tactic on random pairs of terms that are equal up to order and brackets:
import random
def random_term(rng, depth):
if depth == 0 or rng.random() < 0.3:
return rng.choice("abcd")
if rng.random() < 0.25:
return ("n", random_term(rng, depth - 1))
return ("+", random_term(rng, depth - 1), random_term(rng, depth - 1))
def shuffled(rng, t):
"""The same term up to A1, A2: summands shuffled, brackets at random."""
if isinstance(t, str):
return t
if t[0] == "n":
return ("n", shuffled(rng, t[1]))
parts = [shuffled(rng, s) for s in ac.addends(t)]
rng.shuffle(parts)
while len(parts) > 1:
i = rng.randrange(len(parts) - 1)
parts[i:i + 2] = [("+", parts[i], parts[i + 1])]
return parts[0]
rng = random.Random(2026)
pairs = [(t, shuffled(rng, t)) for t in (random_term(rng, 6) for _ in range(500))]
accepted = sum(K.conclusion(ac_proof(K, s, t)) == (s, t) for s, t in pairs)
print(f"the kernel accepted {accepted} proofs out of {len(pairs)}")
the kernel accepted 500 proofs out of 500
Matching modulo associativity and commutativity#
An ordinary rw looks for a pattern literally. In the Robbins proof that is not enough: the left side of a lemma often
sits in the goal in a different order or as a part of a longer sum. In mathlib this shows in lines such as
rw [add_comm _ q, mann_47] — the summands have to be reordered by hand first, so that rw works at all.
The tactic rw_ac matches a pattern modulo A1 and A2. A variable of the pattern may then take several summands of
a sum. For example, the left side of the Robbins equation matches this term in one way, with \(x = a + b\):
from ac import ac_match
pattern = term("n(n(x + y) + n(x + n(y)))")
t = normal(term("n(n(c + a + b) + n(b + a + n(c)))"))
for s in ac_match(pattern, t, {"x", "y"}, {}):
print({x: show(v) for x, v in s.items()})
{'x': 'a + b', 'y': 'c'}
When the pattern fits a part of a sum, rw_ac first regroups the summands — the proof of the regrouping is written by
ac — so that the matching fragment stands alone, and then rewrites it with an ordinary step. In the example the
constants \(a, b, c, d\) satisfy the hypothesis \(a + b = c\), and in the goal \(a\) and \(b\) are separated by the
summand \(d\):
from robbins import Goal, Section
K = theory()
S = Section(K, "abcd", ["a + b = c"]) # constants a, b, c, d and hypothesis h1: a + b = c
g = Goal(S.kernel, "n(b + (d + a)) = n(d + c)")
g.rw_ac("h1")
print(g)
g.ac()
print("nodes:", nodes(g.qed()))
n(d + c) = n(d + c)
nodes: 37
An ordinary rw [h1] would find nothing here: the tree of the term has no subtree \(a + b\). In the proof of lemma
mann_48 the tactic rw_ac replaces in this way the manual add_comm _ q of mathlib.
ac_simp: rewrite as long as you can#
Mann’s lemmas with hypotheses (part 3) need several rewrites in different places on both sides. Instead of pointing
to each, we give a list of equations, and ac_simp rewrites with them — each from left to right, modulo A1 and A2 —
as long as one of them fits, and finally closes the goal with the tactic ac. A simple example: if \(e + e = e\) (an
idempotent element), every sum made of copies of \(e\) and one \(x\) simplifies to \(e + x\).
S = Section(K, "e", ["e + e = e"]) # constant e and hypothesis h1: e + e = e
S.lemma("absorption", "e + (x + (e + e)) + e = x + e", lambda g: g.ac_simp("h1"))
print(show(S.kernel.facts["absorption"][1]), "=", show(S.kernel.facts["absorption"][2]),
"| uses of h1 in the proof:", str(S.kernel.proofs["absorption"]).count("'h1'"))
e + (x + (e + e)) + e = x + e | uses of h1 in the proof: 3
The tactic replaced \(e + e\) by \(e\) three times, although the script never points to a place. Such simplification always ends
when every rule shortens the term (here: two copies of \(e\) become one). When the rules do not shorten, ac_simp could
go round in circles — that is why it has a limit on rewrites and fails with a message when it is exceeded, instead of
running forever.
auto: the creative step from a search#
The hardest part of the Robbins proof are the expansions: replace \(x\) by \(n(n(x + y) + n(x + n(y)))\) — but which \(x\)
and which \(y\)? In mathlib these choices are written out by hand, for example
nth_rw 2 [← robbins (-(a + b)) (-a + b)]. The tactic auto looks for them itself:
it brings both sides of the goal to the normal form;
for each side it lists all terms that can be reached with one rewrite from the list of rules (the expansion
← Rwith the variable \(y\) taken from the subterms of the goal and from short sums of its summands, the contractionR, lemmas in both directions) — each again in normal form;it looks for a common element of the two sets: then the goal has the proof “one step from the left, one from the right, and
acin the middle”.
This is a search from both sides at once (meet in the middle). Let us see what auto found for mann_44:
from kernel import Inst, Symm, Trans, CongrArg
from robbins_proof import STATEMENTS
def instances(proof, name):
"""Arguments of all uses of the fact `name` in a proof tree."""
stack, result = [proof], []
while stack:
d = stack.pop()
if isinstance(d, Inst) and d.name == name:
result.append(tuple(show(a) for a in d.args))
elif isinstance(d, (Symm, CongrArg)):
stack.append(d.p)
elif isinstance(d, Trans):
stack += [d.p, d.q]
return sorted(set(result))
from robbins import lemma
K = theory()
proof, _ = lemma(K, "mann_44", STATEMENTS["mann_44"], lambda g: g.auto())
print("auto used R for (x, y):", instances(proof, "R"))
auto used R for (x, y): [('b', 'a'), ('n(a + b)', 'b + n(a)')]
Exactly the two expansions that mathlib writes out by hand: \(x = b\), \(y = a\), and \(x = n(a + b)\) with \(y = b + n(a)\)
— that is \(n(a) + b\) with the summands in the order of the normal form. The function winker_by_auto proves lemmas
44–49 like this — the script only says which rules may be used:
from robbins_proof import winker_by_auto, winker_by_hand
print(inspect.getsource(winker_by_auto))
def winker_by_auto(K):
"""Stage 1 with the tactic auto: only the rules are named."""
rules = {"mann_44": (), "mann_45": (),
"mann_46": ("← R", "← mann_45"),
"mann_47": ("← R", "← mann_46"),
"mann_48": ("← R", "← mann_47", "mann_47"),
"mann_49": ("← R", "← mann_48", "mann_48")}
for name, names in rules.items():
lemma(K, name, STATEMENTS[name], lambda g: g.auto(*names, pool=3))
winker_rest(K)
import time
for stage in (winker_by_hand, winker_by_auto):
K = theory()
start = time.perf_counter()
stage(K)
print(f"{stage.__name__:15} {time.perf_counter() - start:5.2f} s, "
f"nodes in 12 lemmas: {sum(nodes(K.proofs[n]) for n in STATEMENTS)}")
winker_by_hand 0.06 s, nodes in 12 lemmas: 2039
winker_by_auto 3.97 s, nodes in 12 lemmas: 1951
A script without creative hints is shorter, and the proof for the kernel is almost the same. We pay with time: the
search takes longer than carrying out ready hints. And where is auto not enough? Lemma mann_50 needs instances of
mann_49 with four arbitrary arguments and of mann_44 with two — each would have to be guessed from the pool of
candidates. Let us count how many candidates a variable in mann_50 would have and how many possibilities that gives
for four variables at once:
import robbins
from syntax import equation
l, p = (normal(t) for t in equation(STATEMENTS["mann_50"]))
pool = robbins._pool(l, p, 2)
places = len(list(robbins.positions(l))) + len(list(robbins.positions(p)))
print(f"candidates for one variable: {len(pool)}, for four at once: {len(pool) ** 4:,}".replace(",", " "))
print(f"places in the goal: {places}, terms to check: {places * len(pool) ** 4:,}".replace(",", " "))
candidates for one variable: 15 for four at once: 50 625
places in the goal: 48 terms to check: 2 430 000
More than a million terms, each to be brought to the normal form — and that for a single step. That is why in lemmas
50–54 the script gives the instances itself — as in mathlib — and we leave auto for the places where one variable is
free. This is a typical compromise: a searching tactic compresses the script, but only where the space of
possibilities is small. The rest of the compression comes from a well-chosen lemma — more about that in the next part.
How to design a tactic#
These four examples show a few principles that fit every tactic — also the ones we compose in the Boole Lab and in the Tactic Lab (see Scenarios: building tactics):
Decide or fail fast.
acalways terminates and never leaves a goal half done: either it closes it, or it reports an error. Such a tactic can safely be called at the end of every branch.Have a measure of progress.
ac_simpterminates because every good rule shortens the term; when the rules do not shorten, the limit saves us. In the Boole Lab the same role is played by the analysis “the sum of the sizes of the goals goes down”.Bound the search.
autolooks at only one step from each side and at a bounded pool of candidates. When the pool grows exponentially, a hint is better.Do not ask for trust. Each of these tactics writes an ordinary proof made of five rules. The kernel checks it just like a proof typed by hand (the de Bruijn criterion, see Bound variables and de Bruijn indices).
Compress what repeats. In the Robbins proof the most frequent thing is the bookkeeping of associativity and commutativity — and this is exactly what
acswallows.
References and places worth a visit#
Lean 4: the tactic
ac_rfl(in mathlib used with the type classesStd.AssociativeandStd.Commutative, seeArchive/Robbins.lean); mathlib also hasabelandring, which bring expressions in abelian groups and rings to a normal form.F. Baader, T. Nipkow, Term Rewriting and All That, Cambridge University Press (1998) — normal forms, rewriting modulo AC and its termination.
W. McCune, Solution of the Robbins Problem (1997) — on unification modulo AC in the program EQP, which does the same as our tactic
ac, but inside the search.