Search

Search papers and lessons

LeanDojo: Theorem Proving with Retrieval-Augmented Language Models

Kaiyu Yang, Aidan Swope, Alex Gu et al. · 2023

LeanDojo opens up Lean theorem proving with free tools, data and a benchmark; its ReProver model retrieves the premises it needs from the math library before each proof step.

On this page

  • Colour = topic mix
  • Algorithms
  • Probability
  • Discrete math
  • Language & LLMs
  • Neural network basics
  • Calculus
  • ReadReady to readNot yet

TL;DR

Large language models can write formal proofs, but the strongest ones were closed: their training data, their proof-checking setup and their compute were private. LeanDojo is an open toolkit that extracts data from the Lean proof assistant and lets a program run tactics on Lean and read back the result. Its ReProver model is a language model that, before each proof step, retrieves the 100 lemmas (premises) from Lean's math library that look most similar to the current goal and reads them next to the goal. On the random test split it proves 51.2% of held-out theorems, against 47.6% for the same model without retrieval.

Builds on: Retrieval-Augmented Generation, Dense Passage Retrieval for Open-Domain Question Answering, Premise Selection, Tree Search · Leads to: later retrieval-based provers for Lean

Why it mattered

The paper shipped the things that were missing: the code that extracts training data from Lean, an interface that lets a model try tactics and see whether Lean accepts them, a benchmark of 98,734 theorems and proofs from Lean's math library, the trained models, and code under an MIT license. The authors report that training ReProver took about 120 GPU hours on one A100 with 80 GB of memory, where earlier Lean provers reported more than 1,000 hours. That number is the reason the paper matters to a small lab: a new idea about retrieval can now be tested on one GPU in a few days.

The paper is also the first retrieval-augmented language model for formal theorem proving, which turns a retrieval idea from natural language processing into a tool for mathematics. Lean checks every proof, so a wrong proof is rejected rather than read as a plausible-sounding answer, which gives the evaluation a rigour that text generation lacks.

The problem

Lean is a programming language in which you state theorems and write their proofs. A proof is a sequence of tactics, commands such as "rewrite using this fact" that turn the current goal into simpler goals. The goal and the local facts together are the proof state. The proof is complete when no goals remain. Lean's standard library, mathlib, is large: this paper's benchmark counts 130,262 premises in it. Any of them can be a premise (a lemma or a definition) that a tactic uses.

Two things made learning-based proving hard before this paper.

  1. The raw code is not training data. A Lean file shows the final proof, not the intermediate states between tactics, and it does not say which premise a name refers to after Lean has resolved it. Without those states, a model cannot learn what each step did.
  2. Memorising premises does not generalise. A prover that has seen the lemma mod_self in training can learn to suggest it for similar goals. It cannot use a lemma it has never seen. Putting the whole library in the model's input is also impossible: the paper's library holds 130,262 premises, and a language model's context window is limited. So the model needs to pick premises from the library, which is the problem of Premise Selection.

Existing tools had a further gap. The paper reports that lean-gym, the only mature open-source tool before LeanDojo, marked 21.1% of correct human-written proofs as wrong, because it did not handle Lean namespaces, so names failed to resolve in proofs that were correct. A reward signal that wrong is useless for reinforcement learning.

How it works

Here is the pipeline in the order it runs. Two parts sit side by side: the data side that builds the benchmark and the search side that proves theorems.

