Manuscript Offprint
arXiv:2610.36396Automatic Certified Differentiation in Lean
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original.
Ramy Shahin
Qualgebra
Abstract. Automatic differentiation (the automatic computation of numerical function derivatives) has many applications, especially in scientific computing and machine learning. Several approaches to automate the calculation of derivatives have been presented. Common challenges facing those approaches include (1) having to define derivative rules for different classes of functions, (2) having to manipulate program symbols to understand the semantics of the function being differentiated, and construct the derivative function, and (3), more importantly, ensuring that the calculated derivative is correct.
In this paper, we present an approach for automatic certified differentiation using the Lean proof assistant. By certified, we mean a correctness certificate is computed together with the derivative function and a domain on which the derivative is guaranteed to be valid. Our approach leverages existing derivative theorems included in the Mathlib Lean library instead of having to define our own rules. We also utilize Lean metaprogramming to manipulate the symbolic structure of the input function, and to construct the derivative function. The correctness certificate is computed step-wise as we apply Mathlib theorems. To make the search efficient, we index the derivative theorems by the function they differentiate. We evaluate our approach on 500 randomly generated functions: with the index, all of them are differentiated, with a median time of 0.18 s per function, 8.6 times faster than without the index.
Keywords: automatic differentiation, certified programming, metaprogramming, Lean
1 Introduction
Given a mathematical function, computing its derivative has many practical applications. This includes applications in scientific computing, machine learning, simulation, graphics, and computational finance. The simplest approach is for a programmer to manually analyze the input function and write a program implementing the derivative function, following the differentiation rules in calculus textbooks. However, since those rules have been well studied and understood for centuries, automating this process has been an active area of research since the 1960s [28].
Approaches to computing derivatives automatically are usually classified into numerical, algorithmic, and symbolic differentiation [26,2]. Numerical differentiation treats f as a black box, and approximates its derivative at a given value
R. Shahin
(a) Syntax tree of .
deriv-comp
(b) Proof tree of the derivative of .
Fig.1: Syntax tree of the body of , and proof derivation of its derivative.
x by the rate of change of f between x and neighboring values. Algorithmic differentiation evaluates the program computing f at a given value x, and propagates derivative values through each elementary operation using the chain rule. It computes the exact value of the derivative at x, but not an expression for the derivative function.
On the other hand, symbolic differentiation is a white-box approach. It works directly on the syntactic expression structure of the function body without having to compute any function values. This is based on the fact that derivative rules are compositional. For example, the chain rule is used to compute the derivative of a composition of two functions (e.g., ). Following the syntactic tree structure of the body of function , the derivative is composed using primitive derivative theorems.
For example, to differentiate the function , we follow its syntactic structure (Fig. 1a) top-down. The root of the syntax tree is the unary function log, and its only child is the binary function (operator) /. This is a composition of two functions, and its derivative is computed using the chain rule. The two premises of the chain rule in this case are (1) the derivative of the outer function log applied to the inner function , and (2) the derivative of the inner function .
Using the logarithm derivative rule, the derivative of log, evaluated at 3/x, is . This rule only applies where the argument of log is non-zero, i.e., for , because the logarithm is not differentiable at zero. In Mathlib, division and the logarithm are total functions, with and , so side conditions like this one are about differentiability rather than definedness; since , the condition holds exactly when .
Similarly, using the quotient rule, the derivative of is . The quotient rule requires the denominator to be non-zero, so again the derivative is restricted to . The derivative of now is the product of the two lower-level derivatives, according to the chain rule. This evaluates to .
This approach is completely based on formally proved theorems. As a result, a correctness proof is (implicitly) constructed compositionally alongside the derivative function itself. Fig. 1b is the derivation tree of this proof. This tree captures the exact same steps used to compute the derivative. If this proof is made explicit, and returned by the automatic differentiation system together with the derivative function, then the derivative computation is certified, i.e., it computes a value, together with a certificate proving the correctness of that value.
To be able to build such a system, three ingredients are needed:
-
A formal foundation defining the notion of derivatives down to basic mathematical and logical principles, together with differentiation rules for different forms of mathematical expressions.
-
A way to validate the correctness of proofs built on top of that formal foundation.
-
The ability to manipulate the symbolic structure of mathematical functions, and to apply the right rule to the right kind of expression.
The Lean [19] interactive theorem prover together with its Mathlib [5] library provides all three ingredients. (1) Mathlib is a large, community-maintained library of formalized mathematics, including analysis and calculus; its derivative theorems form exactly the required formal foundation. (2) The Lean kernel, which implements a variant of the Calculus of Inductive Constructions (CIC) [3], only admits well-typed terms, so it acts as a proof checker for Mathlib and for proofs built on top of it. (3) Lean supports metaprogramming: programs that manipulate other programs, such as symbolic differentiation, and that extend the syntax of Lean with new commands.
In this paper we present an automatic certified differentiation framework, leveraging the Lean theorem prover, Mathlib, and Lean metaprogramming. The correctness certificate returned together with the derivative function guarantees that the derivative is correct on the computed domain. This is particularly relevant when used in developing safety-critical or mission-critical software systems. Our contributions are:
– An algorithm for automatic certified differentiation that composes existing Mathlib derivative theorems following the structure of the input function, and returns the derivative, a domain on which it is valid, and a proof of its correctness, checked by the Lean kernel (Sec. 3).
– An implementation of the algorithm as a Lean command, including an index of derivative theorems by the function they differentiate, which makes the search efficient (Sec. 4).
– An evaluation on 500 randomly generated functions, all of which are differentiated, with a median time of 0.18s per function, 8.6 times faster than without the index (Sec. 5).
In particular, after covering some background on Mathlib derivative functions (Sec. 2), we present the automatic certified differentiation algorithm in Sec. 3.
R. Shahin
def HasDerivAt { k : Type u} [NontriviallyNormedField k] {F : Type v} [AddCommGroup F] [Module k F] [TopologicalSpace F] [ContinuousSMul k F] (f : k → F) (f' : F) (x : k): Prop (a) Definition of HasDerivAt.
theorem HasDerivAt.comp { k : Type u} [NontriviallyNormedField k] (x : k) { k' : Type u_1} [NontriviallyNormedField k'] [NormedAlgebra k k'] {h : k → k'} {h₂ : k' → k'} {h' h₂' : k'} (hh₂ : HasDerivAt h₂ h₂' (h x)) (hh : HasDerivAt h h' x): HasDerivAt (h₂ ○ h) (h₂' * h') x (c) Chain rule.
theorem HasDerivAt.log {f : R → R} {x f' : R} (hf : HasDerivAt f f' x) (hx : ¬ (f x = 0)) : HasDerivAt (fun (y : R) => Real.log (f y)) (f' / f x) x
(b) Derivative of log composed with f.
Fig. 2: Documentation of some derivative definitions and theorems from Mathlib.
We then cover the design of the library and how it integrates with Lean in Sec. 4. Evaluation results are then presented in Sec. 5, and discussed in Sec. 6. We then compare our approach to related work in Sec. 7, and finally conclude and discuss some future directions in Sec. 8. The library together with the evaluation driver and scripts is available in open source .
2.1 Differentiation in Mathlib
Mathlib currently has two formalizations of derivatives: one-dimensional derivatives , and Fréchet derivatives . The framework presented in this paper only uses one-dimensional derivatives, restricting our scope to automatic differentiation of functions of a single variable. Fig. 2 includes the documentation of the Mathlib definitions and theorems used in the examples in this paper.
The relation between a function and its derivative at a given point is defined by the HasDerivAt predicate (Fig. 2a). The definition is not specific to functions on real numbers. Instead, the domain of can be any nontrivially normed field . Its codomain can be any additive commutative group . Scalar multiplication between and is also assumed to be jointly continuous in both of its arguments, and should have a topology defined on it. All those constraints on and are required by the underlying formalization of derivatives,
https://github.com/qualgebra/autodiff/tree/DATAMOD2026
Mathlib.Analysis.Calculus.Deriv
Mathlib.Analysis.Calculus.FDeriv and are encoded as type class instances. HasDerivAt is a ternary predicate, relating a function f to its derivative f' at point x.
Derivative rules for different forms of mathematical expressions are defined in Mathlib as theorems in terms of HasDerivAt. For example, the logarithm derivative rule theorem is stated in Fig. 2b. The theorem combines the logarithm derivative together with the chain rule, assuming that log is applied to a function f of x, not x itself. The straightforward derivative of the logarithm of x is an instance of this theorem, where f becomes the identity function. Unlike the generic definition of HasDerivAt, this theorem is specific to , which satisfies all the type class constraints of HasDerivAt.
Preconditions of the derivative rule are also included as premises in the theorem. First, hf is a premise indicating that f' is the derivative of f. Then hx is another premise restricting the argument of log, f(x) in this case, to non-zero values. Such constraints on the variable in which the derivative is computed are essential for proof correctness. For the automatic differentiation to generate a correctness certificate, it has to provide those input constraints as well.
Another example of a derivative rule theorem in Mathlib is the chain rule, or the derivative of function composition (Fig. 2c). The structure of the theorem is similar to that of the logarithm derivative theorem. This one keeps the domain and codomain types generic though, with the codomain of h being the domain of . Proofs of all of those derivative theorems are included in Mathlib, and are checked by the Lean kernel when Mathlib is compiled; proofs built on top of them are checked by the kernel as well, so they cannot be used to construct higher-level proofs that are unsound.
2.2 Lean Metaprogramming
Lean includes a powerful set of metaprogramming constructs and libraries that enable users to write proof tactics, syntax extensions, and environment extensions, all in the Lean language itself. Proof tactics are commonly used to decompose proof goals into simpler sub-goals, and prove each of them individually. The higher-level proof is automatically composed of the smaller proofs as a part of this process. Lean comes with an extensive set of standard general-purpose tactics. Users can still write their own custom tactics using metaprogramming .
When trying to prove a theorem in Lean, each proof goal becomes the type of a Lean metavariable. Writing a proof is the process of assigning syntactic terms of the appropriate types to those metavariables. The Lean kernel does the type checking, admitting the proof only if all metavariables are assigned terms of the right types. A tactic typically tries to automate much of the process of finding sound metavariable assignments.
A metavariable can also be used to encode missing information; such metavariables are sometimes called holes in the proof. When Lean elaborates a syntactic term into a kernel expression, its unification algorithm can find type-sound assignments for those holes. For example, the goal of this project is to find the derivative of a function at point , a correctness proof and a domain predicate. The correctness theorem has to be of the form HasDerivAt .
R. Shahin
Algorithm 1: Derivative Search Algorithm
1 procedure findDeriv Input: history, domain Output: domain
2 goal ← getCurrentGoal
3 if goal ∈ history then 4 | fail 5 end
6 if the function in goal does not depend on x then 7 | apply the constant-function theorem to goal 8 | return domain
9 end
10 for do 11 | if t applies to goal then 12 | sg ← getSubgoals 13 | for do 14 | if s has no metavariables then 15 | domain ← domain ∪ {s} 16 | else 17 | domain ← findDeriv (history ∪ {goal}) domain 18 | end 19 | end 20 | return domain 21 | end 22 end 23 fail 24 end procedure
However, is an unknown, so it cannot be explicitly included in the theorem until it is found. As discussed in Sec. 3 and Sec. 4, a metavariable is used as a placeholder for , and the Lean unification algorithm fills it in.
3 Automatic Certified Differentiation Algorithm
Given a function (where types and have instances of the type classes discussed in Sec. 2.1), the goal of the automatic certified differentiation algorithm is to find three artifacts:
-
The derivative .
-
A predicate specifying a domain on which is guaranteed to be the derivative.
-
A proof of the derivative correctness theorem
Finding all three artifacts is broken down into two stages. The first stage finds the derivative , collecting the conjuncts of the domain constraint and an incomplete proof along the way. The second stage completes the proof by filling in its missing pieces with the corresponding domain constraint conjuncts.
3.1 Derivative Search
The derivative search algorithm initially collects all theorems of the form
(HasDerivAt ___)
in the current environment. This set of theorems is referred to as the theorem database (theoremDB). The proof goal is then set to , where and are Lean metavariables for the domain predicate and the derivative.
Algorithm 1 is then used to find a potentially incomplete proof of this goal, while finding an assignment for the derivative metavariable ?d. The algorithm takes two arguments: history, which is the set of previously seen goals on a single branch of a recursion tree, and domain, which is the set of domain constraints collected so far. When the algorithm starts, the empty set is passed for both arguments.
The algorithm starts by focusing on the current goal (line 2). If it is included in the history, the call fails (lines 3–5). This is a safeguard against falling into infinite recursion due to sequences of theorem applications that loop back to a previously visited step in the proof. If the function being differentiated does not depend on x, it is constant, and the theorem stating that the derivative of a constant function is zero is applied directly, with no domain constraints (lines 6–9). Otherwise, the candidate theorems for the goal are tried one by one (lines 10–22); with the theorem index (Sec. 4.2), these are only the theorems that can match the outermost function of the goal. When a theorem is applicable to the goal (i.e., the unification algorithm finds a value assignment that matches both the theorem and the goal), the theorem is applied, and any generated subgoals are collected (lines 11–12).
For each subgoal s, if s has no metavariables, it is a side condition of the theorem, such as , and it is added to the domain set (lines 14–15). The subgoal s is left as a hole in the global proof, to be filled in later. Otherwise, s is another HasDerivAt goal, whose derivative is still to be found, and findDeriv is called recursively on s, adding goal to the history of goals (line 17). If all subgoals are solved, the algorithm returns the collected domain (line 20). If a recursive call fails, the application of the theorem is undone, and the next candidate theorem is tried. If no candidate theorem leads to a solution, the call fails (line 23).
The goal state is assumed to be global, and updated whenever a theorem is applied successfully to a goal. When the algorithm succeeds, the original goal G is assigned a proof. This proof is incomplete, because it contains holes for the domain constraints. Metavariable ?d is also instantiated with a function satisfying the theorem G.
R. Shahin

Fig. 3: Tool architecture.
structure CDeriv {α β: Type} [NontriviallyNormedField α] [AddCommGroup β] [Module α β] [TopologicalSpace β] [ContinuousSMul α β] (f: α → β) where f': α → β domain: α → Prop proof: ∀ (x:α), domain x → HasDerivAt f (f' x) x
Fig. 4: The CDeriv structure.
3.2 Domain Completion
In the second stage, the holes in the proof corresponding to domain constraints are filled in. First, a domain predicate is constructed as a conjunction of the domain constraints returned by findDeriv, and assigned to the metavariable ?a. The proof G has a hypothesis of type ?a x, i.e., a proof of that conjunction. For each of the holes in the proof, the conjunct corresponding to its type is extracted from this hypothesis, using the left and right eliminators of conjunctions, and assigned to the hole.
4 Implementation
4.1 Design Decisions
Fig. 3 is a high-level architecture of the tool implementation. Differentiation inspects the syntactic structure of the function being differentiated, and it can fail, e.g., if the function is not differentiable, or if the packages containing the required theorems have not been imported. A Lean function cannot inspect the syntax of its argument, so we implement differentiation as a metaprogram: a Lean syntactic extension command. To differentiate a function f, the user issues the following command:
let result := differentiate f
The result is a new definition result of type CDeriv (Fig. 4), a structure encapsulating the results of automatically differentiating a function f of type , where and satisfy the type class constraints of HasDerivAt (Sec. 2). Its first field is the derivative , and its second field, domain, is a predicate on the function parameter type, defining a domain on which the derivative is valid. The third field, proof, has the derivative correctness theorem as its type; its value is a proof that is the derivative of f at every point of domain.
The differentiate command unfolds the body of function f, introduces its parameter, and runs the difftac tactic, which implements Alg. 1. The domain constraints found by the tactic are left as holes in the proof and recorded in a Lean environment extension, through which they are communicated back to the command (outside the TacticM monad). The command folds them into one conjunctive domain predicate, fills in each hole with the corresponding conjunct
(Sec. 3), and adds the resulting CDeriv definition to the environment, where it is checked by the Lean kernel.
When the differentiate command is first used, it searches the current Lean environment for theorems whose conclusion is a HasDerivAt statement (e.g., HasDerivAt.log in Fig. 2b and HasDerivAt.comp in Fig. 2c). Those theorems are stored in theoremDB, another Lean environment extension, which serves as a derivative theorem database during derivative search. It is assumed that the user will import the Mathlib packages relevant to the functions to be differentiated. In addition to the Mathlib theorems, the database contains two theorems proved in our library from Mathlib theorems: a chain-rule form of the derivative of tan, which Mathlib only states for tan itself, and a variant of HasDerivAt.log with its premises reordered. As a heuristic, the theorems are ordered in ascending order of their number of arguments. To decide whether a theorem applies to a goal, the search uses Lean's unifier, which checks definitional (not just syntactic) equality; the same check is used to detect goals that are already in the history.
4.2 Theorem Indexing
A naive search tries every theorem in the database on every goal, in order, until one applies. Most of those attempts fail, and failures are expensive: to establish that a theorem does not apply, the unifier may unfold definitions deeply, e.g., HasDerivAt down to its underlying filter-based definition, or real-number functions such as Real.cos down to their definitions in terms of complex numbers. We therefore index the database in two ways. First, we exclude catch-all theorems, whose conclusion is HasDerivAt f f' x for an arbitrary function f (e.g., HasStrictDerivAt.hasDerivAt, which derives HasDerivAt from a stronger notion of differentiability). Such theorems unify with every goal, but their premises are not derivative goals that the search can discharge, so applying them only leads to failures deeper in the search. Second, we index the remaining theorems by the head symbol of the function they differentiate, e.g., Real.sin for HasDerivAt.sin, or division for HasDerivAt.div. For a goal whose function has head symbol h, only the theorems indexed by h are tried, together with those whose head symbol is not fixed (e.g., the derivative of a constant function), preserving the order of the database. Subgoals that are not HasDerivAt statements, e.g., about other notions of differentiability, cannot be solved by the search, and fail immediately. Sec. 5 compares the performance of derivative search with and without the index.
4.3 Example
Assume we want to differentiate the function of Sec. 1, using the command:
noncomputable def f := λ x:ℝ → log (3 / x)
let d := differentiate f
R. Shahin
fun (x: R) (a: ?a x) => HasDerivAt.log' ?h₁ (HasDerivAt.fun_div (hasDerivAt_const x 3) (hasDerivAt_id' x) ?h₂)
(a) Incomplete proof generated by the tactic, with holes for the domain constraints.
fun (x: R) (a: x ≠ 0 ∧ 3 / x ≠ 0) => HasDerivAt.log' a.right (HasDerivAt.fun_div (hasDerivAt_const x 3) (hasDerivAt_id' x) a.left)
(b) Complete proof, after the holes are filled in.
Fig. 5: Incomplete and complete correctness proofs of the derivative of .
This defines a CDeriv structure d, whose derivative and domain are
fun x => (0 * x - 3 * 1) / x ^ 2 / (3 / x) fun x => x ≠ 0 ∧ 3 / x ≠ 0
The derivative is not simplified; on its domain, it is equal to . The difftac tactic uses four derivative theorems:
-
HasDerivAt.log', the chain rule with log as the outer function. Its domain premise states that the argument of log has to be non-zero, i.e., .
-
HasDerivAt.fun_div, the quotient rule, to differentiate 3/x. Its domain premise states that the denominator has to be non-zero, i.e., .
-
hasDerivAt_const and hasDerivAt_id', to differentiate the numerator 3 and the denominator x. These theorems have no domain premises.
Fig. 5a is the proof generated by the tactic. The type of the hypothesis a is the domain predicate, still the metavariable ?a applied to x. The hole ?h₁ is the domain premise of HasDerivAt.log', and should be a proof of . The hole ?h₂ is the domain premise of HasDerivAt.fun_div, and should be a proof of .
The command collects the types of the holes, and folds them into the conjunctive domain predicate , which is assigned to ?a. Each hole is then assigned the conjunct of its type, extracted from a. Fig. 5b is the complete proof for the derivative of function f: ?h₁ is replaced by a.right, a proof of , and ?h₂ by a.left, a proof of .
5 Evaluation
Beyond the simple functions used during development, we evaluate the tool on randomly generated functions that exercise many different derivative rules.
Function bodies are expression trees over integer literals between -100 and 100, the variable raised to a natural number exponent between 1 and 10, the four arithmetic operators, trigonometric functions (sin, cos, and tan), and natural logarithms. Each inner node of an expression tree is one of those constructs, chosen with equal probability, and each leaf is either a literal or the variable. Function bodies of expression tree depth up to 7 are generated from a fixed random seed. We exclude functions that do not mention the variable, since constant functions are trivially differentiable, as well as functions consisting of a
Table 1: Time per differentiation in milliseconds, with and without the theorem index, over the 488 test cases that complete in both configurations, and the speedup due to indexing (time without the index divided by time with the index, per test case). The domain is the one computed by the tool, which is the same in both configurations.
| domain | n | time with index (ms) | time without index (ms) | speedup | |||||
|---|---|---|---|---|---|---|---|---|---|
| median | p95 | max | median | p95 | max | median | range | ||
| universal | 66 | 67 | 216 | 323 | 439 | 1486 | 2401 | 5.9× | 1.6–8.9× |
| restricted | 422 | 202 | 417 | 1921 | 2871 | 7221 | 12275 | 13.8× | 1.2–71× |
| all | 488 | 181 | 410 | 1921 | 2423 | 7045 | 12275 | 8.6× | 1.2–71× |
single literal or power of the variable, and duplicates, resulting in 500 distinct test functions of 4 to 67 nodes (median 19). Because only a few Mathlib types implement instances of the type classes required by the HasDerivAt theorems, we limit our test set to functions. Division, log, and tan were included particularly to test domain constraints.
The goals of the evaluation experiments are:
-
To ensure that the framework works as expected on a diverse set of mathematical functions.
-
To identify any limitations of the approach and the implementation.
-
To measure the computational time of the automatic differentiation implementation, both on functions differentiable on the entire set of real numbers, and on functions whose differentiable domain is restricted.
-
To measure the performance improvement due to theorem indexing (Sec. 4.2), by running the same test cases with and without the index.
This evaluation was performed on an 8-core AMD Ryzen 7 7730U processor, with 40 GB RAM, running Linux kernel version 7.0.0-38-generic. We used Lean 4.33.1 with Mathlib v4.33.1. Each test case was run in two configurations: with the theorem index (Sec. 4.2), and without it, i.e., trying all theorems of the database in order. The theorem database is built once before each test case. For each configuration, the differentiate command was run five times, where we excluded the first run and averaged the running time of the other four runs. We used the default Lean heartbeat limit (200,000).
With the index, all 500 test cases ran to completion, generating the derivative of the input function, a domain on which the derivative is valid, and a proof that the generated derivative is correct, checked by the Lean kernel. Each of these proofs depends only on Lean's standard axioms (propext, Classical.choice, and Quot.sound); in particular, none of them uses sorry. Without the index, 12 test cases did not complete because the Lean heartbeat limit was reached; with the index, the same functions are differentiated in at most 0.6 s. For the 488 test cases that complete in both configurations, the computed domains are identical, and since both derivatives are certified on the same domain, they agree on it: the index changes which theorems are tried, and possibly the syntactic form of the derivative, but not the result of the search. Table 1 summarizes the running
R. Shahin
(a) time per differentiation

