LeanAgent is a novel lifelong learning framework for formal theorem proving that continuously generalizes to and improves on ever-expanding mathematical knowledge without forgetting previously learned knowledge.
See the codeLeanAgent is a novel lifelong learning framework for formal theorem proving that continuously generalizes to and improves on ever-expanding mathematical knowledge without forgetting previously learned knowledge.
Generated docs by Devin are here: [https://deepwiki.com/lean-dojo/LeanAgent]. It includes a detailed explanation + diagrams.
run_leanagent.shRAID_DIR variable to your desired directory pathsource command to match your installationconda create -n "LeanAgent" python=3.10
conda activate LeanAgent
pip install -r requirements.txt
GITHUB_ACCESS_TOKEN in the script to itRAID_DIR variable in replace_files.shbash replace_files.sh
leanagent.pyrepo_dir: Path to your repositoryDATA_DIR: Directory for storing dataCHECKPOINT_DIR: Directory for model checkpointsEVAL_RESULTS_FILE_PATH: Path for evaluation resultsDB_FILE_NAME: Database filenamePROOF_LOG_FILE_NAME: Proof logging filenameENCOUNTERED_THEOREMS_FILE: Path for tracking encountered theoremsFISHER_DIR: Directory for Fisher Information Matrices (FIMs)main() function according to your requirements. The default options correspond to the LeanAgent configuration, and alternate options can be used to replicate ablation studies from the paper.generate_benchmark_lean4.py if needed:lean_dir2 = f"/.elan/toolchains/leanprover--lean4---{v}"
lean_dir3 = f"~/.elan/toolchains/leanprover--lean4---{v}"
These should match your system's Lean installation paths.
pip install gdown
gdown https://drive.google.com/uc?id=11DXxixg6S4-hUA-u-78geOxEB7J7rCoX
Move the downloaded file to {RAID_DIR}/
gdown https://drive.google.com/uc?id=1aRd1jQPu_TX15Ib5htzn3wZqHYowl3ax
Move the downloaded file to:
{RAID_DIR}/checkpoints/
{RAID_DIR}/{CHECKPOINT_DIR}/
gdown https://drive.google.com/uc?id=1plkC7Y5n0OVCJ0Ad6pH8_mwbALKYY_FY
Move the downloaded file to {RAID_DIR}/checkpoints/
bash run_leanagent.sh
If you want to use Elastic Weight Consolidation (EWC) for lifelong learning, as shown in our ablation studies, follow these additional steps:
compute_fisher.pyCreate and set the new_data_path: Path to new training data
Download the starting FIM for mathlib:
gdown https://drive.google.com/uc?id=1Q8yHq7XTAaHXGCiCGmhwZhTfkhHhN1cP
Move the downloaded file to your FISHER_DIR.
run_compute_fisher.shRAID_DIR variable to your desired directory pathsource command to match your installationGITHUB_ACCESS_TOKENTo use EWC in the training process, alternate between running run_leanagent.sh and run_compute_fisher.sh:
bash run_leanagent.sh for one epoch. Setting use_fisher = True in leanagent.py does this automatically.bash run_compute_fisher.sh to compute the FIMbash run_leanagent.sh again for the next epochTo run the unit test suite, first activate the conda environment and then use pytest:
conda activate LeanAgent
python -m pytest tests/
LeanAgent is a lifelong learning framework for formal theorem proving that continuously generalizes to and improves on expanding mathematical knowledge without forgetting previously learned information. The codebase consists of several key components:
LeanAgent begins by searching for and processing Lean repositories from GitHub. The system maintains a list of known repositories to avoid duplicate processing and uses the GitHub API to identify repositories with Lean as their primary language.
For each identified repository, LeanAgent checks compatibility by determining if the repository uses a supported Lean version. This is done by examining the repository's lean-toolchain configuration file. Currently, supported versions range from Lean 4.3.0-rc2 to Lean 4.8.0-rc1. If compatible, the system clones the repository and extracts its commit SHA for version tracking.
To ensure compatibility with older repositories, LeanAgent can search through a repository's commit history to find the most recent commit that uses a supported Lean version. This allows the system to work with repositories that might have updated to newer, unsupported Lean versions.
The system maintains a list of known repositories that are either already processed or unsuitable for other reasons. This list includes repositories focused on functional programming rather than mathematics, repositories with trace problems, or those with too few theorems to be useful for training.
Once a compatible repository is identified, LeanAgent begins the data extraction process:
Repository Tracing: The system uses LeanDojo's trace function to extract theorem definitions, proofs, and premises from the repository. This involves:
Theorem Processing: Each theorem is stored with its full name, file path, source positions, URL, commit reference, and theorem statement
Premise Collection: The system extracts premises (theorems, lemmas, definitions) from the repository, recording their:
Tracing File Dependencies: LeanAgent builds a topological graph of file dependencies to ensure premises are properly ordered during dataset generation. This ordering is crucial for theorem proving, as premises can only be used after they've been defined.
Then, LeanAgent organizes the traced data into a structured dataset:
Proof Export: For each theorem in the dataset, LeanAgent exports:
Premise Export: LeanAgent exports premise definitions in a topologically sorted order to maintain dependency relationships. Each premise file contains:
Metadata Generation: Additional metadata is recorded for each dataset:
Once generated, the dataset is integrated into LeanAgent's dynamic database (described in more detail in the next section). To do this, a Repository object is created with the extracted data and the repository is added to the dynamic database.
At the core of LeanAgent is a custom dynamic database that tracks and manages all mathematical knowledge across repositories. This database stores:
The database provides functionality to add new repositories, update existing ones, and generate merged datasets from multiple repositories. It uses a JSON-based storage format that can be persisted between runs. Specifically, each class implements to_dict and from_dict methods for conversion. Special handling is provided for non-JSON-serializable types like datetime objects, and the serialization format preserves the full structure of theorems, tactics, and premises. This enables the database to be persisted between runs and distributed across computing resources when necessary.
When generating a dataset from the database, the database can deduplicate theorems and premises when merging repositories, prioritizing the most recently added versions.
The database implementation consists of several interrelated data structures:
sorry that haven't been proven yet, maintaining lists of Premise Files, and providing helper methods for accessing and manipulating theorems and premises.LeanAgent implements a sophisticated curriculum learning strategy based on theorem complexity. The system calculates the complexity of each theorem using an exponential function of the number of proof steps: $e^S$ where $S$ is the number of proof steps. This exponential scaling accounts for the combinatorial explosion of possible proof paths as proofs get longer.
Theorems with no proofs (sorry theorems) are assigned infinite complexity. The system computes the 33rd and 67th percentiles of complexity across all theorems to establish thresholds for categorizing theorems as Easy, Medium, or Hard.
Repositories are then sorted based on the number of easy theorems they contain. This sorting forms the basis of the curriculum, with LeanAgent starting on repositories with the highest number of easy theorems and gradually progressing to more challenging ones.
For theorems without existing proofs, the system distributes them evenly across the three difficulty categories to maintain balance in the curriculum. This approach ensures that LeanAgent builds foundational knowledge before attempting more complex mathematical domains.
LeanAgent employs a simple but effective progressive training approach to avoid catastrophic forgetting. Starting with a pre-trained retriever (based on ByT5), the system trains on each new repository dataset for one additional epoch.
This limited exposure to new data helps prevent overfitting while allowing the model to incorporate essential new information. The retriever is continuously updated during training, and embeddings for all premises are precomputed after each training session to ensure proper evaluation.
The system saves checkpoints based on validation performance, specifically the recall at 10 (R@10) metric, which measures how often the correct premise is among the top 10 retrieved premises. LeanAgent evaluates both plasticity (ability to learn new information) and stability (retention of previous knowledge) by measuring:
This progressive training process is repeated for each repository in the curriculum, allowing LeanAgent to incrementally build its mathematical knowledge while preserving what it has already learned.
sorry Theorem ProvingLeanAgent identifies theorems marked with sorry in the Lean files and attempts to generate formal proofs for them using a best-first tree search approach. For each sorry theorem:
The system processes the premise corpus to build a knowledge base of available facts and definitions
It constructs a directed dependency graph representing file imports to determine which premises are accessible
For each proof state, LeanAgent:
The search continues until a proof is found, all possibilities are exhausted, or a time limit (10 minutes) is reached. Successful proofs are added to the dynamic database, allowing LeanAgent to learn from them in future progressive training.
The system processes theorems in batches (typically 12 theorems per batch) for efficiency and maintains a record of encountered theorems to avoid redundant proving attempts. It also saves progress periodically to ensure resilience against interruptions.
When LeanAgent successfully proves a sorry theorem, it can integrate the generated proof into the original Lean files and create pull requests to propose these changes to repository maintainers. This process involves:
sorry keywords with the generated proof textWhen submitting proven theorems back to repositories, LeanAgent uses a consistent formatting approach with standardized branch names, commit messages, and PR templates that identify the contributions as coming from LeanAgent.
This contribution mechanism helps advance the development of mathematical repositories while also generating additional training data for future research.
LeanAgent is implemented with several key configurations that guide its operation:
The Fisher Information Matrix (FIM) is a key component of Elastic Weight Consolidation (EWC), a technique used in our ablation studies. Although this resulted in suboptimal lifelong learning performance, we describe how to generate and use the Fisher Information Matrix to help replicate our results.
Note: Due to the inherent stochasticity of LLMs and the best-first tree search algorithm used in LeanAgent, your results may vary from those reported in the paper. Differences in hardware, random seeds, and minor implementation details can all affect theorem proving performance.
If you find our work useful, please consider citing our paper:
@inproceedings{kumarappan2025leanagent,
title={{LeanAgent}: Lifelong Learning for Formal Theorem Proving},
author={Kumarappan, Adarsh and Tiwari, Mo and Song, Peiyang and George, Robert Joseph and Xiao, Chaowei and Anandkumar, Anima},
booktitle={International Conference on Learning Representations (ICLR)},
year={2025}
}
Adarsh Kumarappan and Mo Tiwari contributed equally to this work.
LeanAgent is a novel lifelong learning framework for formal theorem proving that continuously generalizes to and improves on ever-expanding mathematical knowledge without forgetting previously learned knowledge.
See the codeLeanAgent is a novel lifelong learning framework for formal theorem proving that continuously generalizes to and improves on ever-expanding mathematical knowledge without forgetting previously learned knowledge.
Generated docs by Devin are here: [https://deepwiki.com/lean-dojo/LeanAgent]. It includes a detailed explanation + diagrams.
run_leanagent.shRAID_DIR variable to your desired directory pathsource command to match your installationconda create -n "LeanAgent" python=3.10
conda activate LeanAgent
pip install -r requirements.txt
GITHUB_ACCESS_TOKEN in the script to itRAID_DIR variable in replace_files.shbash replace_files.sh
leanagent.pyrepo_dir: Path to your repositoryDATA_DIR: Directory for storing dataCHECKPOINT_DIR: Directory for model checkpointsEVAL_RESULTS_FILE_PATH: Path for evaluation resultsDB_FILE_NAME: Database filenamePROOF_LOG_FILE_NAME: Proof logging filenameENCOUNTERED_THEOREMS_FILE: Path for tracking encountered theoremsFISHER_DIR: Directory for Fisher Information Matrices (FIMs)main() function according to your requirements. The default options correspond to the LeanAgent configuration, and alternate options can be used to replicate ablation studies from the paper.generate_benchmark_lean4.py if needed:lean_dir2 = f"/.elan/toolchains/leanprover--lean4---{v}"
lean_dir3 = f"~/.elan/toolchains/leanprover--lean4---{v}"
These should match your system's Lean installation paths.
pip install gdown
gdown https://drive.google.com/uc?id=11DXxixg6S4-hUA-u-78geOxEB7J7rCoX
Move the downloaded file to {RAID_DIR}/
gdown https://drive.google.com/uc?id=1aRd1jQPu_TX15Ib5htzn3wZqHYowl3ax
Move the downloaded file to:
{RAID_DIR}/checkpoints/
{RAID_DIR}/{CHECKPOINT_DIR}/
gdown https://drive.google.com/uc?id=1plkC7Y5n0OVCJ0Ad6pH8_mwbALKYY_FY
Move the downloaded file to {RAID_DIR}/checkpoints/
bash run_leanagent.sh
If you want to use Elastic Weight Consolidation (EWC) for lifelong learning, as shown in our ablation studies, follow these additional steps:
compute_fisher.pyCreate and set the new_data_path: Path to new training data
Download the starting FIM for mathlib:
gdown https://drive.google.com/uc?id=1Q8yHq7XTAaHXGCiCGmhwZhTfkhHhN1cP
Move the downloaded file to your FISHER_DIR.
run_compute_fisher.shRAID_DIR variable to your desired directory pathsource command to match your installationGITHUB_ACCESS_TOKENTo use EWC in the training process, alternate between running run_leanagent.sh and run_compute_fisher.sh:
bash run_leanagent.sh for one epoch. Setting use_fisher = True in leanagent.py does this automatically.bash run_compute_fisher.sh to compute the FIMbash run_leanagent.sh again for the next epochTo run the unit test suite, first activate the conda environment and then use pytest:
conda activate LeanAgent
python -m pytest tests/
LeanAgent is a lifelong learning framework for formal theorem proving that continuously generalizes to and improves on expanding mathematical knowledge without forgetting previously learned information. The codebase consists of several key components:
LeanAgent begins by searching for and processing Lean repositories from GitHub. The system maintains a list of known repositories to avoid duplicate processing and uses the GitHub API to identify repositories with Lean as their primary language.
For each identified repository, LeanAgent checks compatibility by determining if the repository uses a supported Lean version. This is done by examining the repository's lean-toolchain configuration file. Currently, supported versions range from Lean 4.3.0-rc2 to Lean 4.8.0-rc1. If compatible, the system clones the repository and extracts its commit SHA for version tracking.
To ensure compatibility with older repositories, LeanAgent can search through a repository's commit history to find the most recent commit that uses a supported Lean version. This allows the system to work with repositories that might have updated to newer, unsupported Lean versions.
The system maintains a list of known repositories that are either already processed or unsuitable for other reasons. This list includes repositories focused on functional programming rather than mathematics, repositories with trace problems, or those with too few theorems to be useful for training.
Once a compatible repository is identified, LeanAgent begins the data extraction process:
Repository Tracing: The system uses LeanDojo's trace function to extract theorem definitions, proofs, and premises from the repository. This involves:
Theorem Processing: Each theorem is stored with its full name, file path, source positions, URL, commit reference, and theorem statement
Premise Collection: The system extracts premises (theorems, lemmas, definitions) from the repository, recording their:
Tracing File Dependencies: LeanAgent builds a topological graph of file dependencies to ensure premises are properly ordered during dataset generation. This ordering is crucial for theorem proving, as premises can only be used after they've been defined.
Then, LeanAgent organizes the traced data into a structured dataset:
Proof Export: For each theorem in the dataset, LeanAgent exports:
Premise Export: LeanAgent exports premise definitions in a topologically sorted order to maintain dependency relationships. Each premise file contains:
Metadata Generation: Additional metadata is recorded for each dataset:
Once generated, the dataset is integrated into LeanAgent's dynamic database (described in more detail in the next section). To do this, a Repository object is created with the extracted data and the repository is added to the dynamic database.
At the core of LeanAgent is a custom dynamic database that tracks and manages all mathematical knowledge across repositories. This database stores:
The database provides functionality to add new repositories, update existing ones, and generate merged datasets from multiple repositories. It uses a JSON-based storage format that can be persisted between runs. Specifically, each class implements to_dict and from_dict methods for conversion. Special handling is provided for non-JSON-serializable types like datetime objects, and the serialization format preserves the full structure of theorems, tactics, and premises. This enables the database to be persisted between runs and distributed across computing resources when necessary.
When generating a dataset from the database, the database can deduplicate theorems and premises when merging repositories, prioritizing the most recently added versions.
The database implementation consists of several interrelated data structures:
sorry that haven't been proven yet, maintaining lists of Premise Files, and providing helper methods for accessing and manipulating theorems and premises.LeanAgent implements a sophisticated curriculum learning strategy based on theorem complexity. The system calculates the complexity of each theorem using an exponential function of the number of proof steps: $e^S$ where $S$ is the number of proof steps. This exponential scaling accounts for the combinatorial explosion of possible proof paths as proofs get longer.
Theorems with no proofs (sorry theorems) are assigned infinite complexity. The system computes the 33rd and 67th percentiles of complexity across all theorems to establish thresholds for categorizing theorems as Easy, Medium, or Hard.
Repositories are then sorted based on the number of easy theorems they contain. This sorting forms the basis of the curriculum, with LeanAgent starting on repositories with the highest number of easy theorems and gradually progressing to more challenging ones.
For theorems without existing proofs, the system distributes them evenly across the three difficulty categories to maintain balance in the curriculum. This approach ensures that LeanAgent builds foundational knowledge before attempting more complex mathematical domains.
LeanAgent employs a simple but effective progressive training approach to avoid catastrophic forgetting. Starting with a pre-trained retriever (based on ByT5), the system trains on each new repository dataset for one additional epoch.
This limited exposure to new data helps prevent overfitting while allowing the model to incorporate essential new information. The retriever is continuously updated during training, and embeddings for all premises are precomputed after each training session to ensure proper evaluation.
The system saves checkpoints based on validation performance, specifically the recall at 10 (R@10) metric, which measures how often the correct premise is among the top 10 retrieved premises. LeanAgent evaluates both plasticity (ability to learn new information) and stability (retention of previous knowledge) by measuring:
This progressive training process is repeated for each repository in the curriculum, allowing LeanAgent to incrementally build its mathematical knowledge while preserving what it has already learned.
sorry Theorem ProvingLeanAgent identifies theorems marked with sorry in the Lean files and attempts to generate formal proofs for them using a best-first tree search approach. For each sorry theorem:
The system processes the premise corpus to build a knowledge base of available facts and definitions
It constructs a directed dependency graph representing file imports to determine which premises are accessible
For each proof state, LeanAgent:
The search continues until a proof is found, all possibilities are exhausted, or a time limit (10 minutes) is reached. Successful proofs are added to the dynamic database, allowing LeanAgent to learn from them in future progressive training.
The system processes theorems in batches (typically 12 theorems per batch) for efficiency and maintains a record of encountered theorems to avoid redundant proving attempts. It also saves progress periodically to ensure resilience against interruptions.
When LeanAgent successfully proves a sorry theorem, it can integrate the generated proof into the original Lean files and create pull requests to propose these changes to repository maintainers. This process involves:
sorry keywords with the generated proof textWhen submitting proven theorems back to repositories, LeanAgent uses a consistent formatting approach with standardized branch names, commit messages, and PR templates that identify the contributions as coming from LeanAgent.
This contribution mechanism helps advance the development of mathematical repositories while also generating additional training data for future research.
LeanAgent is implemented with several key configurations that guide its operation:
The Fisher Information Matrix (FIM) is a key component of Elastic Weight Consolidation (EWC), a technique used in our ablation studies. Although this resulted in suboptimal lifelong learning performance, we describe how to generate and use the Fisher Information Matrix to help replicate our results.
Note: Due to the inherent stochasticity of LLMs and the best-first tree search algorithm used in LeanAgent, your results may vary from those reported in the paper. Differences in hardware, random seeds, and minor implementation details can all affect theorem proving performance.
If you find our work useful, please consider citing our paper:
@inproceedings{kumarappan2025leanagent,
title={{LeanAgent}: Lifelong Learning for Formal Theorem Proving},
author={Kumarappan, Adarsh and Tiwari, Mo and Song, Peiyang and George, Robert Joseph and Xiao, Chaowei and Anandkumar, Anima},
booktitle={International Conference on Learning Representations (ICLR)},
year={2025}
}
Adarsh Kumarappan and Mo Tiwari contributed equally to this work.