About this notebook
Companion to Lecture 12: AI meets Lean. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see
lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)
Lecture 12 describes AI provers as a loop: something proposes proof steps, Lean checks them, and the answers steer what is proposed next. This notebook builds the smallest honest version of that loop, with no machine learning at all. You will:
- drive Lean one tactic at a time from Python, and read its answers;
- write a best-first search over a fixed list of eight tactics;
- run it on twenty small theorems with two different policies (ways of ranking tactics);
- plot how many theorems each policy proves as the budget of Lean calls grows;
- check every proof it found again, from scratch, as an ordinary Lean theorem.
The search proposes; only Lean decides. Everything below is deterministic, so the numbers are the same on every run.
import leanmagic
leanmagic.setup("", mem_limit_gb=6)Lean 4.35.0 ready; header `(empty header)` elaborated.
The header is empty, so this is core Lean only, and the REPL is stopped if it ever uses more than 6 GiB. One theorem below is about a function we define here:
def double : Nat → Nat
| 0 => 0
| n + 1 => double n + 2✓ Lean accepted this (no messages)
1. Lean as a judge, one call at a time
leanmagic.get_session() returns the Lean process that runs this notebook’s %%lean cells.
We send it a theorem whose proof is sorry. Lean reports the open goal and a proof state:
a handle we can apply tactics to.
S = leanmagic.get_session()
res = S.run("example (p q : Prop) : p → q → p ∧ q := by sorry", advance=False)
root = res.sorries[0]
print(root.goal)p q : Prop ⊢ p → q → p ∧ q
S.tactic(t, state) runs one tactic on a proof state and returns a new one, without
changing the old. So we can try several tactics on the same state, which is what a search
needs. A tactic that fails comes back with an error and no new state.
def show(label, r):
if r.proof_state is None:
print(f"{label}: failed: {r.errors[0].data.splitlines()[0]}")
else:
goals = " | ".join(g.replace("\n", "; ") for g in r.goals) or "(no goals)"
print(f"{label}: {goals}")
a = S.tactic("intro", root.proof_state)
show("intro", a)
show("constructor", S.tactic("constructor", root.proof_state))
b = S.tactic("intro", a.proof_state)
c = S.tactic("constructor", b.proof_state)
show("intro, intro, constructor", c)
d = S.tactic("assumption", S.tactic("assumption", c.proof_state).proof_state)
show("... assumption, assumption", d)
print("proof status:", d.raw.get("proofStatus"))intro: p q : Prop; a✝ : p; ⊢ q → p ∧ q constructor: failed: REPL: Lean error: intro, intro, constructor: case left; p q : Prop; a✝¹ : p; a✝ : q; ⊢ p | case right; p q : Prop; a✝¹ : p; a✝ : q; ⊢ q ... assumption, assumption: (no goals) proof status: Completed
intro names the new hypotheses a✝ and a✝¹. The ✝ marks a name that you cannot type,
but assumption does not need names. When no goals are left, the REPL also reports a
proof status. “Completed” means that it assembled the whole proof term, had the kernel
check it, and found no sorry in it. That status is the only thing our search will accept
as success.
2. The search
Each step of the search tries one pair (proof state, tactic). Two choices shape it:
- a policy ranks the eight tactics for a given goal: rank 0 is tried first;
- a cost: a step costs
1 + 3 × rank, and a path costs the sum of its steps. The search always tries the cheapest untried pair next (best-first), so it follows highly ranked tactics deep before it tries low-ranked ones near the root.
A failed tactic is dropped. A new proof state is kept only if its list of goals has not been seen before; then all eight of its pairs join the queue. The budget is the number of tactic calls to Lean we allow for one theorem.
queue ← pairs (start state, tactic), each with its cost
while queue not empty and calls < budget:
take the cheapest pair (s, t); ask Lean to run t on s
error → drop it
status "Completed" → proved: return the path of tactics
new goals, not seen → push (new state, t') for all eight tactics t'The two policies:
- fixed order ranks the tactics in the same order for every goal;
- shape hints looks at the text of the goal first, like the
steptactic of Notebook 11:introfor→and∀,constructorfor∧and↔,leftandrightfor∨,omegaandrflfor=,≤,<,≠. The other tactics follow in the fixed order.
import heapq
import itertools
TACTICS = ["rfl", "assumption", "omega", "simp", "intro", "constructor", "left", "right"]
def fixed_order(goal):
return TACTICS
def shape_hints(goal):
target = goal.split("⊢ ")[-1] # the goal after the turnstile
first = []
if target.startswith("∀") or "→" in target:
first.append("intro")
if "∧" in target or "↔" in target:
first.append("constructor")
if "∨" in target:
first += ["left", "right"]
if any(op in target for op in ["=", "≤", "<", "≠"]):
first += ["omega", "rfl"]
return first + [t for t in TACTICS if t not in first]
def search(statement, policy, budget):
"""Best-first search. Returns (proved?, tactic calls used, list of tactics or None)."""
start = S.run(f"example {statement} := by sorry", advance=False).sorries[0]
tick = itertools.count() # breaks ties by insertion order, so runs are repeatable
queue = []
def push(state, goals, path, cost):
for rank, tac in enumerate(policy(goals[0])):
heapq.heappush(queue, (cost + 1 + 3 * rank, next(tick), state, path, tac))
push(start.proof_state, [start.goal], [], 0)
seen = {(start.goal,)}
calls = 0
while queue and calls < budget:
cost, _, state, path, tac = heapq.heappop(queue)
calls += 1
r = S.tactic(tac, state)
if r.proof_state is None:
continue
if r.raw.get("proofStatus") == "Completed":
return True, calls, path + [tac]
if not r.goals or tuple(r.goals) in seen:
continue
seen.add(tuple(r.goals))
push(r.proof_state, r.goals, path + [tac], cost) # cost so far, including this step
return False, calls, None3. Twenty theorems
The test set mixes arithmetic, propositional logic, one list fact and four theorems that need something the eight tactics cannot supply: a witness, a lemma name, induction, or applying a hypothesis to an argument.
THEOREMS = {
"two_plus_three": ": 2 + 3 = 5",
"add_comm": ": ∀ a b : Nat, a + b = b + a",
"lt_succ": "(a b : Nat) (h : a < b) : a + 1 ≤ b",
"odd_ne_zero": "(n : Nat) (h : n % 2 = 1) : n ≠ 0",
"chain_eq": "(a b : Nat) (h₁ : a = 3) (h₂ : b = a + 1) : b = 4",
"append_nil": "(xs : List Nat) : (xs ++ []).length = xs.length",
"exists_add": ": ∃ x : Nat, x + 2 = 5",
"iff_self": "(p : Prop) : p ↔ p",
"imp_self": "(p : Prop) : p → p",
"or_left": "(p q : Prop) : p → p ∨ q",
"or_right": "(p q : Prop) : q → p ∨ q",
"and_intro": "(p q : Prop) : p → q → p ∧ q",
"or_and": "(p q : Prop) : q → (p ∨ q) ∧ q",
"and_swap": "(p q : Prop) : p ∧ q → q ∧ p",
"and3": "(p q r : Prop) : p → q → r → p ∧ (q ∧ r)",
"and_or": "(p q r : Prop) : p → r → (p ∨ q) ∧ (q ∨ r)",
"imp_chain": "(p q r : Prop) : (p → q) → (q → r) → p → r",
"square_49": ": ∃ n : Nat, n * n = 49",
"le_square": "(n : Nat) : n ≤ n * n",
"double_eq": ": ∀ n : Nat, double n = 2 * n",
}
BUDGET = 80
POLICIES = {"fixed order": fixed_order, "shape hints": shape_hints}
results = {name: {pol: search(stmt, f, BUDGET) for pol, f in POLICIES.items()}
for name, stmt in THEOREMS.items()}
print(f"{'theorem':<15}{'fixed':>7}{'hints':>7} proof found with shape hints")
for name, row in results.items():
cells = [f"{row[p][1]:>7}" if row[p][0] else f"{'-':>7}" for p in POLICIES]
ok, _, path = row["shape hints"]
proof = "; ".join(path) if ok else "(none)"
print(f"{name:<15}{cells[0]}{cells[1]} {proof}")
for pol in POLICIES:
n = sum(row[pol][0] for row in results.values())
print(f"{pol}: {n} of {len(THEOREMS)} proved within {BUDGET} calls")
print()
for name, row in results.items():
if not row["shape hints"][0]:
used = ", ".join(f"{p} {row[p][1]}" for p in POLICIES)
print(f"{name}: no proof; calls made before the search stopped: {used}")theorem fixed hints proof found with shape hints two_plus_three 1 1 omega add_comm 3 3 intro; intro; omega lt_succ 2 1 omega odd_ne_zero 3 1 omega chain_eq 3 1 omega append_nil 4 4 simp exists_add 4 4 simp iff_self 1 4 rfl imp_self 4 4 intro; assumption or_left 17 6 intro; left; assumption or_right 22 11 intro; right; assumption and_intro 29 16 intro; intro; constructor; assumption; assumption or_and 34 23 intro; constructor; right; assumption; assumption and_swap 53 40 simp; intro; intro; constructor; assumption; assumption and3 53 35 intro; intro; intro; constructor; assumption; constructor; assumption; assumption and_or 62 36 intro; intro; constructor; left; assumption; right; assumption imp_chain - - (none) square_49 - - (none) le_square - - (none) double_eq - - (none) fixed order: 16 of 20 proved within 80 calls shape hints: 16 of 20 proved within 80 calls imp_chain: no proof; calls made before the search stopped: fixed order 32, shape hints 32 square_49: no proof; calls made before the search stopped: fixed order 16, shape hints 16 le_square: no proof; calls made before the search stopped: fixed order 8, shape hints 8 double_eq: no proof; calls made before the search stopped: fixed order 16, shape hints 16
The numbers are tactic calls until success; - means no proof within the budget. Both
policies prove the same sixteen theorems, and fail on the same four. The hints change how
fast, not what: on the longer proofs (and_intro, and3, and_or) the hinted search
needs clearly fewer calls, because the right tactic is usually its first choice.
Look at the failures. imp_chain wants a hypothesis applied to an argument, as in
exact hqr (hpq hp); square_49 wants the witness 7; le_square wants a library lemma
such as Nat.le_mul_self; double_eq wants induction. None of those is in the list. The
last four lines show that a larger budget would not help: for every failure the search
stopped because it had no new proof states left to try, well before 80 calls.
4. Success against budget
For every budget from 0 to 80 calls, count the theorems that each policy proved within that many calls.
import matplotlib.pyplot as plt
budgets = list(range(BUDGET + 1))
fig, ax = plt.subplots(figsize=(6.4, 3.8))
for (pol, color) in zip(POLICIES, ["#81796f", "#2c5f9e"]):
used = [row[pol][1] for row in results.values() if row[pol][0]]
proved = [sum(u <= b for u in used) for b in budgets]
ax.step(budgets, proved, where="post", color=color, lw=2, label=pol)
ax.axhline(len(THEOREMS), color="#b5523b", lw=1, ls="--")
ax.text(BUDGET, len(THEOREMS) - 0.4, f"all {len(THEOREMS)} theorems", color="#b5523b",
ha="right", va="top", fontsize=9)
ax.set_xlabel("budget: Lean tactic calls per theorem")
ax.set_ylabel("theorems proved")
ax.set_xlim(0, BUDGET)
ax.set_ylim(0, len(THEOREMS) + 1)
ax.legend(loc="center right", frameon=False)
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
How many of the 20 test theorems each policy proves within a given number of Lean tactic calls. Both policies end at the same 16; the shape hints reach them with fewer calls. No budget proves the other 4, because the tactics they need are not in the list.
5. Check the proofs again
The search trusted the REPL’s “Completed”. As a last step, independent of the search, we
paste each proof it found into an ordinary theorem, compile it from scratch, and ask
#print axioms. This is the audit of Lecture 12: the proof must compile, contain no
sorry, and use only standard axioms.
for name, row in results.items():
ok, _, path = row["shape hints"]
if not ok:
continue
body = "\n ".join(path)
code = (f"theorem found_{name} {THEOREMS[name]} := by\n {body}\n\n"
f"#print axioms found_{name}")
r = S.run(code, advance=False)
clean = not r.errors and not any("sorry" in m.data for m in r.warnings)
report = r.infos[-1].data if r.infos else "?"
axioms = "none" if "does not depend" in report else report.split(": ", 1)[-1]
print(f"{name:<15}{'compiles' if clean else 'FAILED':<10}axioms: {axioms}")two_plus_three compiles axioms: [propext, Quot.sound] add_comm compiles axioms: [propext, Quot.sound] lt_succ compiles axioms: [propext, Quot.sound] odd_ne_zero compiles axioms: [propext, Quot.sound] chain_eq compiles axioms: [propext, Quot.sound] append_nil compiles axioms: [propext] exists_add compiles axioms: [propext, Quot.sound] iff_self compiles axioms: none imp_self compiles axioms: none or_left compiles axioms: none or_right compiles axioms: none and_intro compiles axioms: none or_and compiles axioms: none and_swap compiles axioms: [propext] and3 compiles axioms: none and_or compiles axioms: none
Every proof compiles on its own, without sorry, and the axioms are at most propext and
Quot.sound, two of Lean’s three standard axioms. In this table they appear exactly in the
proofs that use simp or omega; the purely logical proofs use no axioms at all.
6. How this compares with real provers
this notebook AI provers (Lecture 12)
proposes steps 8 fixed tactics a trained model; any tactic text,
including lemma names and witnesses
ranks them hand-written shape hints the model's probabilities
budget at most 80 calls often thousands of attempts
learns never the reward trains the model
final judge Lean: "Completed", then Lean: the same kernel check,
#print axioms then the same auditThe last row is the one that matters. Our search is crude, but a proof it reports is as trustworthy as one from the best system in Lecture 12’s table, because neither is trusted: the kernel checks the term either way. Everything above the last row is about how often a proof is found, and how cheaply.
The four failures show where models help. Each needs a piece of text that no fixed list
contains: the witness in ⟨7, rfl⟩, the name Nat.le_mul_self, the shape of an induction,
the application hqr (hpq hp). A language model can propose such text; whether it is
right is still Lean’s call. In the other direction, some systems do not search step by
step at all: they write whole proofs and sample many of them, which is what scores
“at 8,192 attempts” mean. aesop (Lecture 11) is a best-first search like this one, with
hand-written rules in place of our eight tactics.
Try this
- Add
simp_alltoTACTICSand run the notebook again. Which of the four failures does it fix, and why can it not fix the others?- Change the step cost from
1 + 3 × rankto1for every tactic. The search becomes breadth-first. What happens to the two curves?- Add a theorem of your own that needs at least five steps, and find the smallest budget at which each policy proves it.
- Replace
shape_hintswith a policy of your own design and try to beat it on the three longest proofs.