flowchart LR
  A[Lean repository] --> B[LeanDojo extraction]
  B --> C[States, tactics, premises]
  C --> D[Accessible premises for each theorem]
  E[Current proof state] --> F[Retriever: top 100 premises]
  D --> F
  F --> G[ByT5 tactic generator]
  G --> H[Candidate tactics]
  H --> I[Lean checks each tactic]
  I --> J[Best-first search over proof states]
  1. Extract. LeanDojo reads a Lean repository and records every file's imports, the abstract syntax tree of each file, every tactic with the state before and after it, and for each premise the place it is defined and every place it is used. The paper's benchmark comes from mathlib, at one fixed commit, with 3,384 Lean files.
  2. Restrict to accessible premises. For a theorem, only premises defined earlier in its file or imported from other files can be used, so the candidate pool shrinks. The paper gives the average pool as 33,160 premises instead of the 130,262 in total.
  3. Embed the state and the premises. The retriever turns the proof state into a vector and each accessible premise into a vector, using the same encoder. Premise vectors can be computed once, ahead of time.
  4. Retrieve. The score of a premise is the cosine similarity between its vector and the state's vector. The top 100 premises are kept.
  5. Concatenate. The state and the retrieved premises are joined into one string and cut to a fixed length.
  6. Generate a tactic. An encoder-decoder Transformer called ByT5 reads that string and writes the next tactic. Because the input is retrieved text, the model can use a premise it never saw in training if the retriever finds it.
  7. Check with Lean. The candidate tactic is run through the Lean environment. An error state means the branch is dead; a new state means the search goes on from there.
  8. Search. A standard best-first search keeps a priority queue of proof states, expands the most promising one, and stops when every goal is solved or the ten-minute wall-time limit runs out.

Tiny instance of step 3 and 4 (a made-up example to show the arithmetic, not a number from the paper). Suppose the state is a two-number vector (1,1)(1, 1) and three accessible premises have these vectors: mod_self gives (2,2)(2, 2), a lemma about order gives (3,1)(3, 1), and gcd_zero_left gives (0,3)(0, 3). Cosine similarity ignores length and compares direction. mod_self points exactly the same way as the state, so its score is 1.00. The order lemma scores about 0.89, and gcd_zero_left about 0.71. With a top-2 cut, the retriever returns mod_self and the order lemma, and the generator sees both next to the goal.

The math

The retriever is a bi-encoder, and its score is the cosine between two vectors. Each piece is written in the paper's notation.

Definition: Premise retrieval

Let ss be a proof state, P\mathcal{P} the set of accessible premises, and f(⋅,θ)f(\cdot, \theta) an encoder that maps text to an hh-dimensional vector. The retriever ranks each premise pp in P\mathcal{P} by

score(s,p)=f(s,θ)Tf(p,θ)∥f(s,θ)∥2 ∥f(p,θ)∥2\mathrm{score}(s, p) = \frac{f(s,\theta)^{T} f(p,\theta)}{\lVert f(s,\theta) \rVert_2 \, \lVert f(p,\theta) \rVert_2}

and returns the mm premises with the highest scores. The paper uses m=100m = 100.

Step 1 in symbols: accessible premises

For each theorem, P\mathcal{P} is restricted to the premises it can see. This is a filter on the library before any scoring, so the retriever never has to rank the premises it cannot use. The paper's averages are 33,160 accessible premises against 130,262 in total.

Step 3 in symbols: the training signal

Take a batch of bb proof states. For each state sis_i there is one ground-truth premise, a positive, and nn sampled negatives. The negatives are shared across the batch, so each state is scored against all b(n+1)b(n+1) premises in the batch, and at least one of them is positive for that state. Let lijl_{ij} be 1 when premise jj is a positive for state ii and 0 otherwise. The paper writes the loss as

L(θ)=∑i=1b∑j=1b(n+1)∣ lij−cos⁡(f(si,θ), f(pj,θ))∣2\mathcal{L}(\theta) = \sum_{i=1}^{b} \sum_{j=1}^{b(n+1)} \left\lvert\, l_{ij} - \cos\bigl(f(s_i,\theta),\, f(p_j,\theta)\bigr) \right\rvert^{2}

