Skip to content

feat(kernel): convert between scalars and indices in custom computations - #44

Draft
NicolasRouquette wants to merge 7 commits into
lean-dojo:mainfrom
NicolasRouquette:kernel-index-conversion
Draft

NicolasRouquette wants to merge 7 commits into
lean-dojo:mainfrom
NicolasRouquette:kernel-index-conversion

Conversation

@NicolasRouquette

@NicolasRouquette NicolasRouquette commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • 9c49ded3 the change described below;
  • b4ba2b2d runs the device pass of KernelIndex only 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's
    host 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 weight u - ⌊u⌋, which needs the index back as a scalar:

  • Expr.toIndex : Expr α Γ .scalar → Expr α Γ .index
  • Expr.ofIndex : Expr α Γ .index → Expr α Γ .scalar

Semantics

They are two new fields of Arithmetic, which Arithmetic.ofOps takes from a small class IndexCast, so they are fixed by the arithmetic like + and <:

scalar type toIndex ofIndex
Float32, Float Lean's toUInt64: truncation toward zero, saturated to the UInt64 range, 0 at a NaN and below zero UInt64.toFloat32, UInt64.toFloat: nearest, ties to even
configured binary the same rule, from the exact value (ExecFloat.Binary.toInt?) the model's NatCast (one nearest-even rounding, the format's overflow convention)
ℝ (proofs) realToIndex: the floor, clamped to the UInt64 range the natural number

Program.of recognizes Float32.toUInt64, Float.toUInt64, UInt64.toFloat32, UInt64.toFloat and the generic IndexCast.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.Regular gains one condition: no scalar converted to an index is an integer. Under it, Expr.exists_hasFDerivAt_tangent and the gradient theorems hold as before.

The toIndex case is the compare case'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 on propext, Classical.choice and Quot.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 give 0 at a NaN: on SM 8.6 a NaN round trip came back as 2^63, which is how the test first failed. An index converts with __ull2float_rn / __ull2double_rn. Configured formats convert in TLBinary::toIndex / TLBinary::ofIndex in csrc/libtorch/binary.h, built from the template's own significand, scale and round.

docs/TRUST_BOUNDARIES.md and the kernel README say what is trusted.

Tests

TorchLeanTest/CUDA/KernelIndex.lean, in the suite on the CPU and on CUDA:

  • the conversions at NaN, ±∞, negative values, signed zeros, fractions, 2^24 + 1, 2^63, the largest binary32 below 2^64, 2^64 and beyond, observed rounded back to a scalar and through the index modulo 7 (which keeps its low bits exact);
  • ofIndex over a pseudorandom sweep of the UInt64 range and at the ties near 2^24 and 2^53;
  • ten configured formats (e4m3 in all four encodings, e5m2, binary16, bfloat16, configured binary32/64, binary128) on boundary and pseudorandom words;
  • the table lookup of feat(libtorch): piecewise-linear table lookup composed from float32 primitives #34 as one 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_suite and TORCHLEAN_LIBTORCH_DEVICE=cpu TORCHLEAN_REQUIRE_NATIVE=1 nn_tests_suite both end with == TorchLean: all curated tests passed ==, and scripts/lake.sh lint gives No findings. and the 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 main without this change, with no conversion in the program:

  1. A scalar let bound to an if and then used does not certify:
    let lo := if u < 0 then 0 else u; pure (lo + 1) fails with Program.of: could not certify source equivalence; case h_1, leaving the hypothesis heq✝ : (if v✝ < 0 then Except.ok 0 else Except.ok v✝) = Except.error err✝.
  2. An if directly in the else of another if fails with Tactic `simp` failed with a nested error: maximum recursion depth has been reached, also under set_option maxRecDepth 8192.

The lookup in the test is written around them: one if per arm, the second after a bind. I can open an issue for them if that is useful.

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 added a commit to NicolasRouquette/TorchLean that referenced this pull request Nov 23, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant