Repository navigation
Conversation
Member
|
Thanks, this is right. The fix and your test will be in the Lean 4.36 release commit (branch |
Contributor
Author
|
@Robertboy18 thanks! |
Robertboy18
added a commit
that referenced
this pull request
Nov 19, 2026
Lean v4.36.0, Mathlib v4.36.0 and FloatLib 71a3d7ff. The guide (home_page/blueprint) and the Python bindings still pin Lean 4.35 and FloatLib acba2057 while requiring TorchLean at `../..`, so neither builds against this commit until VersoBlueprint and nerodia have 4.36 versions. Special functions: - `Op.special` and the family `SpecialFn n`: erfc, erfcx, erfinv, ndtr, ndtri, lgamma, digamma, the Bessel functions J0, J1, I0, I1, I0e and I1e, the spherical j0, igamma, igammac, zeta and betainc, defined from Mathlib's functions. They have operator certificates, derivative certificates where the function is differentiable, roundoff registration, and import from torch.special and from lax. - They are specified over the reals only. No binary format executes them, none of their roundoff analyses is better than `unsupported`, and no test compares their values with PyTorch or JAX. Each member's derivative certificate applies on its proved smooth domain (`SpecialFn.smoothDomain`): for igamma and igammac where both arguments are positive, for zeta where s > 1 and q > 0, and for betainc where a and b are positive and x is in (0, 1). These are not the largest such sets: zeta at q <= 0 and the boundaries are not covered. - frexp, in the formats whose exponents fit its int32 word. JAX import (155 of JAX 0.11.1's 219 lax primitives): - complex values as their real and imaginary parts, with real, imag, conj, fft, reductions, sorts and scans; - cumlogsumexp, stack, unstack, approx_top_k, select_and_scatter_add, select_and_gather_add, ragged_dot_general, scaled_dot and rng_uniform; - cond, scan and while loops with a trip count known at import; - sorts of several operands and the total-order comparisons; an integer or Boolean key is sorted at its own element, so it is not converted to binary64 and a 64-bit key is not split; - the four float8 formats: sums, differences and products rounded once in the format, and the other operations imported at float8 in binary32 and rounded once to the format. For the 20 elementary functions a test checks this at every word of each format; no theorem proves it; - triangular_solve, cholesky, cholesky_update, householder_product, ormqr, lu_pivots_to_permutation and tridiagonal_solve as IR programs. Where JAX and StableHLO differ, the import follows StableHLO: - select_and_scatter_add is StableHLO's operation on the operand, not the expand_padding lowering that JAX registers for CPU and GPU, so with padding the two can differ; - clamp is `min (max x lo) hi`, not JAX's documented case form, at a NaN bound, at x = -0 or where lo > hi; - ragged_dot_general's free-axis mode selects each position's group, TorchLean's reading where JAX documents only the shapes, so an infinity in another group does not reach it. None of them is refused. PyTorch capture (147 of PyTorch 2.13's 160 core ATen operators): - convolution, linear and normalization weights not known at capture; - the default graph's T, mT, mH, adjoint, swapdims, movedim, rsub, silu as `Op.silu`, stack, repeat_interleave, roll, tril, triu, detach_ and detach as `Op.detach`, device moves, copy_, scatter_ and scatter_add_; - index_add, index_copy and their in-place forms of a fresh destination (a binary16 index_add of a matrix or higher rounds each step, where eager's CPU kernel sums in binary32); unbind; Tensor.unfold as strided slices; linalg_vector_norm; linspace and logspace of constant arguments; created tensors of one value (zeros, ones, full and their forms) as one word broadcast to the shape; - an operator without a lowering of its own whose CPU kernel is its CompositeImplicitAutograd composite (einsum, outer, type_as, expand_as among them) as that composite, when the composite itself imports and its value is a tensor: item stays refused; - transposed convolutions (conv_transpose1d, 2d and 3d, groups, output_padding) as the convolution at stride 1 of the input spread with zeros, by the kernel with each group's channel axes swapped and its spatial axes reversed. The spread zeros multiply the kernel, where eager adds only the input entries' products, so an infinite or NaN kernel entry gives NaN where eager can be finite, and a test pins that difference. Its sums round in the IR convolution's order, not eager's, so the tests compare integer data, as for convolutions; - the dtype arguments of sum, prod, mean, cumsum, cumprod, softmax and log_softmax as a cast first, as their docstrings state. Eager mean to binary16 or bfloat16 from another type rounds once instead, and a test pins that difference; - binary16 and bfloat16 sum and mean as a binary32 accumulation rounded once, as ATen's CPU kernel computes them, and a binary16 or bfloat16 vector norm in binary32; prod rounds each step in the format, as eager does; - the stable sort of integer and Boolean tensors, through `Op.sort` at an element type; - integer and Boolean values through the runtime gathers (index, index_select, gather, take_along_dim) and the writes that replace (index_put without accumulate, index_copy, scatter of a tensor); the writes that sum and scatter of a Python value stay floating; - complex64 and complex128 values as their real and imaginary parts on a last axis of 2, through rfft, irfft, view_as_complex, view_as_real, real, imag, slices, selects, unsqueeze, view and reshape. The quotient by a nonzero finite real number is c10::complex's division, equal to eager word for word in the tests; the product of two complex tensors is (ac - bd, ad + bc), and eager fuses multiply-adds after its last whole AVX512 vector, so the tests compare it within a tolerance. Complex inputs, constants, outputs and other complex operators are refused; - the four float8 formats are typed, and only their conversions and the operators that move entries without reading them are imported; any other float8 operator and float8_e8m0fnu are refused. A conversion to a float8 format rounds once, also from binary64, where eager rounds through binary32, and the conversion to float8_e4m3fn first clamps to [-448, 448], as PyTorch's saturating conversion does; - leaky_relu as `Op.leakyReLU` and elu at unit scales as `Op.elu`, so their pullbacks at 0 are PyTorch's; softplus and elu with other scales stay their kernels' selections; - a torch.export graph that holds a grad-mode region is refused, not traced symbolically; a decomposed program, where detach_ no longer appears, carries a `decomposed_program` constraint; - state export resolves a lazily negated tensor before reading its words (PR #40). Linear algebra: QR, pivoted QR, LU, eigh, eig, SVD, Schur, real Schur, Hessenberg, tridiagonal reduction and tridiagonal solves, specified as relations, with existence proofs. No theorem links these relations to the seven IR programs above. Roundoff: `#roundoff_coverage` reuses a theorem with the same statement instead of declaring another, and `every M` registers the public functions of the modules under M whose result is a scalar or a tensor, so the 45 functions of TorchLean.NN.RL and TorchLean.NN.Optimizer are analyzed. The baseline is regenerated: 2805 rows, 332 proved, 1232 conditional, 1169 unsupported and 72 failed (main: 2517 rows, 175, 972, 1325 and 45). No row of main is removed. `Op.gelu` [tanh backward] configured absolute goes from conditional to failed, and `Op.attentionFromScores` [forward] mixed from 1 premise to 4. The 184 rows of the reinforcement-learning and optimizer functions are new, and 20 of them fail: 13 over the heartbeat budget, among them the policy KL divergences, 6 of `RL.DQN.loss` at its cast and 1 of `RL.Tabular.qLearningTarget` at its match. The symbolic bounds of rows that stay proved or conditional are not compared with main's. 29 rows of 45b43c6's baseline (Op.conv, Op.convTranspose, Op.cat, Op.indexAt, Op.gather, Op.topk) change only their hashes; their status, premises, terms and values are the same. The transformer block's rounding bound, `Arithmetic.sqrt_sum_sq_block_sub_le`, is a bound of its own schedule `Arithmetic.block`, not of the executed block: that layer norm takes the variance of the unscaled centered entries and that linear map starts its sum from the bias, where `Tensor.layerNorm` rescales by `Tensor.normalizationScale` and `Linear.forward` adds the bias last. Only the exact real functions are tied to the op table. Also: - `Op.fma`, which no frontend produces yet; - `Op.sort` takes an element type, so the wire format is version 4 and no version 3 record decodes any more; - the policy KL divergences use the expm1x form of Amos (2026, section 4.1), centered at the largest log-ratio and proved equal to the textbook sum over the reals. `klFromLogits` centers a quarter of each logit vector before the difference, takes the old weights from the log-softmax, no longer takes `epsilon` and clamps nothing. The log-sum-exp normalizer is kept as two parts, so binary32 `klFromLogits [0, -2^27] [0, 0]` is log 2. The shift d and the old log-probabilities l are summed once, as (d - t) + l with t the largest entry of d + l, and each term's exponent subtracts the largest entry of that sum, so binary32 `klFromLogits [0, -384, -2^33] [0, 2^33, 2^32]` is 2^33 and `[0.5625, 0, -2^26]` against `[0.5625, 2.25, -2^25]` is about 0.4737, where two other orders of the exponent gave infinity and about -0.214. In floating point it is tested on the tests' inputs only, not proved: binary32 `klFromLogits [0, 0] [-2^127, 2^127]` is 2^127, and its docstring states the logit range, old logits at most the largest finite value apart, argues that each term's exponent is at most about log 2 there, and states two limits of rounding the shift between the logit vectors, which the tests check: `[0, 1]` against `[2^-26, 1]` gives 0 (the divergence is about 2.2e-17), and against `[0, 5]` (about 5.0067) `[0, -2^24]` gives about 4.0181 and `[0, -2^100]` gives log 2; the 0.4737 above is the second limit (the divergence is about 0.5896); - `IsCholesky` requires a positive diagonal, as torch.linalg.cholesky's factor has; - the roundoff coverage restores a private matcher's splitter and equations from the matcher they belong to; - duplicate definitions and theorems removed, unused imports removed, linter findings fixed, and docstrings added; - the docs, the guide and the site updated. Changed or deleted public statements: `klFromLogits`'s signature; `index_of_outs`, replaced by `not_isScalar_of_outs`; 153 generated coverage theorem names, whose statements stay under the other route's name; `releaseCUDABuffer` and `releaseSparseBuffer`; 16 lemmas no longer `@[simp]`; `VPSchedule.alphaBar_zero`, now `sched.alphaBar 0 = 1`; `IsCholesky`, now with `∀ i, 0 < L i i`; `Op.sort`, now with an element argument, and `Op.Wire.formatVersion`, now 4; `SpecialFn.smoothDomain`, no longer empty for igamma, igammac, zeta and betainc; the nine instances `Op.Capability.rounding` to `Op.Capability.fma`, now the one instance `Op.Capability.present`.
Robertboy18
added a commit
that referenced
this pull request
Nov 20, 2026
Lean v4.36.0, Mathlib v4.36.0 and FloatLib 71a3d7ff. The guide (home_page/blueprint) and the Python bindings still pin Lean 4.35 and FloatLib acba2057 while requiring TorchLean at `../..`, so neither builds against this commit until VersoBlueprint and nerodia have 4.36 versions. Special functions: - `Op.special` and the family `SpecialFn n`: erfc, erfcx, erfinv, ndtr, ndtri, lgamma, digamma, the Bessel functions J0, J1, I0, I1, I0e and I1e, the spherical j0, igamma, igammac, zeta and betainc, defined from Mathlib's functions. They have operator certificates, derivative certificates where the function is differentiable, roundoff registration, and import from torch.special and from lax. - They are specified over the reals only. No binary format executes them, none of their roundoff analyses is better than `unsupported`, and no test compares their values with PyTorch or JAX. Each member's derivative certificate applies on its proved smooth domain (`SpecialFn.smoothDomain`): for igamma and igammac where both arguments are positive, for zeta where s > 1 and q > 0, and for betainc where a and b are positive and x is in (0, 1). These are not the largest such sets: zeta at q <= 0 and the boundaries are not covered. - frexp, in the formats whose exponents fit its int32 word. JAX import (155 of JAX 0.11.1's 219 lax primitives): - complex values as their real and imaginary parts, with real, imag, conj, fft, reductions, sorts and scans; - cumlogsumexp, stack, unstack, approx_top_k, select_and_scatter_add, select_and_gather_add, ragged_dot_general, scaled_dot and rng_uniform; - cond, scan and while loops with a trip count known at import; - sorts of several operands and the total-order comparisons; an integer or Boolean key is sorted at its own element, so it is not converted to binary64 and a 64-bit key is not split; - the four float8 formats: sums, differences and products rounded once in the format, and the other operations imported at float8 in binary32 and rounded once to the format. For the 20 elementary functions a test checks this at every word of each format; no theorem proves it; - triangular_solve, cholesky, cholesky_update, householder_product, ormqr, lu_pivots_to_permutation and tridiagonal_solve as IR programs. Where JAX and StableHLO differ, the import follows StableHLO: - select_and_scatter_add is StableHLO's operation on the operand, not the expand_padding lowering that JAX registers for CPU and GPU, so with padding the two can differ; - clamp is `min (max x lo) hi`, not JAX's documented case form, at a NaN bound, at x = -0 or where lo > hi; - ragged_dot_general's free-axis mode selects each position's group, TorchLean's reading where JAX documents only the shapes, so an infinity in another group does not reach it. None of them is refused. PyTorch capture (147 of PyTorch 2.13's 160 core ATen operators): - convolution, linear and normalization weights not known at capture; - the default graph's T, mT, mH, adjoint, swapdims, movedim, rsub, silu as `Op.silu`, stack, repeat_interleave, roll, tril, triu, detach_ and detach as `Op.detach`, device moves, copy_, scatter_ and scatter_add_; - index_add, index_copy and their in-place forms of a fresh destination (a binary16 index_add of a matrix or higher rounds each step, where eager's CPU kernel sums in binary32); unbind; Tensor.unfold as strided slices; linalg_vector_norm; linspace and logspace of constant arguments; created tensors of one value (zeros, ones, full and their forms) as one word broadcast to the shape; - an operator without a lowering of its own whose CPU kernel is its CompositeImplicitAutograd composite (einsum, outer, type_as, expand_as among them) as that composite, when the composite itself imports and its value is a tensor: item stays refused; - transposed convolutions (conv_transpose1d, 2d and 3d, groups, output_padding) as the convolution at stride 1 of the input spread with zeros, by the kernel with each group's channel axes swapped and its spatial axes reversed. The spread zeros multiply the kernel, where eager adds only the input entries' products, so an infinite or NaN kernel entry gives NaN where eager can be finite, and a test pins that difference. Its sums round in the IR convolution's order, not eager's, so the tests compare integer data, as for convolutions; - the dtype arguments of sum, prod, mean, cumsum, cumprod, softmax and log_softmax as a cast first, as their docstrings state. Eager mean to binary16 or bfloat16 from another type rounds once instead, and a test pins that difference; - binary16 and bfloat16 sum and mean as a binary32 accumulation rounded once, as ATen's CPU kernel computes them, and a binary16 or bfloat16 vector norm in binary32; prod rounds each step in the format, as eager does; - the stable sort of integer and Boolean tensors, through `Op.sort` at an element type; - integer and Boolean values through the runtime gathers (index, index_select, gather, take_along_dim) and the writes that replace (index_put without accumulate, index_copy, scatter of a tensor); the writes that sum and scatter of a Python value stay floating; - complex64 and complex128 values as their real and imaginary parts on a last axis of 2, through rfft, irfft, view_as_complex, view_as_real, real, imag, slices, selects, unsqueeze, view and reshape. The quotient by a nonzero finite real number is c10::complex's division, equal to eager word for word in the tests; the product of two complex tensors is (ac - bd, ad + bc), and eager fuses multiply-adds after its last whole AVX512 vector, so the tests compare it within a tolerance. Complex inputs, constants, outputs and other complex operators are refused; - the four float8 formats are typed, and only their conversions and the operators that move entries without reading them are imported; any other float8 operator and float8_e8m0fnu are refused. A conversion to a float8 format rounds once, also from binary64, where eager rounds through binary32, and the conversion to float8_e4m3fn first clamps to [-448, 448], as PyTorch's saturating conversion does; - leaky_relu as `Op.leakyReLU` and elu at unit scales as `Op.elu`, so their pullbacks at 0 are PyTorch's; softplus and elu with other scales stay their kernels' selections; - a torch.export graph that holds a grad-mode region is refused, not traced symbolically; a decomposed program, where detach_ no longer appears, carries a `decomposed_program` constraint; - state export resolves a lazily negated tensor before reading its words (PR #40). Linear algebra: QR, pivoted QR, LU, eigh, eig, SVD, Schur, real Schur, Hessenberg, tridiagonal reduction and tridiagonal solves, specified as relations, with existence proofs. No theorem links these relations to the seven IR programs above. Roundoff: `#roundoff_coverage` reuses a theorem with the same statement instead of declaring another, and `every M` registers the public functions of the modules under M whose result is a scalar or a tensor, so the 45 functions of TorchLean.NN.RL and TorchLean.NN.Optimizer are analyzed. The baseline is regenerated: 2805 rows, 332 proved, 1232 conditional, 1169 unsupported and 72 failed (main: 2517 rows, 175, 972, 1325 and 45). No row of main is removed. `Op.gelu` [tanh backward] configured absolute goes from conditional to failed, and `Op.attentionFromScores` [forward] mixed from 1 premise to 4. The 184 rows of the reinforcement-learning and optimizer functions are new, and 20 of them fail: 13 over the heartbeat budget, among them the policy KL divergences, 6 of `RL.DQN.loss` at its cast and 1 of `RL.Tabular.qLearningTarget` at its match. The symbolic bounds of rows that stay proved or conditional are not compared with main's. 29 rows of 45b43c6's baseline (Op.conv, Op.convTranspose, Op.cat, Op.indexAt, Op.gather, Op.topk) change only their hashes; their status, premises, terms and values are the same. Reduction orders: `Tensor.ReduceOrder` is a binary tree over a reduction's start value and its entries, and `reduceIn` (sum, product, max, min), `sumIn`, `dotIn`, `meanIn`, `contractIn`, `matmulIn`, `poolIn` (sum and average pools), `scanIn` (cumulative sums and products) and `einsumIn` reduce in such an order, with the orders `leftFold`, `pairwise` and `blocked w`. In `leftFold` each is the existing definition (the `_leftFold` theorems), and over the reals every order that covers each entry once gives the same value. An ordered sum with a finite result in an IEEE format of FloatLib's configured binary arithmetic differs from the exact sum by at most `((1 + u) ^ d - 1)` times the sum of the absolute values, with `d` the tree's depth, which is at most `⌈log₂ (n + 1)⌉` for the pairwise order. No bound covers ordered products or the mean's division. The operator table, the IR, the wire format and the importers carry no order: their reductions mean the left fold, and no backend is proved to reduce in any order. IR flows: `IR.Flow` adds branches and loops over straight-line graphs: `cond`, which runs only the selected branch (the last for an index out of range), `scan`, and `whileLoop`, whose fuel is a parameter of the total `Flow.eval`. For every flow, `cond` equals evaluating every branch and selecting one wherever every branch is defined, a `scan` of `n` equals its body unrolled `n` times, and a `while` loop that stops after `k` iterations equals its body unrolled `k` times when `k` is at most its fuel. The checks of the IR flows run one example program each. No importer writes a flow, so JAX's cond still evaluates every branch and its loops are still unrolled, and flows have no derivative rule. The transformer block's rounding bound, `Arithmetic.sqrt_sum_sq_block_sub_le`, is a bound of its own schedule `Arithmetic.block`, not of the executed block: that layer norm takes the variance of the unscaled centered entries and that linear map starts its sum from the bias, where `Tensor.layerNorm` rescales by `Tensor.normalizationScale` and `Linear.forward` adds the bias last. Only the exact real functions are tied to the op table. Also: - `Op.fma`, which no frontend produces yet; - `Op.sort` takes an element type, so the wire format is version 4 and no version 3 record decodes any more; - the policy KL divergences use the expm1x form of Amos (2026, section 4.1), centered at the largest log-ratio and proved equal to the textbook sum over the reals. `klFromLogits` centers a quarter of each logit vector before the difference, takes the old weights from the log-softmax, no longer takes `epsilon` and clamps nothing. The log-sum-exp normalizer is kept as two parts, so binary32 `klFromLogits [0, -2^27] [0, 0]` is log 2. The shift d and the old log-probabilities l are summed once, as (d - t) + l with t the largest entry of d + l, and each term's exponent subtracts the largest entry of that sum, so binary32 `klFromLogits [0, -384, -2^33] [0, 2^33, 2^32]` is 2^33 and `[0.5625, 0, -2^26]` against `[0.5625, 2.25, -2^25]` is about 0.4737, where two other orders of the exponent gave infinity and about -0.214. In floating point it is tested on the tests' inputs only, not proved: binary32 `klFromLogits [0, 0] [-2^127, 2^127]` is 2^127, and its docstring states the logit range, old logits at most the largest finite value apart, argues that each term's exponent is at most about log 2 there, and states two limits of rounding the shift between the logit vectors, which the tests check: `[0, 1]` against `[2^-26, 1]` gives 0 (the divergence is about 2.2e-17), and against `[0, 5]` (about 5.0067) `[0, -2^24]` gives about 4.0181 and `[0, -2^100]` gives log 2; the 0.4737 above is the second limit (the divergence is about 0.5896); - `IsCholesky` requires a positive diagonal, as torch.linalg.cholesky's factor has; - the roundoff coverage restores a private matcher's splitter and equations from the matcher they belong to; - duplicate definitions and theorems removed, unused imports removed, linter findings fixed, and docstrings added; - the docs, the guide and the site updated. Changed or deleted public statements: `klFromLogits`'s signature; `index_of_outs`, replaced by `not_isScalar_of_outs`; 153 generated coverage theorem names, whose statements stay under the other route's name; `releaseCUDABuffer` and `releaseSparseBuffer`; 16 lemmas no longer `@[simp]`; `VPSchedule.alphaBar_zero`, now `sched.alphaBar 0 = 1`; `IsCholesky`, now with `∀ i, 0 < L i i`; `Op.sort`, now with an element argument, and `Op.Wire.formatVersion`, now 4; `SpecialFn.smoothDomain`, no longer empty for igamma, igammac, zeta and betainc; the nine instances `Op.Capability.rounding` to `Op.Capability.fma`, now the one instance `Op.Capability.present`.
Robertboy18
added a commit
that referenced
this pull request
Nov 20, 2026
Lean v4.36.0, Mathlib v4.36.0 and FloatLib 71a3d7ff. The guide (home_page/blueprint) and the Python bindings still pin Lean 4.35 and FloatLib acba2057 while requiring TorchLean at `../..`, so neither builds against this commit until VersoBlueprint and nerodia have 4.36 versions. Special functions: - `Op.special` and the family `SpecialFn n`: erfc, erfcx, erfinv, ndtr, ndtri, lgamma, digamma, the Bessel functions J0, J1, I0, I1, I0e and I1e, the spherical j0, igamma, igammac, zeta and betainc, defined from Mathlib's functions. They have operator certificates, derivative certificates where the function is differentiable, roundoff registration, and import from torch.special and from lax. - They are specified over the reals only. No binary format executes them, none of their roundoff analyses is better than `unsupported`, and no test compares their values with PyTorch or JAX. Each member's derivative certificate applies on its proved smooth domain (`SpecialFn.smoothDomain`): for igamma and igammac where both arguments are positive, for zeta where s > 1 and q > 0, and for betainc where a and b are positive and x is in (0, 1). These are not the largest such sets: zeta at q <= 0 and the boundaries are not covered. - frexp, in the formats whose exponents fit its int32 word. JAX import (155 of JAX 0.11.1's 219 lax primitives): - complex values as their real and imaginary parts, with real, imag, conj, fft, reductions, sorts and scans; - cumlogsumexp, stack, unstack, approx_top_k, select_and_scatter_add, select_and_gather_add, ragged_dot_general, scaled_dot and rng_uniform; - cond, scan and while, lowered by partial evaluation (below): what is decided at capture as straight-line steps, and a cond or while that the capture does not decide as one of the IR's flows, so a loop's trip count can depend on the inputs; - sorts of several operands and the total-order comparisons; an integer or Boolean key is sorted at its own element, so it is not converted to binary64 and a 64-bit key is not split; - the four float8 formats: sums, differences and products rounded once in the format, and the other operations imported at float8 in binary32 and rounded once to the format. For the 20 elementary functions a test checks this at every word of each format; no theorem proves it; - triangular_solve, cholesky, cholesky_update, householder_product, ormqr, lu_pivots_to_permutation and tridiagonal_solve as IR programs. Where JAX and StableHLO differ, the import follows StableHLO: - select_and_scatter_add is StableHLO's operation on the operand, not the expand_padding lowering that JAX registers for CPU and GPU, so with padding the two can differ; - clamp is `min (max x lo) hi`, not JAX's documented case form, at a NaN bound, at x = -0 or where lo > hi; - ragged_dot_general's free-axis mode selects each position's group, TorchLean's reading where JAX documents only the shapes, so an infinity in another group does not reach it. None of them is refused. PyTorch capture (147 of PyTorch 2.13's 160 core ATen operators): - torch.export's torch.cond, while_loop and map as the IR's flows (below), and invoke_subgraph inlined, which only torch 2.11's tests exercise, since 2.13 inlines it itself; - convolution, linear and normalization weights not known at capture; - the default graph's T, mT, mH, adjoint, swapdims, movedim, rsub, silu as `Op.silu`, stack, repeat_interleave, roll, tril, triu, detach_ and detach as `Op.detach`, device moves, copy_, scatter_ and scatter_add_; - index_add, index_copy and their in-place forms of a fresh destination (a binary16 index_add of a matrix or higher rounds each step, where eager's CPU kernel sums in binary32); unbind; Tensor.unfold as strided slices; linalg_vector_norm; linspace and logspace of constant arguments; created tensors of one value (zeros, ones, full and their forms) as one word broadcast to the shape; - an operator without a lowering of its own whose CPU kernel is its CompositeImplicitAutograd composite (einsum, outer, type_as, expand_as among them) as that composite, when the composite itself imports and its value is a tensor: item stays refused; - transposed convolutions (conv_transpose1d, 2d and 3d, groups, output_padding) as the convolution at stride 1 of the input spread with zeros, by the kernel with each group's channel axes swapped and its spatial axes reversed. The spread zeros multiply the kernel, where eager adds only the input entries' products, so an infinite or NaN kernel entry gives NaN where eager can be finite, and a test pins that difference. Its sums round in the IR convolution's order, not eager's, so the tests compare integer data, as for convolutions; - the dtype arguments of sum, prod, mean, cumsum, cumprod, softmax and log_softmax as a cast first, as their docstrings state. Eager mean to binary16 or bfloat16 from another type rounds once instead, and a test pins that difference; - binary16 and bfloat16 sum and mean as a binary32 accumulation rounded once, as ATen's CPU kernel computes them, and a binary16 or bfloat16 vector norm in binary32; prod rounds each step in the format, as eager does; - the stable sort of integer and Boolean tensors, through `Op.sort` at an element type; - integer and Boolean values through the runtime gathers (index, index_select, gather, take_along_dim) and the writes that replace (index_put without accumulate, index_copy, scatter of a tensor); the writes that sum and scatter of a Python value stay floating; - complex64 and complex128 values as their real and imaginary parts on a last axis of 2, through rfft, irfft, view_as_complex, view_as_real, real, imag, slices, selects, unsqueeze, view and reshape. The quotient by a nonzero finite real number is c10::complex's division, equal to eager word for word in the tests; the product of two complex tensors is (ac - bd, ad + bc), and eager fuses multiply-adds after its last whole AVX512 vector, so the tests compare it within a tolerance. Complex inputs, constants, outputs and other complex operators are refused; - the four float8 formats are typed, and only their conversions and the operators that move entries without reading them are imported; any other float8 operator and float8_e8m0fnu are refused. A conversion to a float8 format rounds once, also from binary64, where eager rounds through binary32, and the conversion to float8_e4m3fn first clamps to [-448, 448], as PyTorch's saturating conversion does; - leaky_relu as `Op.leakyReLU` and elu at unit scales as `Op.elu`, so their pullbacks at 0 are PyTorch's; softplus and elu with other scales stay their kernels' selections; - a torch.export graph that holds a grad-mode region is refused, not traced symbolically; a decomposed program, where detach_ no longer appears, carries a `decomposed_program` constraint; - state export resolves a lazily negated tensor before reading its words (PR #40). Linear algebra: QR, pivoted QR, LU, eigh, eig, SVD, Schur, real Schur, Hessenberg, tridiagonal reduction and tridiagonal solves, specified as relations, with existence proofs. No theorem links these relations to the seven IR programs above. Roundoff: `#roundoff_coverage` reuses a theorem with the same statement instead of declaring another, and `every M` registers the public functions of the modules under M whose result is a scalar or a tensor, so the 45 functions of TorchLean.NN.RL and TorchLean.NN.Optimizer are analyzed. The baseline is regenerated: 2805 rows, 332 proved, 1232 conditional, 1169 unsupported and 72 failed (main: 2517 rows, 175, 972, 1325 and 45). No row of main is removed. `Op.gelu` [tanh backward] configured absolute goes from conditional to failed, and `Op.attentionFromScores` [forward] mixed from 1 premise to 4. The 184 rows of the reinforcement-learning and optimizer functions are new, and 20 of them fail: 13 over the heartbeat budget, among them the policy KL divergences, 6 of `RL.DQN.loss` at its cast and 1 of `RL.Tabular.qLearningTarget` at its match. The symbolic bounds of rows that stay proved or conditional are not compared with main's. 29 rows of 45b43c6's baseline (Op.conv, Op.convTranspose, Op.cat, Op.indexAt, Op.gather, Op.topk) change only their hashes; their status, premises, terms and values are the same. Reduction orders: `Tensor.ReduceOrder` is a binary tree over a reduction's start value and its entries, and `reduceIn` (sum, product, max, min), `sumIn`, `dotIn`, `meanIn`, `contractIn`, `matmulIn`, `poolIn` (sum and average pools), `scanIn` (cumulative sums and products) and `einsumIn` reduce in such an order, with the orders `leftFold`, `pairwise` and `blocked w`. In `leftFold` each is the existing definition (the `_leftFold` theorems), and over the reals every order that covers each entry once gives the same value. An ordered sum with a finite result in an IEEE format of FloatLib's configured binary arithmetic differs from the exact sum by at most `((1 + u) ^ d - 1)` times the sum of the absolute values, with `d` the tree's depth, which is at most `⌈log₂ (n + 1)⌉` for the pairwise order. No bound covers ordered products or the mean's division. The operator table, the IR, the wire format and the importers carry no order: their reductions mean the left fold, and no backend is proved to reduce in any order. IR flows: `IR.Flow` adds branches and loops over straight-line graphs: `cond`, which runs only the selected branch (the last for an index out of range), `scan`, and `whileLoop`, whose fuel is a parameter of the total `Flow.eval`, on blocks of a language `Flow.Lang m` in a monad `m`. For every language and flow, a `scan` of `n` equals its body unrolled `n` times (`Flow.eval_scan`). For every language in `Except String`, such as graphs' (`Flow.graphs`) and `Flow.Reals.lang`, and every flow, `cond` equals evaluating every branch and selecting one wherever every branch is defined (`Flow.eval_cond`), and a `while` loop that stops after `k` iterations equals its body unrolled `k` times when `k` is at most its fuel (`Flow.eval_whileLoop`). Typed programs (`Flow.programs`) run in `StateT ConversionStatus (Except String)` and merge the conversion flags of every block they run: for them only `Flow.eval_scan` is proved. The `cond` equation is not, and fails where an unselected branch raises a conversion flag that the selected one does not, since evaluating every branch merges the flags of all of them. - A second wire format, the flow artifact (`IR.FlowArtifact`, version 1, `Flow.formatVersion`, under the same format name `torchlean.ir`, told apart from a flat artifact, which has no version of its own, by its `"flow"` key), holds a fuel and a flow whose blocks are typed artifacts. The states between blocks hold no constant: each block that reads one holds it, and no other block does, so a weight that both branches of a `cond` read is written twice. `IR.loadFlow` loads a document as a flow of typed programs, with `declared_types` per block, and `IR.load` refuses one. The checker runs a document's flow by `Flow.eval` in typed programs (`Flow.programs`). Its `structure` and `types` findings also check that the flow's blocks compose (`Capture.flowTypes`): each block is given values its arguments read, each `cond` selects by a scalar index, integer or Boolean, and each loop's test returns one scalar Boolean, in every typing that some path through the flow's branches and loop iterations gives its state, whether or not a run takes that path; values that come straight from the flow's arguments are left to execution. No theorem relates this check to `Flow.eval`. - The JAX importer lowers control flow by partial evaluation first. A `scan` is its body once per iteration, each iteration's counter a constant, or, where its body holds a flow and no iteration would decide at capture how a value it reads is lowered, one `Flow.scan` of its body, as `lax.fori_loop`'s is where its counter decides no `cond`, which reads and writes its rows at a counter by the `Op.gather` and `Op.scatter` of PyTorch's `map`, so its document is the size of one iteration at 100,000 of them; that region is a trial, which is dropped for the unrolled scan wherever carry known at capture, or computed from such carry, may decide a value it found unknown, wherever it draws from `rng_uniform`, and wherever it is refused or fails while it is built, so building it adds no refusal (one that `_flow.lower` then refuses would not be retried; none is known); a `cond` whose index is known at capture is the branch it selects; and a `while` loop whose test reads only values known at capture (constants and the integer and Boolean values folded from them, through `jax.jit` calls too) is its body once per iteration, counted by running the test and the parts of the body it reads with JAX, at most 65,536 iterations unrolled per import in all (a dropped scan trial gives back what it counted), and no step for a loop that runs none. So a branch or loop body that never runs is not imported, and may hold what the importer refuses. Only a `cond` or `while` that the capture does not decide, or a loop past that count, is a flow, and a scan is one `Flow.scan` only where its body holds such a flow; floating arithmetic is not folded, so a `while` whose test reads a floating value that the loop computes is a flow even where constants alone give that value. `scripts/checks/ir_capture_jax_decided.py` holds 29 control-flow examples that the importer decides whole; a test checks that their documents have no flow and match, digest for digest, those of an importer that lowered control flow only by unrolling (`ir_capture_jax_decided.json`). A JAX `cond` whose index depends on the inputs and that gives a returned value is a flow, so its document is a flow artifact, which `IR.load` refuses and `IR.loadFlow` loads. A JAX `scan` of length zero, which the importer refused, is its carry and stacked outputs without rows. Before a flow is written, both importers drop every node, `cond` and `while` that gives no value the program returns, as JAX's dead-code elimination does, so no block is without outputs, and a dropped node that would fail at execution, such as an integer division by zero, or a dropped loop that would not stop, no longer fails; a flow that stays keeps all of its results. A computation none of whose flows gives a returned value, such as a `cond` whose branches return nothing, is the artifact of its other nodes that give one, without a flow. Where the capture decides all control flow, the artifact keeps every node, used or not, as before. Both importers write a region's parts as a `seq` of the flows of its first and second halves, so an unrolled scan of 1,000 iterations with a `cond` in each nests a few levels, within the recursion limit of Python's `json` and `copy.deepcopy`. - The PyTorch importer writes flows for torch.export's `torch.cond` on a predicate not known at capture, `while_loop` and a `map` whose body does not draw from TorchLean's generator. In a flow, a `cond` runs only the selected branch, and a loop's body is in the artifact once. A `while` loop runs at most the artifact's fuel of iterations each time it is entered, 65,536 unless the `fuel` of `export_torchlean_graph_json` (or JAX's `jaxpr.export`) names another, and fails at execution where its test still holds then. A `torch.cond` on a predicate known at capture is the branch it selects, without a flow, and only that branch is checked, so the other may hold what the capture refuses, as an unselected JAX branch may. Loop arithmetic is IEEE 754's: a binary32 value halved from 2^-126 while it is positive stops after 24 iterations, where XLA's CPU code, which flushes subnormals to zero, stops after 1, and jnp.gcd of vectors whose lanes stop at different iterations and jnp.lcm(0, 0) fail at execution, at a remainder by zero that a select discards. The body of a JAX `while` that the capture does not decide, and of a `while_loop`, draws the same entries in every iteration, since a flow's region is one set of nodes, each drawing under a key of its own, where XLA's and PyTorch's stateful generators draw new ones; the iterations of an unrolled scan draw under keys of their own, and a PyTorch `map` whose body draws (`rand`, `randn`, `randperm`, dropout in training) is unrolled for that reason. Each lowering of a PyTorch graph draws under keys of its own, its dropout masks too, as at two calls of a function that PyTorch 2.11 exports as one `invoke_subgraph` graph. A JAX document with a flow has no `computation`, `jit_computations` or `primitive_index`, since XLA's CPU code is emulated only for artifacts without control flow, so a mismatch there fails without the `consistent_with` advice. - Flows of blocks of real sums, products, negations, constants and comparisons (`Flow.Reals.lang`) have derivatives and roundoff bounds. `Flow.Reals.dual_follows`: wherever a flow's run in the dual language succeeds, the flow near the point takes its branches, each of its loops returns what its body unrolled as often as the dual's loop runs returns, and it has its values and Fréchet derivatives there. `Flow.Reals.rounded_follows`: wherever its run with each constant, sum and product rounded by an `rnd` with an error bound succeeds, the exact flow takes the same branches, each of its loops returns what its body unrolled as often as the rounded loop runs returns, and its reals are within the carried bounds. `Flow.Follows.whileLoop` does not state that the exact loop's test fails after that many iterations. FloatLib's `roundAt` is such an `rnd`; it has no largest exponent, so overflow is not covered. The theorems for any two related languages are in `TorchLean/NN/IR/Flow/Follows.lean`. Flows of imported graphs have neither, since no theorem relates a graph's forward-mode rules to a derivative or bounds a graph's rounding error. - `TorchLeanTest/IR/Flow.lean` checks Euclid's algorithm and its branches and loops as flows of graphs and with 13 checks of 12 capture documents, four of them flows whose blocks do not compose, and the capture tests compare JAX and PyTorch control flow with the frameworks on CPU and compile the Lean module exported for a PyTorch flow capture and for a flat one. The transformer block's rounding bound, `Arithmetic.sqrt_sum_sq_block_sub_le`, is a bound of its own schedule `Arithmetic.block`, not of the executed block: that layer norm takes the variance of the unscaled centered entries and that linear map starts its sum from the bias, where `Tensor.layerNorm` rescales by `Tensor.normalizationScale` and `Linear.forward` adds the bias last. Only the exact real functions are tied to the op table. Also: - `Op.fma`, which no frontend produces yet; - `Op.sort` takes an element type, so the wire format is version 4 and no version 3 record decodes any more; - the policy KL divergences use the expm1x form of Amos (2026, section 4.1), centered at the largest log-ratio and proved equal to the textbook sum over the reals. `klFromLogits` centers a quarter of each logit vector before the difference, takes the old weights from the log-softmax, no longer takes `epsilon` and clamps nothing. The log-sum-exp normalizer is kept as two parts, so binary32 `klFromLogits [0, -2^27] [0, 0]` is log 2. The shift d and the old log-probabilities l are summed once, as (d - t) + l with t the largest entry of d + l, and each term's exponent subtracts the largest entry of that sum, so binary32 `klFromLogits [0, -384, -2^33] [0, 2^33, 2^32]` is 2^33 and `[0.5625, 0, -2^26]` against `[0.5625, 2.25, -2^25]` is about 0.4737, where two other orders of the exponent gave infinity and about -0.214. In floating point it is tested on the tests' inputs only, not proved: binary32 `klFromLogits [0, 0] [-2^127, 2^127]` is 2^127, and its docstring states the logit range, old logits at most the largest finite value apart, argues that each term's exponent is at most about log 2 there, and states two limits of rounding the shift between the logit vectors, which the tests check: `[0, 1]` against `[2^-26, 1]` gives 0 (the divergence is about 2.2e-17), and against `[0, 5]` (about 5.0067) `[0, -2^24]` gives about 4.0181 and `[0, -2^100]` gives log 2; the 0.4737 above is the second limit (the divergence is about 0.5896); - `IsCholesky` requires a positive diagonal, as torch.linalg.cholesky's factor has; - the roundoff coverage restores a private matcher's splitter and equations from the matcher they belong to; - duplicate definitions and theorems removed, unused imports removed, linter findings fixed, and docstrings added; - the docs, the guide and the site updated. Changed or deleted public statements: `klFromLogits`'s signature; `index_of_outs`, replaced by `not_isScalar_of_outs`; 153 generated coverage theorem names, whose statements stay under the other route's name; `releaseCUDABuffer` and `releaseSparseBuffer`; 16 lemmas no longer `@[simp]`; `VPSchedule.alphaBar_zero`, now `sched.alphaBar 0 = 1`; `IsCholesky`, now with `∀ i, 0 < L i i`; `Op.sort`, now with an element argument, and `Op.Wire.formatVersion`, now 4; `SpecialFn.smoothDomain`, no longer empty for igamma, igammac, zeta and betainc; the nine instances `Op.Capability.rounding` to `Op.Capability.fma`, now the one instance `Op.Capability.present`; `Flow.Lang`, now `Flow.Lang m β V`, its `run`, `index` and `test` in a monad `m`, and `Flow.eval`, `evalBranch`, `condAll`, `holds`, `iterate`, `runWhile`, `holdsOf`, `pick`, `iterate_eval` and `eval_scan`, now in any monad `m` with `MonadExcept String m` (`Except String` gives the former), and `Flow.eval_cond`, `eval_whileLoop` and `evalBranch_eq_pick`, now stated for a `Lang (Except String) β V`; `IR.mapM_eq_ok_iff` and `IR.exists_mapM_eq_ok`, replaced by Batteries' `List.mapM_eq_ok_iff_forall₂` and `List.exists_mapM_eq_ok_iff`; `IR.Program.checkDeclared` and `Program.checkDeclared_ok`, replaced by `IR.checkDeclared` and `IR.checkDeclared_ok` over a list of blocks; `IR.Declared`, now with the field `block`, whose `Declared.ofJson` reads a `"block"` key on any document's entry (an entry without it names block 0; on a flat document only block 0 passes `IR.checkDeclared`); `IR.load_eq_ok`, restated with `IR.checkDeclared`; `JAX.load`, now returning a flow and its fuel, and `JAX.load_ok`, now stated per block; `Capture.compareFinding`, now taking an optional trace instead of the program, payload, arguments and steps; `Capture.execute`, now running the document's flow (`IR.loadFlow`, `Flow.programs`), so `checkError_sound` and `checkPrediction_sound` keep their text but are about that run. For a document without a flow, `Capture.execute_of_flat` states that it is the former run, `IR.load` and then `Program.eval`. `IR.table`, the op table the Python captures read, has a new field `flow_version` (`Flow.formatVersion`).
Robertboy18
added a commit
that referenced
this pull request
Nov 20, 2026
Lean v4.36.0, Mathlib v4.36.0 and FloatLib 4.1.0 (tag v4.1.0, fc2fad1f). The guide (home_page/blueprint) and the Python bindings still pin Lean 4.35 and FloatLib acba2057 while requiring TorchLean at `../..`, so neither builds against this commit until VersoBlueprint and nerodia have 4.36 versions. Special functions: - `Op.special` and the family `SpecialFn n`: erfc, erfcx, erfinv, ndtr, ndtri, lgamma, digamma, the Bessel functions J0, J1, I0, I1, I0e and I1e, the spherical j0, igamma, igammac, zeta and betainc, defined from Mathlib's functions. They have operator certificates, derivative certificates where the function is differentiable, roundoff registration, and import from torch.special and from lax. - They are specified over the reals only. No binary format executes them, none of their roundoff analyses is better than `unsupported`, and no test compares their values with PyTorch or JAX. Each member's derivative certificate applies on its proved smooth domain (`SpecialFn.smoothDomain`): for igamma and igammac where both arguments are positive, for zeta where s > 1 and q > 0, and for betainc where a and b are positive and x is in (0, 1). These are not the largest such sets: zeta at q <= 0 and the boundaries are not covered. - frexp, in the formats whose exponents fit its int32 word. JAX import (167 of JAX 0.11.1's 219 lax primitives): - complex values as their real and imaginary parts, with real, imag, conj, fft, reductions, sorts and scans, and the complex functions below; - the internals eval_jaxpr, linear_call, remat_opt and call_hi_primitive as calls of their bodies, name, sharding_constraint, reshard and layout_constraint as their operand, tie as its second operand, dce_sink as nothing, and empty and empty2 as zeros; six other internals are refused, each with its reason; - cumlogsumexp, stack, unstack, approx_top_k, select_and_scatter_add, select_and_gather_add, ragged_dot_general, scaled_dot and rng_uniform; - cond, scan and while, lowered by partial evaluation (below): what is decided at capture as straight-line steps, and a cond or while that the capture does not decide as one of the IR's flows, so a loop's trip count can depend on the inputs; - sorts of several operands and the total-order comparisons; an integer or Boolean key is sorted at its own element, so it is not converted to binary64 and a 64-bit key is not split; - the four float8 formats: sums, differences and products rounded once in the format, and the other operations imported at float8 in binary32 and rounded once to the format, atan2 and pow in binary64. For the 20 elementary functions a test checks this at every word of each format, and for atan2 and pow at every pair of words; no theorem proves it; - triangular_solve, cholesky, cholesky_update, householder_product, ormqr, lu_pivots_to_permutation and tridiagonal_solve as IR programs. Where JAX and StableHLO differ, the import follows StableHLO: - select_and_scatter_add is StableHLO's operation on the operand, not the expand_padding lowering that JAX registers for CPU and GPU, so with padding the two can differ; - clamp is `min (max x lo) hi`, not JAX's documented case form, at a NaN bound, at x = -0 or where lo > hi; - ragged_dot_general's free-axis mode selects each position's group, TorchLean's reading where JAX documents only the shapes, so an infinity in another group does not reach it. None of them is refused. PyTorch capture (151 of PyTorch 2.13's 160 core ATen operators): - torch.export's torch.cond, while_loop and map as the IR's flows (below), and invoke_subgraph inlined, which only torch 2.11's tests exercise, since 2.13 inlines it itself; - convolution, linear and normalization weights not known at capture; - the default graph's T, mT, mH, adjoint, swapdims, movedim, rsub, silu as `Op.silu`, stack, repeat_interleave, roll, tril, triu, detach_ and detach as `Op.detach`, device moves, copy_, scatter_ and scatter_add_; - index_add, index_copy and their in-place forms of a fresh destination (a binary16 index_add of a matrix or higher rounds each step, where eager's CPU kernel sums in binary32); unbind; Tensor.unfold as strided slices; linalg_vector_norm; linspace and logspace of constant arguments; created tensors of one value (zeros, ones, full and their forms) as one word broadcast to the shape; - an operator without a lowering of its own whose CPU kernel is its CompositeImplicitAutograd composite (einsum, outer, type_as, expand_as among them) as that composite, when the composite itself imports and its value is a tensor: item stays refused; - transposed convolutions (conv_transpose1d, 2d and 3d, groups, output_padding) as the convolution at stride 1 of the input spread with zeros, by the kernel with each group's channel axes swapped and its spatial axes reversed. The spread zeros multiply the kernel, where eager adds only the input entries' products, so an infinite or NaN kernel entry gives NaN where eager can be finite, and a test pins that difference. Its sums round in the IR convolution's order, not eager's, so the tests compare integer data, as for convolutions; - the dtype arguments of sum, prod, mean, cumsum, cumprod, softmax and log_softmax as a cast first, as their docstrings state. Eager mean to binary16 or bfloat16 from another type rounds once instead, and a test pins that difference; - binary16 and bfloat16 sum and mean as a binary32 accumulation rounded once, as ATen's CPU kernel computes them, and a binary16 or bfloat16 vector norm in binary32; prod rounds each step in the format, as eager does; - the stable sort of integer and Boolean tensors, through `Op.sort` at an element type; - integer and Boolean values through the runtime gathers (index, index_select, gather, take_along_dim) and the writes that replace (index_put without accumulate, index_copy, scatter of a tensor); the writes that sum and scatter of a Python value stay floating; - complex64 and complex128 values as their real and imaginary parts on a last axis of 2, through rfft, irfft, view_as_complex, view_as_real, real, imag, slices, selects, unsqueeze, view and reshape. The quotient by a nonzero finite real number is c10::complex's division, equal to eager word for word in the tests; the product of two complex tensors is (ac - bd, ad + bc), and eager fuses multiply-adds after its last whole AVX512 vector, so the tests compare it within a tolerance. Complex inputs, constants, outputs and other complex operators are refused; - the four float8 formats are typed, and only their conversions and the operators that move entries without reading them are imported; any other float8 operator and float8_e8m0fnu are refused. A conversion to a float8 format rounds once, also from binary64, where eager rounds through binary32, and the conversion to float8_e4m3fn first clamps to [-448, 448], as PyTorch's saturating conversion does; - leaky_relu as `Op.leakyReLU`, elu at every scale and input scale, selu and celu as `Op.elu`, which takes PyTorch's `scale` and `input_scale`, and softplus at every beta and threshold through `Op.softplus`, so their pullbacks at 0 are PyTorch's and no activation stays its kernel's selection; - empty, empty_strided and their variants as the values PyTorch documents for deterministic algorithms (NaN at a floating dtype, else the dtype's largest value), as_strided as the storage words it reads, and zero_ and fill_ of a fresh destination; - batch norm with running statistics that the capture does not hold (graph inputs or computed values), and `_native_batch_norm_legit` in both modes; group norm, training batch norm and layer norm at a negative or NaN eps; - a torch.export graph that holds a grad-mode region is refused, not traced symbolically; in a decomposed program, detach (`aten.alias` from detach) is `Op.detach`, and the `decomposed_program` constraint names only the dropped detach_; - state export resolves a lazily negated tensor before reading its words (PR #40). Normalization: every normalization (layer, RMS, group and batch norm, with batch or running statistics) divides by the IEEE root of `var + eps` as it stands, as PyTorch does, where the root was clamped at zero. In an IEEE format a negative or NaN `var + eps` gives NaN, as in PyTorch; over the reals the root is 0 there. Complex functions: `Op.complex f` applies one of 18 functions (exp, expm1, log, log1p, sqrt, rsqrt, the trigonometric and hyperbolic functions and their inverses) to each entry of a complex tensor stored as its real and imaginary parts, and `Op.complexPow` gives the principal power of two complex tensors; JAX's lax functions, pow and exp2 on complex operands import as them. Their rules read a tenth optional capability, `Op.Capabilities.complex?`, whose instances are the principal values over the reals (`ComplexFn.value`, Mathlib's derivatives) and FloatLib's `ExecComplex` in the configured binary formats; `Float` and `Float32` have none. The derivative certificates hold on one set per function, the complex plane off its branch cut for the ten with a logarithm or root, and `Op.complexPow`'s where the base entries are in the slit plane. In every IEEE configured format each part of an entry of `Op.complex` is FloatLib's exact part rounded once where the entry is finite and off the points FloatLib's proofs leave out (`Op.complex_forward_round`), and that exact part is the principal value off the cut at every sign bit, and on the cut where the sign bits select the side whose limit the principal value is. No theorem bounds the error of their binary derivatives, and their 232 roundoff rows are unsupported: the analysis has no numerical rule for `ExecComplex`'s operations. Complex logistic, cumlogsumexp, argmax, argmin, clamp and atan2 stay refused. reduce_precision: a finite result of the four conversions that the JAX import emits (to a wide format, to the narrow one, and back) is the operand rounded once to the narrow format (`toReal_reduce`; `toReal_reduce_float8` for the float8 route, whose narrower-exponent range step is covered only by its parts). That the import emits these conversions is tested, not proved. Linear algebra: QR, pivoted QR, LU, eigh, eig, SVD, Schur, real Schur, Hessenberg, tridiagonal reduction and tridiagonal solves, specified as relations, with existence proofs. No theorem links these relations to the seven IR programs above. Roundoff: `#roundoff_coverage` reuses a theorem with the same statement instead of declaring another, and `every M` registers the public functions of the modules under M whose result is a scalar or a tensor, so the 45 functions of TorchLean.NN.RL and TorchLean.NN.Optimizer are analyzed. The baseline is regenerated: 3649 rows, 386 proved, 1561 conditional, 1614 unsupported and 88 failed (main: 2517 rows, 175, 972, 1325 and 45), 612 of them in a reduction order (below). No row of main is removed and none has a lower status. Two rows of `Op.elu` have one premise more, a finite intermediate in forward absolute and a finite input in [backward 0] mixed, since the input is scaled by `input_scale`. The 184 rows of the reinforcement-learning and optimizer functions are new, and 17 of them fail: 10 over the heartbeat budget, among them the policy KL divergences in the configured scalar, 6 of `RL.DQN.loss` at its cast and 1 of `RL.Tabular.qLearningTarget` at its match. With FloatLib 4.1.0, seven native `Float32` routes that ran out of heartbeats stop at an operation without a numerical rule, four of them unsupported on main too and three of the KL divergences. The symbolic bounds of rows that stay proved or conditional are not compared with main's. 29 rows of 45b43c6's baseline (Op.conv, Op.convTranspose, Op.cat, Op.indexAt, Op.gather, Op.topk) change only their hashes; their status, premises, terms and values are the same. Reduction orders: `Tensor.ReduceOrder` is finite data, `leftFold`, `pairwise`, `blocked w` or a given tree `ofTree t`, that gives for each count of entries a tree over a reduction's start value and its entries, and it covers `n` entries when that tree holds the start value and each entry once. `reduceIn` (sum, product, max, min), `sumIn`, `dotIn`, `meanIn`, `contractIn`, `matmulIn`, `batchMatmulIn`, `poolIn` (sum and average pools), `scanIn` (cumulative sums and products), `cummaxIn`, `cumminIn`, `Attention.scaledMatmulIn` and `einsumIn` reduce in such an order. In `leftFold` each is the existing definition at every scalar (the `_leftFold` theorems). Over the reals every covering order gives the left fold's value, and the running maxima and minima give the left fold's values and indices in every covering order, also bit for bit in every configured binary format, NaN and signed zeros included (`ConfiguredBinary.cummaxIn_eq`, `cumminIn_eq`). - Ten operators of the op table take an order last, `.leftFold` by default: `reduce`, `mean`, `contract`, `matmul`, `scaledMatmul`, `pool`, `cumsum`, `cumprod`, `cummax` and `cummin`. `Op.check` refuses an order that does not cover the count reduced (`Op.checkOrder_eq_ok`), and in the left fold each operator has its rule from before orders (`Op.rule?_reduce_leftFold` and the others). Over the reals, for every graph and input, a graph that evaluates gives the same outputs with every order set to the left fold (`IR.Graph.eval_leftFold_real`). The forwards, and the tangents of sums, means, contractions, matrix products and cumulative sums, are computed in the order; the pullbacks and the other tangents are the left fold's in every order. The derivative certificates of the ten are stated at a variable order that covers the count. - The wire format is version 5: the records of the ten end with their order. The IR's JSON writes it as `{"order": O}` with `O` one of `"leftFold"`, `"pairwise"`, `{"blocked": w}` and `{"tree": t}`, and both round trips are proved for every order. The PyTorch, JAX and ONNX importers write the left fold, and the PyTorch exporter refuses every other order. CROWN, the numerical certificates' range transfers and the LibTorch kernels take the left fold only, so an operator in another order has no box, transfer or kernel. - Roundoff, in every IEEE format of FloatLib's configured binary family: a finite ordered sum differs from the exact sum by at most `((1 + u) ^ d - 1)` times the sum of the absolute values, with `d` the depth of the order's tree, at most `⌈log₂ (n + 1)⌉` in `pairwise` (`abs_ordered_sum_sub_le`, `abs_pairwise_sum_sub_le`, `abs_blocked_sum_sub_le`); an ordered product rounds once per entry, so its relative error is the left fold's `(1 + u) ^ n - 1` and only its absolute error from underflow follows the tree; on finite entries an ordered maximum or minimum has the real value of the left fold, though a stored zero's sign can differ; and a running maximum or minimum is its input at the index the order selects. The baseline's 612 rows in the orders `pairwise`, `blocked ?width` and `ofTree ?tree` each have the status of the operator's left-fold row. - The deterministic CUDA sum's schedule is the order `LibTorch.sumOrder n`, and `reduceSumTree_eq_fold` proves that its Lean evaluation is that order's fold for every input list. That the native kernel follows the schedule is tested on fixtures, not proved, and no backend is proved to reduce in any order. IR flows: `IR.Flow` adds branches and loops over straight-line graphs: `cond`, which runs only the selected branch (the last for an index out of range), `scan`, and `whileLoop`, whose fuel is a parameter of the total `Flow.eval`, on blocks of a language `Flow.Lang m` in a monad `m`. For every language and flow, a `scan` of `n` equals its body unrolled `n` times (`Flow.eval_scan`). For every language in `Except String`, such as graphs' (`Flow.graphs`) and `Flow.Reals.lang`, and every flow, `cond` equals evaluating every branch and selecting one wherever every branch is defined (`Flow.eval_cond`), and a `while` loop that stops after `k` iterations equals its body unrolled `k` times when `k` is at most its fuel (`Flow.eval_whileLoop`). Typed programs (`Flow.programs`) run in `StateT ConversionStatus (Except String)` and merge the conversion flags of every block they run: for them only `Flow.eval_scan` is proved. The `cond` equation is not, and fails where an unselected branch raises a conversion flag that the selected one does not, since evaluating every branch merges the flags of all of them. - A second wire format, the flow artifact (`IR.FlowArtifact`, version 1, `Flow.formatVersion`, under the same format name `torchlean.ir`, told apart from a flat artifact, which has no version of its own, by its `"flow"` key), holds a fuel and a flow whose blocks are typed artifacts. The states between blocks hold no constant: each block that reads one holds it, and no other block does, so a weight that both branches of a `cond` read is written twice. `IR.loadFlow` loads a document as a flow of typed programs, with `declared_types` per block, and `IR.load` refuses one. The checker runs a document's flow by `Flow.eval` in typed programs (`Flow.programs`). Its `structure` and `types` findings also check that the flow's blocks compose (`Capture.flowTypes`): each block is given values its arguments read, each `cond` selects by a scalar index, integer or Boolean, and each loop's test returns one scalar Boolean, in every typing that some path through the flow's branches and loop iterations gives its state, whether or not a run takes that path; values that come straight from the flow's arguments are left to execution. No theorem relates this check to `Flow.eval`. - The JAX importer lowers control flow by partial evaluation first. A `scan` is its body once per iteration, each iteration's counter a constant, or, where its body holds a flow and no iteration would decide at capture how a value it reads is lowered, one `Flow.scan` of its body, as `lax.fori_loop`'s is where its counter decides no `cond`, which reads and writes its rows at a counter by the `Op.gather` and `Op.scatter` of PyTorch's `map`, so its document is the size of one iteration at 100,000 of them; that region is a trial, which is dropped for the unrolled scan wherever carry known at capture, or computed from such carry, may decide a value it found unknown, wherever it draws from `rng_uniform`, and wherever it is refused or fails while it is built, so building it adds no refusal (one that `_flow.lower` then refuses would not be retried; none is known); a `cond` whose index is known at capture is the branch it selects; and a `while` loop whose test reads only values known at capture (constants and the integer and Boolean values folded from them, through `jax.jit` calls too) is its body once per iteration, counted by running the test and the parts of the body it reads with JAX, at most 65,536 iterations unrolled per import in all (a dropped scan trial gives back what it counted), and no step for a loop that runs none. So a branch or loop body that never runs is not imported, and may hold what the importer refuses. Only a `cond` or `while` that the capture does not decide, or a loop past that count, is a flow, and a scan is one `Flow.scan` only where its body holds such a flow; floating arithmetic is not folded, so a `while` whose test reads a floating value that the loop computes is a flow even where constants alone give that value. `scripts/checks/ir_capture_jax_decided.py` holds 29 control-flow examples that the importer decides whole; a test checks that their documents have no flow and match, digest for digest, those of an importer that lowered control flow only by unrolling (`ir_capture_jax_decided.json`). A JAX `cond` whose index depends on the inputs and that gives a returned value is a flow, so its document is a flow artifact, which `IR.load` refuses and `IR.loadFlow` loads. A JAX `scan` of length zero, which the importer refused, is its carry and stacked outputs without rows. Before a flow is written, both importers drop every node, `cond` and `while` that gives no value the program returns, as JAX's dead-code elimination does, so no block is without outputs, and a dropped node that would fail at execution, such as an integer division by zero, or a dropped loop that would not stop, no longer fails; a flow that stays keeps all of its results. A computation none of whose flows gives a returned value, such as a `cond` whose branches return nothing, is the artifact of its other nodes that give one, without a flow. Where the capture decides all control flow, the artifact keeps every node, used or not, as before. Both importers write a region's parts as a `seq` of the flows of its first and second halves, so an unrolled scan of 1,000 iterations with a `cond` in each nests a few levels, within the recursion limit of Python's `json` and `copy.deepcopy`. - The PyTorch importer writes flows for torch.export's `torch.cond` on a predicate not known at capture, `while_loop` and a `map` whose body does not draw from TorchLean's generator, and the body of a `map` may hold a `torch.cond` or `while_loop` of its own. In a flow, a `cond` runs only the selected branch, and a loop's body is in the artifact once. A `while` loop runs at most the artifact's fuel of iterations each time it is entered, 65,536 unless the `fuel` of `export_torchlean_graph_json` (or JAX's `jaxpr.export`) names another, a Python or numpy integer that is not negative, and fails at execution where its test still holds then. A `torch.cond` on a predicate known at capture is the branch it selects, without a flow, and only that branch is checked, so the other may hold what the capture refuses, as an unselected JAX branch may. Loop arithmetic is IEEE 754's: a binary32 value halved from 2^-126 while it is positive stops after 24 iterations, where XLA's CPU code, which flushes subnormals to zero, stops after 1, and jnp.gcd of vectors whose lanes stop at different iterations and jnp.lcm(0, 0) fail at execution, at a remainder by zero that a select discards. The body of a JAX `while` that the capture does not decide, and of a `while_loop`, draws the same entries in every iteration, since a flow's region is one set of nodes, each drawing under a key of its own, where XLA's and PyTorch's stateful generators draw new ones; the iterations of an unrolled scan draw under keys of their own, and a PyTorch `map` whose body draws (`rand`, `randn`, `randperm`, dropout in training) is unrolled for that reason. Each lowering of a PyTorch graph draws under keys of its own, its dropout masks too, as at two calls of a function that PyTorch 2.11 exports as one `invoke_subgraph` graph. A JAX document with a flow has no `computation`, `jit_computations` or `primitive_index`, since XLA's CPU code is emulated only for artifacts without control flow, so a mismatch there fails without the `consistent_with` advice. - Flows of blocks of real sums, products, negations, constants and comparisons (`Flow.Reals.lang`) have derivatives and roundoff bounds. `Flow.Reals.dual_follows`: wherever a flow's run in the dual language succeeds, the flow near the point takes its branches, each of its loops returns what its body unrolled as often as the dual's loop runs returns, and it has its values and Fréchet derivatives there. `Flow.Reals.rounded_follows`: wherever its run with each constant, sum and product rounded by an `rnd` with an error bound succeeds, the exact flow takes the same branches, each of its loops returns what its body unrolled as often as the rounded loop runs returns, and its reals are within the carried bounds. `Flow.Follows.whileLoop` does not state that the exact loop's test fails after that many iterations. FloatLib's `roundAt` is such an `rnd`; it has no largest exponent, so overflow is not covered. The theorems for any two related languages are in `TorchLean/NN/IR/Flow/Follows.lean`. Flows of imported graphs have neither, since no theorem relates a graph's forward-mode rules to a derivative or bounds a graph's rounding error. - `TorchLeanTest/IR/Flow.lean` checks Euclid's algorithm and its branches and loops as flows of graphs and with 13 checks of 12 capture documents, four of them flows whose blocks do not compose, and the capture tests compare JAX and PyTorch control flow with the frameworks on CPU and compile the Lean module exported for a PyTorch flow capture and for a flat one. The transformer block's rounding bound, `Arithmetic.sqrt_sum_sq_block_sub_le`, is a bound of its own schedule `Arithmetic.block`, not of the executed block: that layer norm takes the variance of the unscaled centered entries and that linear map starts its sum from the bias, where `Tensor.layerNorm` rescales by `Tensor.normalizationScale` and `Linear.forward` adds the bias last. Only the exact real functions are tied to the op table. Also: - `Op.fma`, which no frontend produces yet; - `Op.sort` takes an element type and ten operators an order, so the wire format is version 5 and no record of an earlier version decodes any more; - the policy KL divergences use the expm1x form of Amos (2026, section 4.1), centered at the largest log-ratio and proved equal to the textbook sum over the reals. `klFromLogits` centers a quarter of each logit vector before the difference, takes the old weights from the log-softmax, no longer takes `epsilon` and clamps nothing. The log-sum-exp normalizer is kept as two parts, so binary32 `klFromLogits [0, -2^27] [0, 0]` is log 2. The shift d and the old log-probabilities l are summed once, as (d - t) + l with t the largest entry of d + l, and each term's exponent subtracts the largest entry of that sum, so binary32 `klFromLogits [0, -384, -2^33] [0, 2^33, 2^32]` is 2^33 and `[0.5625, 0, -2^26]` against `[0.5625, 2.25, -2^25]` is about 0.4737, where two other orders of the exponent gave infinity and about -0.214. In floating point it is tested on the tests' inputs only, not proved: binary32 `klFromLogits [0, 0] [-2^127, 2^127]` is 2^127, and its docstring states the logit range, old logits at most the largest finite value apart, argues that each term's exponent is at most about log 2 there, and states two limits of rounding the shift between the logit vectors, which the tests check: `[0, 1]` against `[2^-26, 1]` gives 0 (the divergence is about 2.2e-17), and against `[0, 5]` (about 5.0067) `[0, -2^24]` gives about 4.0181 and `[0, -2^100]` gives log 2; the 0.4737 above is the second limit (the divergence is about 0.5896); - `IsCholesky` requires a positive diagonal, as torch.linalg.cholesky's factor has; - the roundoff coverage restores a private matcher's splitter and equations from the matcher they belong to, and keeps a binder of a generated theorem only where its statement or proof uses it, so 390 of the 1512 configured theorems hold at every format, OCP's E4M3 included; - a `softmax_bound` tactic proves the online softmax bounds, `op_deriv` proves 21 more derivative certificates, and the CROWN transfers and node enclosures are proved once per family; - duplicate definitions and theorems removed, primed names dropped, unused imports and arguments removed, the variables of iff lemmas made implicit, linter findings fixed, large modules shrunk, and docstrings added; - the docs, the guide and the site updated. Changed or deleted public statements: `klFromLogits`'s signature; `index_of_outs`, replaced by `not_isScalar_of_outs`; 153 generated coverage theorem names, whose statements stay under the other route's name; `releaseCUDABuffer` and `releaseSparseBuffer`; 16 lemmas no longer `@[simp]`; `VPSchedule.alphaBar_zero`, now `sched.alphaBar 0 = 1`; `IsCholesky`, now with `∀ i, 0 < L i i`; `Op.sort`, now with an element argument, and `Op.Wire.formatVersion`, now 5; `Op.reduce`, `mean`, `contract`, `matmul`, `scaledMatmul`, `pool`, `cumsum`, `cumprod`, `cummax` and `cummin`, now with an order last, and their derivative certificates, now at a covering order; `ReductionPolicy.fixedLeft` and `fixedLeftOrExact`, now `fixed order` and `fixedOrExact order`; `SpecialFn.smoothDomain`, no longer empty for igamma, igammac, zeta and betainc; the nine instances `Op.Capability.rounding` to `Op.Capability.fma`, now the one instance `Op.Capability.present`; `Flow.Lang`, now `Flow.Lang m β V`, its `run`, `index` and `test` in a monad `m`, and `Flow.eval`, `evalBranch`, `condAll`, `holds`, `iterate`, `runWhile`, `holdsOf`, `pick`, `iterate_eval` and `eval_scan`, now in any monad `m` with `MonadExcept String m` (`Except String` gives the former), and `Flow.eval_cond`, `eval_whileLoop` and `evalBranch_eq_pick`, now stated for a `Lang (Except String) β V`; `IR.mapM_eq_ok_iff` and `IR.exists_mapM_eq_ok`, replaced by Batteries' `List.mapM_eq_ok_iff_forall₂` and `List.exists_mapM_eq_ok_iff`; `IR.Program.checkDeclared` and `Program.checkDeclared_ok`, replaced by `IR.checkDeclared` and `IR.checkDeclared_ok` over a list of blocks; `IR.Declared`, now with the field `block`, whose `Declared.ofJson` reads a `"block"` key on any document's entry (an entry without it names block 0; on a flat document only block 0 passes `IR.checkDeclared`); `IR.load_eq_ok`, restated with `IR.checkDeclared`; `JAX.load`, now returning a flow and its fuel, and `JAX.load_ok`, now stated per block; `Capture.compareFinding`, now taking an optional trace instead of the program, payload, arguments and steps; `Capture.execute`, now running the document's flow (`IR.loadFlow`, `Flow.programs`), so `checkError_sound` and `checkPrediction_sound` keep their text but are about that run. For a document without a flow, `Capture.execute_of_flat` states that it is the former run, `IR.load` and then `Program.eval`. `IR.table`, the op table the Python captures read, has a new field `flow_version` (`Flow.formatVersion`). `Op.elu`, now with `scale` and `input_scale`; `Op.Capabilities`, now with a tenth field `complex?`; the `.running` arm of `Tensor.batchNorm` and the standard deviations of the normalizations, now without the clamp; `Normalization.normalize_full` and `ApproxTensor.sqrt_of_pos_lb`, removed; CROWN's `invoke_one` to `invoke_four`, now cases of `invoke_ok`, with `read_cons` and `read_nil` moved to `TorchLean.CROWN.Op`.
Robertboy18
added a commit
that referenced
this pull request
Nov 21, 2026
Move the library, guide, site, and Python bindings to Lean 4.36, Mathlib 4.36, and FloatLib 4.1.0. Extend JAX and PyTorch graph import with structured control flow, explicit reduction orders, more linear algebra and dtype coverage, and wire format version 5. Strengthen the operator, gradient, and numerical proof layers, and revise the public documentation and examples. Resolve lazily negated PyTorch tensor words reported in PR #40. Co-authored-by: Vel <110626982+Code4me2@users.noreply.github.com>
Member
|
Thanks again, @Code4me2—this was a real bug, and both the fix and regression test were exactly right. The change is now on main in the Lean 4.36 release, including coverage for lazily negated values and negative zero. The release commit also credits your contribution. Really appreciate the careful work! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
A conjugated complex scalar’s imaginary component is a real float32 tensor with a lazy negative bit. Making it contiguous does not clear that bit, so reinterpreting it as an integer fails during state export. Resolve negation before the word view in the shared encoder.
The PyTorch-only regression checks exact state words for -2 and negative zero. Both subcases raised RuntimeError before the fix and pass after it (PyTorch 2.10.0, CPU). Ran
python scripts/checks/test_ir_capture.py; checker-dependent tests were skipped.