The paper calls this a contrastive loss, and it is one in spirit: it pushes the score of positives toward 1 and of negatives toward 0. The formula it writes is a squared error between the label and the cosine. Worked by hand: a positive with cosine 0.8 contributes (1−0.8)2=0.04(1 - 0.8)^2 = 0.04, and a negative with cosine 0.3 contributes (0−0.3)2=0.09(0 - 0.3)^2 = 0.09. The loss is small when positives score high and negatives score low.

The in-file negatives change which negatives are sampled. Of the nn negatives, kk are drawn from the same Lean file as the positive, and n−kn - k are drawn at random. The reason is an error the authors saw early on: with purely random negatives, the model often retrieved other premises from the same file as the positive, which are close to it and can be just as useful.

Step 6 in symbols: the tactic

The generator sees the state and the retrieved premises, concatenated and cut to a fixed length, and outputs a tactic tt. It is trained to minimise the usual cross-entropy loss against the tactic a human wrote in that situation. Lean enters later, when the search checks the candidates it proposes.

Example
Retrieval with the numbers from the worked instance
  1. The state is (1,1)(1, 1). Its length is 2≈1.41\sqrt{2} \approx 1.41.
  2. mod_self is (2,2)(2, 2). Dot product =4= 4. Length =8≈2.83= \sqrt{8} \approx 2.83. Score =4/(1.41×2.83)=4/4=1.00= 4 / (1.41 \times 2.83) = 4 / 4 = 1.00.
  3. The order lemma is (3,1)(3, 1). Dot product =4= 4. Length =10≈3.16= \sqrt{10} \approx 3.16. Score =4/(1.41×3.16)≈0.89= 4 / (1.41 \times 3.16) \approx 0.89.
  4. gcd_zero_left is (0,3)(0, 3). Dot product =3= 3. Length =3= 3. Score =3/(1.41×3)≈0.71= 3 / (1.41 \times 3) \approx 0.71.
  5. Interpretation: the ranking is mod_self, order lemma, gcd_zero_left. Only the first two enter the prompt. Scaling mod_self to (20,20)(20, 20) would not change its score, because only the direction matters.

Try it: suppose a fourth premise has vector (1,0)(1, 0). Compute its score and say whether it would enter the top two. Answer: dot product =1= 1, length =1= 1, score =1/(1.41×1)≈0.71= 1 / (1.41 \times 1) \approx 0.71. It ties with gcd_zero_left, so it would not enter the top two unless the cut were wider.

Results

The paper reports two kinds of result: premise selection on its own, and theorem proving with the full search. Both are on the LeanDojo Benchmark, which has 94,734 training theorems, 2,000 validation theorems and 2,000 test theorems. It has two splits. The random split is the usual one. The novel_premises split requires the test proof to use at least one premise never used in training. The authors argue that performance on such challenging splits says more about a prover's ability, and that future work should emphasise them.

Table 1: premise selection (test). R@k is the share of ground-truth premises found among the top k; MRR is the mean reciprocal rank, where a hit at rank 1 scores 1 and a hit at rank 10 scores 0.1.

Methodrandom R@1random R@10random MRRnovel_premises R@1novel_premises R@10novel_premises MRR
BM256.717.20.155.915.50.14
Ours (ReProver retriever)13.538.40.319.127.60.24
Ours, without in-file negatives10.833.10.257.925.70.22

Table 2: theorem proving, Pass@1 (%) on the test set. Pass@1 means one attempt, with a ten-minute wall-time limit per theorem.

Methodrandomnovel_premises
tidy (a heuristic tactic in mathlib)23.85.3
GPT-4, zero-shot, 35 tactics per state29.07.4
ReProver (ours)51.226.3
ReProver without retrieval47.623.2

What these numbers mean. The retriever beats BM25, a keyword method that needs no training, by a wide margin on both splits. Removing the in-file negatives costs about five points of R@10 on the random split, so that idea does real work. Retrieval adds 3.6 points on the random split and 3.1 on the novel split over the same generator without it. Every method drops on the novel split, and the authors argue that split should be emphasised in future work.

