LLM-Assisted Formal Verification: Engineering Practices and Lessons from Fermat's Last Theorem

    This article examines why formal verification has suddenly become a hot topic in the LLM era, using the recent formalization of Fermat's Last Theorem as a case study. It explains what formal verification is, how proof assistants check every step, and why a single flawed lemma can invalidate an entire proof chain. It then breaks down the technical path of LLM-assisted formalization: statement formalization, lemma decomposition, tactic generation with error-feedback repair, and lemma retrieval with context management, along with a sample model-driven pipeline. Finally, it covers the performance, cost, and quality tradeoffs engineering teams face (throughput versus latency, building a realistic cost model, and quality-first mode selection), how to run such projects in practice, how to evaluate them, and why "30-hour" milestones should be read with the accumulated libraries and human supervision in mind. The core takeaway: a proof that has not been machine-checked is only text that looks like a proof.

    LLM-Assisted Formal Verification: Engineering Practices and Lessons from Fermat’s Last Theorem

    1. Introduction: Why Formal Verification Suddenly Matters

    Recent reports claim that a new generation of large models made significant progress on the formalization of mathematical proofs, completing the formalization work related to Fermat’s Last Theorem in a matter of tens of hours. The story attracted wide attention not only because Fermat’s Last Theorem is one of the most famous problems in the history of mathematics, but because it touches a core question: can the output of a large language model actually reach a level of trustworthiness comparable to mathematics itself?

    In ordinary code generation, an occasional hallucination can be caught by unit tests and code review. In formal mathematics, a single wrong lemma or one overlooked edge case can invalidate the entire proof chain. “The model completed the formal verification” is therefore fundamentally a challenge to the boundary of trustworthy AI reasoning.

    This article is not about any specific product. Starting from the technical fundamentals, it systematically unpacks what formal verification is, what role large models play in it, how to implement it in engineering practice, and how to reason soberly about the tradeoff between model performance and cost.

    2. Formal Verification: From Proofs Humans Read to Proofs Machines Check

    2.1 Core Concepts

    Formal verification is the process of expressing mathematical propositions and proofs in a rigorous logical system, and having a proof assistant check their logical validity line by line. Common proof assistants include dependent type systems based on type theory and interactive theorem provers based on set theory.

    A formal proof typically consists of:

    • Axioms and definitions: formalizing the mathematical objects involved in the proposition (elliptic curves, modular forms, Galois representations) into objects the system can understand;
    • A chain of lemmas: decomposing a large theorem into several independently verifiable lemmas;
    • Tactic scripts: guiding the prover’s reasoning through tactics such as induction, rewriting, and proof by contradiction;
    • Machine checking: the kernel accepts only proof terms that obey the logical rules; any step that “looks reasonable but does not hold logically” is rejected.

    2.2 The Value of Formal Verification

    1. Absolute trustworthiness: as long as the kernel is correct, the correctness of the proof is exactly what the check result says, unaffected by human reading fatigue or intuitive bias.
    2. Reusable assets: a formalized theorem library can be referenced by later work, compounding knowledge over time.
    3. Exposing hidden gaps: formalization frequently surfaces details that the original paper silently skipped, which in turn pushes mathematical exposition toward greater rigor.

    2.3 Why Fermat’s Last Theorem Is the Litmus Test

    The complete proof of Fermat’s Last Theorem relies on a vast body of algebraic geometry and number theory (the modularity theorem and results related to the Taniyama–Shimura conjecture). Its formalization involves:

    • building a large amount of foundational library code (rings, fields, ideals, cohomology, and so on);
    • combining lemmas across domains;
    • maintaining an extremely long proof chain.

    Whether such formalization can be completed efficiently therefore directly tests a model’s long-range reasoning, context management, and deep understanding of mathematical structure.

    3. Technical Paths for LLM-Assisted Formalization

    3.1 The “Translator” Paradigm for Interactive Proofs

    The mainstream approach in the industry today is not to have the model emit a complete proof in one shot, but to use a “human–machine collaboration, step-by-step” mode:

    1. Loop:
    2. 1. Select the next proof goal from the theorem library (or let the model suggest one)
    3. 2. The model reads the current proof state (goal, existing hypotheses, related lemmas)
    4. 3. The model generates candidate proof steps / lemma statements / tactic scripts
    5. 4. The proof assistant checks: accept if it passes; if it fails, feed the error message back to the model
    6. 5. The model revises based on the feedback until the goal is closed

    The benefit of this paradigm is that the model is only responsible for “proposing hypotheses and strategies,” while correctness is guaranteed by the proof assistant. This constrains the uncertainty of a generative model inside a verifiable framework.

    3.2 Breakdown of Key Capabilities

    (1) Statement Formalization

    Translating a natural-language mathematical statement into the language of a proof assistant is the most error-prone step. The model has to understand quantifiers, implicit assumptions, and conventions. In engineering practice this usually requires:

    • human review by a mathematician after the statement is generated;
    • bidirectional “statement–proof” validation: first prove a simple corollary to check whether the statement matches intuition.

    (2) Lemma Decomposition

    A large theorem cannot be swallowed in one bite. Decomposing it sensibly into independent lemmas, each with a clear input/output contract, is the key to maintaining a long proof. The model can automatically suggest a decomposition based on existing mathematical literature, but a human must confirm equivalence.

    (3) Tactic Generation and Error-Feedback Repair

    Error messages from the proof assistant (for example, “unable to unify types” or “rewrite failed”) are an important signal for model self-correction. In practice, the error message is sent back to the model together with relevant library documentation, and the loop converges over multiple iterations.

    (4) Library Retrieval and Context Management

    In a formalization project, an existing lemma is often more reliable than a newly written one. The model needs the ability to retrieve relevant existing results — for instance, finding reusable theorems by semantic similarity and then attempting to apply them.

    3.3 An Illustrative Workflow

    1. # Pseudocode: a model-driven formal verification pipeline
    2. def formalize(theorem_statement):
    3. goal = parse(theorem_statement) # Parse into an internal goal
    4. context = retrieve_related_lemmas(goal) # Retrieve existing lemmas
    5. while not goal.is_closed():
    6. suggestion = model.propose(goal, context)
    7. result = proof_assistant.check(suggestion)
    8. if result.ok:
    9. goal.apply(suggestion)
    10. else:
    11. context.add_error_feedback(result.message)
    12. return goal.export_certificate() # Export a machine-checkable proof certificate

    It is worth emphasizing that the final deliverable is a proof certificate, which can be independently rechecked and does not depend on trusting the model itself.

    4. Performance, Cost, and Engineering Tradeoffs

    The original reports mention that the new-generation model generates faster and costs less, with an optional “fast mode” for further speedup (at roughly double the price). Phenomena like this reflect a general engineering tradeoff that teams should analyze rationally.

    4.1 Throughput vs. Latency: Which Matters More?

    • Batch formalization tasks (such as migrating an entire math library to a new formal language) care more about throughput, suit high-concurrency parallel calls, and benefit noticeably from fast mode;
    • Interactive proving (a human advancing step by step in the loop) cares more about single-response latency and quality; blindly speeding up can raise the error rate and actually lengthen the number of convergence rounds.

    4.2 Building a Cost Model

    For long-range tasks, cost is not simply “unit price × token count.” A reasonable estimate should include:

    1. Input cost: in long-context scenarios, the proof state and library documentation are fed to the model repeatedly, so input tokens are often the largest cost item;
    2. Output cost: proof scripts are verbose, so output tokens are also substantial;
    3. Retry cost from failures: every retry after a failed tactic repeats a large amount of context as input;
    4. Caching gains: enabling prefix caching for the stable portion of the context can significantly reduce repeated input cost.

    A practical cost formula:

    1. Total cost ≈ Σ (input tokens per call × input unit price + output tokens × output unit price)
    2. + extra calls caused by failed retries

    Teams should measure the “average cost per closed lemma” for their own tasks rather than looking only at unit price.

    4.3 Quality First: What Makes Formalization Special

    Formal verification demands extremely high correctness, so optimizing “cost per token” must yield to optimizing “cost per correct lemma.” If fast mode raises the error rate and increases retries, total cost may go up rather than down. Recommended practices:

    • run A/B evaluations on a representative set of lemmas first, comparing pass rate and average number of rounds across modes;
    • establish a “difficulty tiering” strategy: fast mode for simple lemmas, standard mode for complex ones;
    • record the reason for every failure and continuously improve prompts and context organization.

    5. Implementation: Getting Started in Your Own Team

    5.1 Technology Selection and Infrastructure

    • Proof assistant: choose a type-theory-based or set-theory-based tool according to the team’s background, with emphasis on how well the ecosystem’s libraries cover your needs;
    • Model access: manage model calls through a unified API gateway, with support for multi-model routing and fallback;
    • Storage and collaboration: use object storage for proof certificates and intermediate states, and a code repository to manage formalization projects;
    • Logging and monitoring: record a summary of the input, the output, the check result, and the elapsed time for every model call, for later analysis.

    5.2 Process Management

    1. Establish a trust boundary: model output is always only a candidate; the proof assistant’s check result is authoritative;
    2. Version management: when the formalization library is upgraded, use regression tests to ensure existing proofs are not broken;
    3. Human review checkpoints: statement translation and equivalence arguments for key lemmas must be reviewed by a human;
    4. Documentation: for each lemma, note the source, the location in the original paper, and the tradeoffs made during formalization.

    5.3 Evaluation System

    Maintain a layered evaluation set:

    • Unit level: pass rate of a single tactic or small lemma;
    • Integration level: end-to-end closure rate of complete theorems (classical algebraic identities, elementary number theory results);
    • Regression level: whether already-closed proofs still reproduce after a model or library update.

    Metrics include first-pass rate, average number of iterations, cost per lemma, and total elapsed time. This system objectively assesses the real gains of different model configurations.

    6. Reading “30-Hour” Milestones Rationally

    Even if a model really can complete formalization at the level of Fermat’s Last Theorem in tens of hours, several preconditions deserve attention:

    1. Accumulated infrastructure and libraries: a formalization math library built up over decades is a hidden foundation and is not counted in the “model runtime”;
    2. Human supervision: experts typically set the route and review statements during the process;
    3. Correctness is independent of elapsed time: the ultimate value lies in the machine-checkable certificate, not in speed itself.

    So for companies and technical teams, the more practical lesson is this: large models are turning formal methods from “a manual craft practiced by a few experts” into “an engineerable pipeline,” but the design, supervision, and evaluation of that pipeline still demand rigorous engineering capability.

    7. Conclusion

    Progress in LLM-assisted formal verification marks a shift in AI-generated content from “usable” to “provable.” For developers, the key to converting this wave of technology into reliable engineering output is to master the collaboration paradigm between proof assistants and models, to establish a trust boundary anchored on machine checking, and to weigh speed against cost in a data-driven way. No matter how fast future models run, the core tenet of formal verification will not change: a proof that has not been machine-checked is only a piece of text that looks like a proof.