TorchLean: Formalizing Neural Networks in Lean
Organizations: California Institute of Technology · Washington University in St. Louis · University of Illinois Urbana-Champaign
Abstract
Neural networks are increasingly deployed in scientific, safety critical, and mission critical pipelines, yet verification and analysis are often performed outside the programming environment that defines and runs the model. This creates a semantic gap between the executed network and the analyzed artifact: guarantees can depend on implicit conventions about operator semantics, tensor layouts, preprocessing, floating-point behavior, graph transformations, accelerated kernels, and external certificates. We present TorchLean, a unified framework for formalizing, executing, and verifying neural networks in Lean 4. TorchLean treats learned models as executable programs and mathematical objects with a shared semantics for computation, verification, and theorem proving. The framework provides a PyTorch style API for typed tensors, layers, objectives, optimizers, automatic differentiation, and graph programs, with eager and compiled execution paths that lower to a common computation-graph representation. TorchLean supports exact and finite-precision tensor semantics, verified reverse-mode differentiation, interval and affine bound propagation, CROWN/LiRPA style certificate checking, import/export workflows, and CUDA-backed execution through explicit FFI boundaries. It also includes semantic layers for attention and FlashAttention, state-space sequence models, diffusion and sampling processes, probability kernels, reinforcement-learning objectives and Markov decision processes, and self-supervised objectives such as masked autoencoding, JEPA-style predictive views, and variance/correlation-based anti-collapse losses. Together, these components provide a semantic foundation for verified machine learning, where executable neural network artifacts, verification procedures, runtime boundaries, and mathematical claims can be stated and related inside one theorem-proving environment.
Figures & tables
| Mode | Purpose | Semantics and trust |
| Proofs, reference Autograd | Exact real arithmetic; reference semantics for theorem statements. | |
| Interval / affine | IBP, CROWN/LiRPA bounds | Sound enclosure domains with proved transfer rules where available. |
| FP32 / NF | Rounding-aware theorems | Round-on- proof model with compositional error envelopes. |
| IEEE32Exec | Executable Float32 model | Lean-defined binary32 semantics for core ops; hardware matching is separate. |
| Arb/FLINT oracle | Rigorous transcendentals | External validated ball/interval enclosures; explicit non-kernel oracle boundary. |
| Lean Float32 | Fast execution | Runtime implementation opaque to the kernel; treated as a deployment assumption or validated backend. |
| Path | Method | Safe/ | Time |
| Lean | IBP | 0/30 | 6.05s |
| Lean | CROWN-Obj | 6/30 | 22.60s |
| Lean | CROWN+ | 6/30 | 14.21s |
| CPU producer | -CROWN | 13/30 | 8.39s |
| CUDA producer | -CROWN | 13/30 | 7.67s |
Appendix figures & tables6 assets
Supplementary material from the paper’s appendix.
Appendix
| Component | What the paper claims (scope) | Status | Where |
| Shared IR semantics | Operator tagged SSA/DAG IR with a precise denotation reused by execution and verification. | Kernel-checked definitions | Sections 2 , B |
| Reverse-mode AD | Backpropagation equals the adjoint Fréchet derivative for well-typed SSA/DAG graphs over , assuming local per-op derivative correctness (with a pointwise variant for non-smooth ops). | Proved | Theorem 2.2 , Appendix B |
| TorchLean compilation | “Compiled mode” produces the verifier IR; full compiler correctness for arbitrary TorchLean programs is not yet proved. | Proved (fragment) / Future (full) | Theorems B.3 – B.3 |
| IBP / CROWN operators | Sound transfer rules and relaxations for a curated set of operators; additional ops use conservative fallbacks or are treated as unsupported in the strongest theorems. | Mixed (proved subset) | Appendix E |
| Certificate checking | Small Lean checkers validate certificate structure and the final enclosure constraints needed to discharge a theorem about . | Checked (plus proved core) | Section 3 , Appendix E |
| External solvers (e.g. -CROWN) | Used only as untrusted certificate producers; full optimizer internals are outside the checked certificate scope in this work. | Assumed/External | Section 3 , Appendix E |
| OpKind / primitive | Global HasFDerivAt | Pointwise (side conditions) | Not covered |
| Linear / shape ops | add , sub , mul_elem , linear , matmul , conv2d , broadcastTo , reshape , flatten , permute , reduce_sum , reduce_mean , sum , concat (curated axes), swap_first_two , transpose3d_last_two | – | – |
| Smooth nonlinearities / losses | tanh , sigmoid , exp , square , sinh , cosh , softplus , gelu (tanh approximation), silu , softmax / log_softmax (curated axis), layernorm (curated axis), mse_loss , cross-entropy/NLL/BCE/KL pointwise losses, smooth surrogates safe_log and smooth_abs (with ) | – | – |
| Non-smooth / domain-sensitive | – | relu , abs , log , inv , sqrt , max_elem / min_elem (no ties) | – |
| Structured graph families | fixed-mask dropout, scaled dot-product attention, unmasked MHA, residual MHA, post-norm transformer sublayers, BatchNorm-like graphs, one-step Elman RNN, gather-row / embedding lookup adjointness | – | full GPT/ViT stacks, masked causal decoder blocks, full recurrent/state-space sequence theorems, FNO spectral-conv training paths |
| Nondifferentiable / workflow ops | – | – | detach , rand_uniform , stochastic masks beyond fixed-mask dropout, pooling ( max_pool2d , avg_pool2d ), executable CUDA/cuBLAS/cuFFT kernels |
| Aspect | PyTorch | TorchLean |
| Shapes | Dynamic runtime shapes; many errors are runtime exceptions. | Shapes are part of types ( Tensor s ); many mismatches are untypeable. |
| Dtypes | Many numeric and integer dtypes; mixed-dtype graphs are common. | Scalar-polymorphic single-dtype graphs (one per run); integer indices handled via a separate non-differentiable channel ( NatRef / NatVecRef ) in sessions. |
| Execution modes | Eager by default, with compilation/export toolchains (TorchScript, ONNX, AOT). | Eager tape backend and proof-linked compiled SSA/DAG backend share one semantics; the compiled graph is the verifier target by construction. |
| Autograd status | Widely tested and trusted, but not formally proved correct. | Reverse-mode correctness theorem for well-typed SSA/DAG graphs; eager runs linked to proved graphs. |
| Indexing | Tensor-valued indexing/slicing/gather/scatter across dtypes (e.g. LongTensor ). | Typed indexing primitives and session-level Nat channels for labels/indices; not yet PyTorch-complete for tensor-valued integer indices. |
| Breadth/performance | Very broad op surface and ecosystem; highly optimized CPU/GPU kernels. | Curated op surface focused on verification-relevant primitives; extensible via a “new op” workflow; Lean execution prioritizes clarity/verification over performance. |