Limits the paper itself states. The GPT-4 baseline may have seen the ground-truth proofs in its training data, because many were public on GitHub before its cutoff, so its score is hard to read as a clean comparison. The paper does not compare ReProver with other LLM-based provers, because their training data or tools were not public (the appendix lists the reasons). On the two outside datasets, MiniF2F and ProofNet, which contain no training theorems, ReProver reaches 26.5% and 13.8% Pass@1. The paper also reports 33 proofs for MiniF2F theorems and 39 for ProofNet theorems that had no Lean proof before, which shows the tool can help extend a library, but these are counts of new proofs with the caveats the appendix lists, not a general proof rate.

Reading guide

Read the paper in this order and use the lessons it needs:

  • Abstract and Section 1 (Introduction). Motivation and the premise-selection bottleneck. Needs Retrieval-Augmented Generation for the idea of conditioning a model on retrieved text.
  • Section 2 (Related Work). Skim. The useful part is the list of learning-based provers and their architectures, which goes from classical models to Transformer language models.
  • Section 3 (Background: theorem proving in Lean). Lean's tactics and premises. Read the figures; no lesson is needed beyond the terms defined above.
  • Section 4 (LeanDojo: toolkit and benchmark). Data extraction, the benchmark splits and the interaction interface. Needs Tree Search for the proof-search view and Formal Verification for why checking matters.
  • Section 5 (ReProver). The core method. Needs Bi-Encoder and Dense Passage Retrieval for Open-Domain Question Answering for the retriever, Contrastive Learning and Cosine Similarity for the loss and score, and Encoder-Decoder Architecture with Cross-Entropy Loss for the generator.
  • Section 6 (Experiments). The tables above. Needs BM25 as the classical baseline and Mean Squared Error for the form of the loss the paper writes.
  • Appendix A (technical details) and D (Lean 4). Optional. Appendix A explains the lean-gym failure; Appendix D repeats the experiments for Lean 4.

Check yourself

QuestionWhat is a premise, and why does a prover need to select them from a library?Show answer
A premise is an existing lemma or definition that a tactic uses as an argument. A library such as mathlib holds about 130,000 premises in this paper's benchmark, and a language model's input can only hold a small fraction of them. The prover has to retrieve the few that are relevant to the current goal.
QuestionUsing the worked instance: the state is (1, 1) and a premise is (4, 4). What is its cosine score, and why does its length not matter?Show answer
Dot product is 1 times 4 plus 1 times 4, which is 8. The lengths are the square root of 2 and the square root of 32, which is 4 times the square root of 2. The score is 8 divided by (the square root of 2 times 4 times the square root of 2), which is 8 divided by 8, so 1.00. Cosine divides out the lengths, so only the direction of the vectors matters: a premise scaled by 4 scores the same as the original.
QuestionWhy does the paper evaluate on a novel_premises split as well as a random split?Show answer
On a random split, a model can lean on premises it saw in training. The novel split forces the test proof to use at least one premise never used in training, which tests whether the prover can use a premise it has not learned by heart. All methods score lower on it, which is why the authors treat it as the more honest measure.
QuestionWhy does the paper sample in-file negatives instead of only random ones?Show answer
In early experiments the retriever often ranked other premises from the same file as the positive, so it needed training examples that show the difference. Sampling in-file negatives supplies those hard cases. The paper's ablation shows that removing in-file negatives lowers R@10 on the random split from 38.4 to 33.1.
QuestionA prover marks a correct human proof as wrong. Give one reason the paper says this is dangerous for training with reinforcement learning.Show answer
The reward signal is noisy: a correct tactic gets a failure reward, so the policy learns from the environment's bug rather than from the mathematics. The paper reports that lean-gym misjudged 21.1% of correct proofs, which makes any reward it produces unreliable.

Sources

Read the full paper

Kaiyu Yang, Aidan Swope, Alex Gu et al., 2023. arXiv:2306.15626