Repository navigation
feat(kernel): convert between scalars and indices in custom computations - #44
Draft
NicolasRouquette wants to merge 7 commits into
Draft
NicolasRouquette wants to merge 7 commits into
NicolasRouquette wants to merge 7 commits into
Conversation
The LibTorch bridge runs on a CUDA device or on the host, through ATen's CPU kernels. The device is selected once: TORCHLEAN_LIBTORCH_DEVICE=cpu selects the host and =cuda a CUDA device; unset, a visible CUDA device, and the host only with a CPU-only SDK. A CUDA-enabled SDK without a visible device stays nativeUnavailable. - CMake: an SDK without torch_cuda builds with TORCHLEAN_LIBTORCH_CUDA=0, without USE_CUDA, the CUDA toolkit, NVRTC or the driver. - kernels.cpp and the caching-allocator calls compile for a CUDA SDK only; generated kernels call require_cuda and fail through IO on the host, and so does the encoded upload of configured binary arithmetic. - axpy and the ordered segment sums, reached from pure entry points, have host loops with the kernels' fma and summation order. - Tree folds and unfolds take their host references unless a CUDA device is selected (Buffer.cudaAvailable). - Lean: LibTorch.DeviceKind, deviceKind, Buffer.requireCudaDevice. The suite's TORCHLEAN_REQUIRE_CUDA=1 requires a CUDA device, and TORCHLEAN_REQUIRE_NATIVE=1 the bridge on any device. - TRUST lists CUDA C Shims and CUDA Unstable Remainder; libtorch_abi.py expects them exactly when the library links libtorch_cuda.so.
ATen's CPU log1p of torch 2.13 returns zero at the least subnormal of binary32 and binary64, which lost the combined tail of the two-level cross-entropy normalizer on the host. The bridge's log1p returns x on the host wherever |x| < 2^-p, where x is the correctly rounded value; CUDA's log1p is unchanged. requireNativeRuntime reports why the bridge selected no device (an unknown TORCHLEAN_LIBTORCH_DEVICE, or =cuda with a CPU-only SDK) through torchlean_libtorch_unavailable_reason, and keeps its message when no CUDA device is visible.
On the host, generated kernels and configured-binary recordings are checked to be refused through IO (KernelGradient, Elementwise), the native memory probes are replaced by a check that the allocator statistics read zero (Stress), and the graph checks of configured words and custom operations run on CUDA only (Graph). Every other check runs on both devices.
The backend README gains a Host device section: the selection table, what runs, what is refused and the log1p repair. scripts/README.md, TorchLeanTest/README.md, the tree README and the CUDA page describe TORCHLEAN_REQUIRE_NATIVE=1 and the CPU-only SDK build.
A custom computation can now read an input at a position it computes from its inputs. `Expr.toIndex` converts a scalar to a `UInt64` index and `Expr.ofIndex` an index to a scalar, by two new fields of `Arithmetic` that `Arithmetic.ofOps` takes from the class `IndexCast`: - `Float32` and `Float` use Lean's `toUInt64` (truncation toward zero, saturated to the `UInt64` range, zero at a NaN and below zero) and `UInt64.toFloat32` / `UInt64.toFloat` (nearest even); - configured binary formats convert from their exact value (`ExecFloat.Binary.toInt?`) and round with the model's `NatCast`; - over the reals an index is the floor of its scalar, clamped to the `UInt64` range. `Program.of` recognizes these functions. Every existing theorem covers the new constructors: lowering, emission and its text grammar, tangent, gradient, map and hylo. `Expr.Regular` gains one condition, that no integer is converted to an index, and the derivative theorems hold under it: away from the integers the floor does not change nearby, and the scalar of an index has the tangent zero. Native CUDA converts a scalar with the guards of Lean's runtime (`lean_float32_to_uint64`) around `__float2ull_rz` / `__double2ull_rz`, which on their own do not give zero at a NaN, and an index with `__ull2float_rn` / `__ull2double_rn`. The configured template converts in `TLBinary::toIndex` and `TLBinary::ofIndex`. `TorchLeanTest/CUDA/KernelIndex.lean` checks the conversions at the values where their rules differ, a sweep of the `UInt64` range, the ties near 2^24 and 2^53 and ten configured formats, and the interpolation of a coordinate into a uniform table with its value and both gradients, exact on dyadic inputs. On CUDA every result has the bits of the CPU run.
On the host bridge a generated kernel is refused, so the device run of the index checks failed there. The CPU run of the same checks already runs in every build, and the refusal itself is checked once.
NicolasRouquette
force-pushed
the
kernel-index-conversion
branch
from
November 23, 2026 16:49
f161dae to
b4ba2b2
Compare
NicolasRouquette
added a commit
to NicolasRouquette/TorchLean
that referenced
this pull request
Nov 23, 2026
…rnel-index-conversion, lean-dojo#44)
This branch has not been deployed
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.
Depends on #43
This branch is based on #43 (the bridge on the host), so until #43 merges the diff here also shows
#43's five commits. This PR's own commits are the last two:
9c49ded3the change described below;b4ba2b2druns the device pass ofKernelIndexonly when the bridge is on a CUDA device. On Run the LibTorch bridge on the host when the SDK is CPU-only (#36, reimplemented) #43'shost bridge a generated kernel is refused, and without this the suite stopped with
libTorch: a generated kernel needs a CUDA device, but the bridge runs on the host (a CPU-only SDK, or TORCHLEAN_LIBTORCH_DEVICE=cpu).The CPU pass of the same checks runs in every build.
What
This implements option 1 of Issue#42: the kernel language gets conversions between scalars and indices, so a custom computation can read an input at a position it computes from its inputs, without a round trip to the host.
It turned out to need two constructors, not the one #42 described. Interpolation needs the segment
⌊u⌋as an index and its weightu - ⌊u⌋, which needs the index back as a scalar:Expr.toIndex : Expr α Γ .scalar → Expr α Γ .indexExpr.ofIndex : Expr α Γ .index → Expr α Γ .scalarSemantics
They are two new fields of
Arithmetic, whichArithmetic.ofOpstakes from a small classIndexCast, so they are fixed by the arithmetic like+and<:toIndexofIndexFloat32,FloattoUInt64: truncation toward zero, saturated to theUInt64range,0at a NaN and below zeroUInt64.toFloat32,UInt64.toFloat: nearest, ties to evenExecFloat.Binary.toInt?)NatCast(one nearest-even rounding, the format's overflow convention)ℝ(proofs)realToIndex: the floor, clamped to theUInt64rangeProgram.ofrecognizesFloat32.toUInt64,Float.toUInt64,UInt64.toFloat32,UInt64.toFloatand the genericIndexCast.toIndex/IndexCast.ofIndex.Proofs
Every theorem over
Expr,Target, the named statements and the emitted text covers the two constructors (lowering,Primitive.Denotes, tangent, gradient,map,readsBelow).Expr.Regulargains one condition: no scalar converted to an index is an integer. Under it,Expr.exists_hasFDerivAt_tangentand the gradient theorems hold as before.The
toIndexcase is thecomparecase's argument: by continuity the argument stays strictly between two integers nearθ₀, so its floor, and the index, do not change. The scalar of an index has the tangent zero.lake lint: the theorems still depend only onpropext,Classical.choiceandQuot.sound.Native code and the template
Native kernels convert a scalar with the guards of Lean's runtime (
lean_float32_to_uint64),0 <= x ? (x < 2^64 ? __float2ull_rz(x) : 2^64 - 1) : 0. The bare intrinsic does not give0at a NaN: on SM 8.6 a NaN round trip came back as2^63, which is how the test first failed. An index converts with__ull2float_rn/__ull2double_rn. Configured formats convert inTLBinary::toIndex/TLBinary::ofIndexincsrc/libtorch/binary.h, built from the template's ownsignificand,scaleandround.docs/TRUST_BOUNDARIES.mdand the kernel README say what is trusted.Tests
TorchLeanTest/CUDA/KernelIndex.lean, in the suite on the CPU and on CUDA:2^24 + 1,2^63, the largest binary32 below2^64,2^64and beyond, observed rounded back to a scalar and through the index modulo 7 (which keeps its low bits exact);ofIndexover a pseudorandom sweep of theUInt64range and at the ties near2^24and2^53;Program.of: value at interior, integral, boundary, out-of-range and NaN coordinates, the gradient in the coordinate (the segment's slope, zero outside the grid) and the gradient in the table (the interpolation weights), exact on dyadic inputs, in binary32 and binary64.On CUDA every result has the bits of the CPU run. On
b4ba2b2d, with an RTX A4500 (SM 8.6), torch 2.13.0+cu130 and CUDA 13.0:TORCHLEAN_REQUIRE_CUDA=1 nn_tests_suiteandTORCHLEAN_LIBTORCH_DEVICE=cpu TORCHLEAN_REQUIRE_NATIVE=1 nn_tests_suiteboth end with== TorchLean: all curated tests passed ==, andscripts/lake.sh lintgivesNo findings.andthe 29380 theorems of 1020 modules depend on at most propext, Classical.choice and Quot.sound.Two frontend limits I met, outside this PR
Both reproduce on
mainwithout this change, with no conversion in the program:letbound to anifand then used does not certify:let lo := if u < 0 then 0 else u; pure (lo + 1)fails withProgram.of: could not certify source equivalence; case h_1, leaving the hypothesisheq✝ : (if v✝ < 0 then Except.ok 0 else Except.ok v✝) = Except.error err✝.ifdirectly in theelseof anotheriffails withTactic `simp` failed with a nested error: maximum recursion depth has been reached, also underset_option maxRecDepth 8192.The lookup in the test is written around them: one
ifper arm, the second after a bind. I can open an issue for them if that is useful.