(b) speedup due to indexing
Fig. 6: (a) Time per differentiation in milliseconds against the size of the input function in expression tree nodes, with and without the theorem index (log scale). Crosses mark the 12 test cases that do not complete without the index. (b) Speedup due to indexing per test case, for functions whose computed domain is restricted or universal (log scale).
times, and Fig. 6 shows them per test case against the size of the input function in expression tree nodes.
With the index, the median time per differentiation is 181 ms, 95% of the test cases take less than 0.42 s, and the slowest takes 1.9 s. Without the index, the median is 2.4 s and the slowest successful test case takes 12.3 s. Indexing speeds up differentiation by a factor of 8.6 for the median test case, and the total time for all 488 test cases drops from 1333 s to 98 s. The speedup grows with function size (Fig. 6b), and is larger for functions with a restricted domain (median 13.8×) than for functions with a universal domain (median 5.9×). Theorems with domain premises (e.g., for division, log, and tan) have more arguments than most other derivative theorems, so they come late in the database. Without the index, the search reaches them only after trying, and failing to apply, most other theorems.
Functions with a restricted domain still take longer than those with a universal domain, also with the index (median 202 ms vs. 67 ms). They tend to be larger (median 20 vs. 10.5 nodes) and to use more complex derivative theorems; in addition, each domain premise becomes a hole in the proof that has to be filled from the domain predicate.
We also checked the computed domains: every conjunct has the form for some expression , i.e., a non-zero denominator, argument of log, or cosine of the argument of tan, and all but one of the 433 restricted domains hold at some of 4000 points in , evaluated with Mathlib's conventions for division by zero and logarithms. The exception, for , requires a product with a zero factor to be non-zero, so its correctness theorem holds vacuously (Sec. 6).
6 Discussion
Generality. Our evaluation (Sec. 5) covered randomly generated real functions over a limited grammar, chosen for practical reasons: to evaluate the applicability and performance of the approach, whose soundness is guaranteed by the Lean kernel. The framework is not restricted to this grammar: it only needs derivative theorems for the building blocks of a function, and composition theorems such as the chain rule. Mathlib has such theorems for many real functions outside our grammar, and they can be used as soon as their packages are imported; as Mathlib grows, it may also cover domains other than the real numbers, which the type class constraints of HasDerivAt already allow. Functions with conditionals, such as piecewise functions, would need derivative theorems that hold on parts of the domain, which HasDerivAt, being stated at a point, accommodates. Functions of multiple variables and partial derivatives would require extending the differentiate command, to compute a domain over all parameters and to specify the parameter to differentiate with respect to.
Soundness and Precision of Side Conditions. The correctness theorem , domain is a soundness guarantee: wherever the domain predicate holds, is the derivative of . However, it does not guarantee that the domain predicate is precise. Side conditions are collected from the premises of the theorems applied during derivative search, following the syntactic structure of rather than its semantics. As a result, the computed domain is a sufficient, but not necessarily the weakest, precondition for differentiability, in the sense of Dijkstra's weakest preconditions [7].
In the extreme case, the domain predicate can be unsatisfiable, making the correctness theorem vacuously true. For example, since division in Mathlib is total, is constant, yet differentiating it syntactically yields the side condition , i.e., False. This also occurs in our evaluation, for one of the 500 test functions, where a factor of the argument of log is (Sec. 5). Such a certificate is useless, but it is never wrong: using the correctness proof at any particular point requires a proof of domain , so an unsatisfiable domain cannot be used to derive an incorrect derivative value. The same limitation applies to side conditions generated by structural differentiation in other proof assistants (Sec. 7).
Two inexpensive mitigations are (1) simplifying the domain predicate and rejecting results whose domain reduces to False, and (2) extending CDeriv with a proof that the domain is non-empty, found by trying candidate witnesses. A stronger guarantee is that the domain is a non-empty open set, so that the derivative is valid on a neighborhood of some point. Proving that the domain is maximal, i.e., that f is not differentiable outside of it, is outside the scope of this paper.
Performance and Further Optimizations. Profiling the search without the theorem index showed where its time goes. For a typical function with a restricted domain, 97% of the 1970 theorem applications attempted by the search failed, and those failed attempts took about 80% of the running time. Each attempt
R. Shahin
calls the unifier (Lean.Meta.isDefEq ), which checks whether the function being differentiated is definitionally (not just syntactically) equal to the function f in the conclusion of a theorem. Before giving up on a mismatch, the unifier unfolds definitions deeply, e.g., HasDerivAt down to its filter-based definition, and real-number functions down to their definitions in terms of complex numbers. All test cases that time out without the index exhaust the heartbeat limit during unification. The theorem index (Sec. 4.2) removes most of these attempts: for the same function, the number of attempted applications drops from 1970 to 79, and over the whole test set (Sec. 5) differentiation becomes 8.6 times faster for the median test case, with no timeouts.
Further optimizations remain possible. (1) Within the theorems indexed by a head symbol, the search still tries candidates in order with full unification. A discrimination tree, as used by Lean's simplifier, keyed on the structure of the whole function rather than its head symbol, would narrow the candidates further. (2) Restricting unification to reducible definitions would make failed attempts cheap, but we found that some derivations rely on unfolding, e.g., of the instances of arithmetic operations on , so it would need a fallback to full unification. (3) Preprocessing the input function into a syntactic normal form might allow syntactic instead of definitional matching altogether.
Beyond Differentiation. One important reason why our framework works is the fact that derivatives are unique, i.e., a differentiable function has a unique derivative. This guarantees the confluence of the stepwise construction of the proof tree of the derivative of a function. As a result, we could start with a set of theorems (together with their proofs), and apply them compositionally to reach a computational result, together with a correctness certificate. But is this unique to computing derivatives?
If we were to inspect the design of the framework again, it might be surprising that, with the exception of particularly storing theorems with a HasDerivAt conclusion in the database, it has nothing specific to computing derivatives. The domain predicate of the derivative is a precondition of the compositional computation. Other certified compositional computations can be inferred in a similar fashion. For example, static program analyses based on Dijkstra's weakest precondition calculus [7] can be implemented similarly. Here a precondition (ideally the weakest one) would be analogous to the derivative domain, while the result of the analysis would be analogous to the derivative. Generalizing our framework to search for computational results and their preconditions given compositional theorems, while stepwise constructing a correctness certificate as a part of the process, can be another future direction in which this work can evolve.
7 Related Work
Automatic differentiation in its different forms (numerical, algorithmic, and symbolic) has been extensively surveyed by different research groups [26,10,2]. Other
https://leanprover-community.github.io/mathlib4_docs/Lean/Meta/Basic.html#Lean.Meta.isDefEq surveys focused on flaws in existing automatic differentiation systems [12], and pitfalls developers typically overlook when developing new automatic differentiation approaches [11]. With so many issues found in existing systems, it is clear that generating a correctness certificate together with the derivative function is of real value.
Within Mathlib itself, the fun_prop tactic proves properties such as differentiability by decomposing a function into elementary functions, and simplification lemmas about deriv can rewrite derivative expressions. The SciLean scientific computing library [24] builds on Mathlib's derivatives with the fun_trans tactic, which computes derivatives by rewriting with differentiation rules registered with the tactic. In both cases, side conditions such as for division or log have to be discharged at a given point, e.g., from hypotheses supplied by the user. In contrast, our approach infers those side conditions, and returns them as the domain on which the computed derivative is valid. In previous work, we embedded Datalog in Lean, translating Datalog queries into theorems proved by backward chaining, and used it, among other examples, to compute derivatives from Mathlib theorems listed by the user [22]. That example is restricted to functions differentiable everywhere, since it requires the derivative at every point; here, the applicable theorems are found automatically, and the domain on which the derivative is valid is computed.
Structural, theorem-driven differentiation has also been implemented in other proof assistants. In HOL4, the DIFF_CONV conversion [25], building on Harrison's formalization of real analysis in HOL [9], derives a derivative theorem for a given term, carrying side conditions as hypotheses. Isabelle/HOL provides the derivative_eq_intros rule collection, which, combined with the simplifier, computes derivatives of large expressions, leaving side conditions as residual subgoals [21]. In Coq, the auto_derive tactic of the Coquelicot library [4] proves the differentiability of an expression and computes its derivative, generating side goals for the conditions under which the derivative exists. In a similar spirit, an automated continuity checker for real-valued functions was developed in PVS [8]. Our approach differs in three ways. First, the result is a single self-contained CDeriv object packaging the derivative, an explicit domain predicate, and a closed proof, rather than a theorem with hypotheses or residual goals left to the user. Second, instead of relying on a fixed, curated rule set, derivative rules are discovered by searching the environment for HasDerivAt theorems, so new Mathlib theorems are picked up automatically once imported. Third, differentiation is exposed as a top-level command producing a definition, rather than as a tactic used inside a proof. A different use of theorem proving is to verify an automatic differentiation tool once and for all, as done in Coq for the Odyssée tool on a subset of FORTRAN programs [17]. In contrast, our approach does not verify the differentiation procedure itself; instead, each computed derivative comes with its own kernel-checked certificate.
Approaches other than theorem proving have also been pursued to improve the correctness of automatic differentiation systems. At the formal semantics level, automatic differentiation formalization in the Turing-complete PCF core
R. Shahin
language has been studied [18]. Correctness of typical approaches particularly in the case of non-differentiable functions was also studied [15]. Lighter-weight approaches were also proposed, e.g., static analysis to find bugs in automatic differentiation systems [14]. Those approaches all start from basic principles, attempting to formally define the correctness of differentiation, and apply the definition to some classes of functions. Our approach, on the other hand, starts with mathematically sound theorems whose proofs are checked by Lean, and builds a stepwise proof that follows the structure of the function being differentiated.
Using theorem provers to write certified programs or develop other software artifacts has been gradually growing in adoption and scope in the last 20 years. Early success stories included the CompCert certified C compiler project [16] and the seL4 certified microkernel [13]. More recent examples include formalizing authorization policies and access permissions [6], formalizing change-impact assessment in product lines of assurance cases [23], and sound compositional construction of assurance cases from building blocks [27].
8 Conclusion
In this paper we presented an approach to automatic function differentiation that generates a correctness certificate together with the derivative. It also generates a predicate on the function input, a sufficient condition under which the derivative is valid. This approach builds on Mathlib's formalization of derivatives and differentiation rules. Our evaluation of the approach shows that it handles relatively complex functions, including functions whose derivative is valid only on a restricted domain, and that indexing the derivative theorems by the function they differentiate makes the search 8.6 times faster for the median test case, and up to 71 times faster.
We believe this approach can be extended in several ways. Our implementation currently supports only first-order, one-dimensional derivatives, possibly with restricted domains. One relatively straightforward extension is adding support for higher-order derivatives by repeatedly differentiating the derivative. Supporting partial derivatives and multidimensional (Fréchet) derivatives, which Mathlib already formalizes, is another possible extension. Finally, the computed domain is a sufficient condition for the derivative to be valid, but not necessarily the largest one; proving that it is non-empty, or open, would make the correctness certificate more informative (Sec. 6).
Beyond extending the approach itself, certified derivatives are ultimately meant to be used in software, such as safety-critical systems, where the computed derivative is evaluated using fixed-point or floating-point approximations of real numbers. Formalizing the approximation bounds of those representations would extend the correctness guarantee from the derivative over the reals to its numerical implementation.
Acknowledgments. We thank the anonymous reviewers for their insightful comments and suggestions.
References
-
Baanen, A., Bentkamp, A., Blanchette, J., Hölzl, J., Limperg, J.: The hitchhiker's guide to logical verification (2024 edition), https://lean-forward.github.io/hitchhikers-guide/2024/
-
Baydin, A.G., Pearlmutter, B.A., Radul, A.A., Siskind, J.M.: Automatic differentiation in machine learning: a survey. Journal of machine learning research 18(153), 1–43 (2018)
-
Bertot, Y., Castran, P.: Interactive Theorem Proving and Program Development: Coq'Art The Calculus of Inductive Constructions. Springer Publishing Company, Incorporated, 1st edn. (2010)
-
Boldo, S., Lelay, C., Melquiond, G.: Coquelicot: A User-Friendly Library of Real Analysis for Coq. Mathematics in Computer Science 9(1), 41–62 (2015). https://doi.org/10.1007/s11786-014-0181-1
-
mathlib Community, T.: The lean mathematical library. In: Proceedings of the 9th ACM SIGPLAN International Conference on Certified Programs and Proofs. p. 367–381. CPP 2020, Association for Computing Machinery, New York, NY, USA (2020). https://doi.org/10.1145/3372885.3373824, https://doi.org/10.1145/3372885.3373824
-
Cutler, J.W., Disselkoen, C., Eline, A., He, S., Headley, K., Hicks, M., Hietala, K., Ioannidis, E., Kastner, J., Mamat, A., McAdams, D., McCutchen, M., Rungta, N., Torlak, E., Wells, A.M.: Cedar: A new language for expressive, fast, safe, and analyzable authorization. Proc. ACM Program. Lang. 8(OOPSLA1) (Apr 2024). https://doi.org/10.1145/3649835, https://doi.org/10.1145/3649835
-
Dijkstra, E.W.: A Discipline of Programming. Prentice Hall PTR, USA, 1st edn. (1976)
-
Gottliebsen, H.: Transcendental Functions and Continuity Checking in PVS. In: Theorem Proving in Higher Order Logics (TPHOLs 2000). LNCS, vol. 1869, pp. 197–214. Springer (2000). https://doi.org/10.1007/3-540-44659-1_13
-
Harrison, J.: Theorem Proving with the Real Numbers. Tech. Rep. UCAM-CLTR-408, University of Cambridge Computer Laboratory (1996)
-
Hoffmann, P.H.: A hitchhiker's guide to automatic differentiation. Numerical Algorithms 72(3), 775–811 (2016)
-
Hückelheim, J., Menon, H., Moses, W., Christianson, B., Hovland, P., Hascoët, L.: A taxonomy of automatic differentiation pitfalls. WIREs Data Mining and Knowledge Discovery 14(6), e1555 (2024). https://doi.org/https://doi.org/10.1002/widm.1555, https://wires.onlinelibrary.wiley.com/doi/abs/10.1002/widm.1555
-
Johnson, D., Maxfield, T., Jin, Y., Fedkiw, R.: Software-based automatic differentiation is flawed. Journal of Computational Physics p. 114319 (2025). https://doi.org/https://doi.org/10.1016/j.jcp.2025.114319, https://www.sciencedirect.com/science/article/pii/S002199912500600X
-
Klein, G., Elphinstone, K., Heiser, G., Andronick, J., Cock, D., Derrin, P., Elkaduwe, D., Engelhardt, K., Kolanski, R., Norrish, M., et al.: seL4: Formal verification of an OS kernel. In: Proceedings of the ACM SIGOPS 22nd Symposium on Operating Systems Principles. pp. 207–220 (2009)
-
Laurel, J., Qian, S.B., Singh, G., Misailovic, S.: Synthesizing precise static analyzers for automatic differentiation. Proc. ACM Program. Lang. 7(OOPSLA2) (Oct 2023). https://doi.org/10.1145/3622867, https://doi.org/10.1145/3622867
R. Shahin
-
Lee, W., Yu, H., Rival, X., Yang, H.: On correctness of automatic differentiation for non-differentiable functions. Advances in neural information processing systems 33, 6719–6730 (2020)
-
Leroy, X.: A Formally Verified Compiler Back-end. Journal of Automated Reasoning 43(4), 363–446 (2009), http://xavierleroy.org/publi/compcert-backend.pdf
-
Mayero, M.: Using Theorem Proving for Numerical Analysis (Correctness Proof of an Automatic Differentiation Algorithm). In: Theorem Proving in Higher Order Logics (TPHOLs 2002). LNCS, vol. 2410, pp. 246–262. Springer (2002). https://doi.org/10.1007/3-540-45685-6_17
-
Mazza, D., Pagani, M.: Automatic differentiation in pcf. Proc. ACM Program. Lang. 5(POPL) (Jan 2021). https://doi.org/10.1145/3434309, https://doi.org/10.1145/3434309
-
Moura, L.d., Ullrich, S.: The lean 4 theorem prover and programming language. In: Automated Deduction – CADE 28: 28th International Conference on Automated Deduction, Virtual Event, July 12–15, 2021, Proceedings. p. 625–635. Springer-Verlag, Berlin, Heidelberg (2021). https://doi.org/10.1007/978-3-030-79876-5_37, https://doi.org/10.1007/978-3-030-79876-5_37
-
Paulino, A., Testa, D., Ayers, E., Karunus, E., Böving, H., Limperg, J., Gadgil, S., Bhat, S.: Metaprogramming in lean 4, https://leanprover-community.github.io/lean4-metaprogramming-book/
-
Paulson, L.C.: Formalising New Mathematics in Isabelle: Diagonal Ramsey. In: 16th International Conference on Interactive Theorem Proving (ITP 2025). LIPIcs, vol. 352, pp. 18:1–18:18 (2025). https://doi.org/10.4230/LIPIcs.ITP.2025.18
-
Shahin, R.: A Shallow Embedding of Datalog in Lean. In: Proceedings of the 19th ACM SIGPLAN International Conference on Software Language Engineering (SLE '26). pp. 108–117. ACM (2026). https://doi.org/10.1145/3806383.3815521
-
Shahin, R., Kokaly, S., Chechik, M.: Towards certified analysis of software product line safety cases. In: International Conference on Computer Safety, Reliability, and Security. pp. 130–145. Springer (2021)
-
Skřivan, T.: Scientific computing in lean (2022), https://lecopivo.github.io/scientific-computing-lean/
-
The HOL4 Team: HOL4 Diff structure: DIFF_CONV. https://hol-theorem-prover.org/docs/trindemossen-2/htmlsigns/Diff.html, accessed October 2026
-
Tolsma, J.E., Barton, P.I.: On computational differentiation. Computers & chemical engineering 22(4-5), 475–490 (1998)
-
Viger, T., Murphy, L., Di Sandro, A., Menghi, C., Shahin, R., Chechik, M.: The FOREMOST approach to building valid model-based safety arguments. Software and Systems Modeling 22(5), 1473–1494 (2023)
-
Wengert, R.E.: A simple automatic derivative evaluation program. Communications of the ACM 7(8), 463–464 (1964)