返回资讯中心
外部精选
软件工程
#开发者实时流

Writing Tensor Programs in Lean · TorchLean Verified Examples

Robert Joseph George · TorchLean Verified Examples

Hacker News 最新matt_d2026/10/15 · 2026/10/1530 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

Robert Joseph George · TorchLean Verified Examples

I've wanted to use TorchLean for calculations that don't need a neural-network model around them. If I'm experimenting with an activation or repeating an update in a simulation, I'd like to write that function in Lean and choose CPU or GPU when I run it. I also want to be able to prove something about the function I wrote.

The tensor library already gives us operations on shaped tensors, automatic differentiation (autograd), and FloatLib's numerical formats. Autograd records the operations and intermediate values needed to propagate derivatives backward; I'll call that recording a tape below. I've been working on connecting custom functions to those pieces. We can now compile supported Lean functions for GPU execution and use them through the tensor API.

A GPU is useful when a calculation has lots of independent work. Applying the same update to a million starting values gives us a million computations we can run alongside one another. Within each computation, however, the next update may depend on the previous one. We need a way to express both the independent work and that dependency without maintaining another version of the function in CUDA.

Lean gives us an interesting place to do this. It is a functional programming language as well as a theorem prover, so we can write the calculation, evaluate it, and prove a statement about its definition. I want those activities to feel like parts of the same project. The GPU compiler adds another question we can state precisely: does the lowered program still compute the function we wrote?

Let's try it with a repeated update, a custom loss, and a row sum. Then we'll write matrix products and attention with einsum, compose a model, and look at what takes time when we run it. I also want to show the precision and higher-derivative work, because those features change which calculations we can write, not only how we spell them.

Functional programming has a long history of treating a collection of calculations as a program the compiler can transform. In Accelerate, we write array computations inside Haskell using operations such as maps and reductions. Its backends compile those computations for a target device. The distinction between the host language and the embedded array program matters: an ordinary Haskell function doesn't become a GPU program merely because we use Accelerate.

Futhark's introduction gives a motivation I share:

Because it's nicer than writing CUDA or OpenCL by hand!

Here we can also write a theorem about the function before and after lowering it. That connection is what I want to keep as we make the compiler more useful.

Futhark takes a different approach, with a functional array language designed for GPU compilation. Its work on nested parallelism asks how a compiler can expose useful parallel work while retaining efficient loops and updates. A short functional expression can describe many calculations, but the compiler still has to decide how to organize them on the machine.

Dex is particularly relevant to tensor programming. It makes indices part of how we write array computations and studies differentiation that preserves their parallel structure. Indices tell us which entries a calculation reads and which outputs it produces. That is useful information for both a compiler and a proof.

Bend exposes parallel work through functions too. Its parallel-call model lets a programmer split independent calls and run them through a CPU/GPU runtime. It has a broader goal than our current tensor compiler, including recursive data and divide-and-conquer programs. Our custom path starts with tensor entries and ordered numerical loops.

Bend also uses affine ownership: an ordinary value can be used at most once, unless it is explicitly reusable. That restriction helps control sharing and updates. It is a different design choice from adding a tensor compiler to Lean; we aren't introducing an affine language or replacing Lean's runtime here.

Our starting point is the tensor system and certified einsum compiler we already have, which connects a generated computation to reference semantics. We want to extend that approach to functions users write themselves. Mathlib supplies the mathematics we can reuse for proofs, and FloatLib lets us describe the arithmetic rather than assume that a floating-point calculation is an exact real-number one.

That numerical support is also a concrete difference from Bend's current implementation: its documented limitations describe native F32 arithmetic as axiomatic. FloatLib supplies executable arithmetic with correctness and rounding theorems. Connecting those theorems to a foreign GPU implementation is further work, but we already have the numerical definitions to make the question precise. I wouldn't infer a speed advantage from that difference; execution speed needs a matched experiment.

import NN.Kernel

open TorchLean

def square {α : Type} [Mul α] (x : α) : α := x * x def input : Tensor Float32 [3] := [1, 2, 3]

-- The device belongs to the call, so the function stays unchanged. def onGpu : IO (Tensor Float32 [3]) := square.run input (device := gpu) #eval square.run input (device := cpu)

Lean output[1.000000, 4.000000, 9.000000]

The answer is [1, 4, 9]. Each output needs only its corresponding input, so the three calculations are independent. A tensor with a million entries would expose the same kind of work. The shape stays where it belongs, on the tensor: squaring a matrix replaces each entry in the same row and column. We can use this function on different tensor shapes without naming a new operation for every rank.

The definition also leaves the number type open. In the code, α is the type of an entry, and [Mul α] asks for multiplication on that type. The input chooses Float32 for this example. Later we'll use a wider FloatLib format, keeping the same multiplication expression.

We choose cpu or gpu when we run the function. CPU evaluates the Lean calculation. The custom GPU path recognizes supported arithmetic, produces a checked representation, and generates CUDA. NVIDIA's NVRTC compiles that source at runtime. We can keep the function itself free of a device choice.

A square is a small place to start, but the reason for having this interface is to let the body grow. Local bindings, arithmetic comparisons, and supported conditionals can be part of the function. We should be able to try a calculation before deciding it deserves a permanent name in the library.

An update often needs two inputs: a previous estimate and a new observation, or two fields we want to interpolate. Let's blend corresponding entries with a weight of one quarter:

import NN.Kernel

open TorchLean

def blend (weight left right : Float32) : Float32 := (1 - weight) * left + weight * right

def left : Tensor Float32 [3] := [0, 4, 8] def right : Tensor Float32 [3] := [8, 4, 0]

#eval (blend 0.25).zip left right def gpuBlend : IO (Tensor Float32 [3]) := (blend 0.25).zip left right (device := gpu)

Lean output[2.000000, 4.000000, 6.000000]

For the first pair, three quarters of zero plus one quarter of eight gives two. The middle pair stays at four, and the last pair gives six. Changing the weight changes that calculation; it doesn't require a new function named after a particular coefficient.

Both inputs have shape [3]. The type of .zip requires the shapes to agree, so it doesn't truncate one input to the other's length or choose broadcasting we didn't request. The result keeps that shared shape. A tensor of another rank can use the same scalar blend.

The weight is shared by all entries. For GPU compilation, a captured scalar such as this weight becomes a constant in the generated source. Changing it can require recompilation; the runtime reuses identical source through its cache. Frequently changing per-entry values can instead arrive through tensor inputs. This is an execution choice worth understanding before using a small example in a longer loop.

Now repeat the update (x\mapsto x^2+1). Starting at one, the first update gives two, the second gives five, and the third gives twenty-six. Starting at two gives a different history. Neither history needs to read the other.

Move the slider back to zero: the output is the starting value. At two updates, the outputs are five and twenty-six. This is also how we define the recurrence in Lean:

import NN.Kernel

open TorchLean

-- Keep the element type general; the step needs multiplication and addition. def evolve {α : Type} [One α] [Mul α] [Add α] (x : α) : Nat → α | 0 => x | n + 1 => let previous := evolve x n previous * previous + 1

def starts : Tensor Float32 [2] := [1, 2] def evolution (steps : UInt64) (device : NN.Backend.Device := cpu) := (fun x => evolve x steps.toNat).run starts (device := device)

#eval evolution 2

-- Recording visits both updates, so backward includes both local derivatives. #eval do let result ← (fun (x : Float32) => evolve x 2).run starts (grad := true) IO.println (← result.backward)

Lean output[5.000000, 26.000000]

[8.000000, 40.000000]

The zero case returns the input. The successor case computes the previous result, then squares it and adds one. Writing recursion makes the dependency explicit: the new value comes from the old one. We haven't created a separate implementation for GPU.

For a forward-only GPU call, the frontend uses the recurrence's zero and successor equations to derive an ordered loop. It constructs a Lean proof that the loop agrees with those equations. The body isn't copied into the generated program once for every update. Increasing the count gives the loop more work to do.

This also makes the available parallelism clear. A thousand starting values can evolve independently, but ten updates of one value form a dependency chain. A compiler cannot run the second update before it knows the first result. Some recurrences admit more elaborate parallel algorithms; using one would require showing that its reorganized computation has the meaning we intend.

The recognized recursion currently keeps its parameters fixed and recurses on the predecessor of its final natural-number argument. The call passes a UInt64 count converted to a natural number, giving the GPU loop a bounded count without truncating an arbitrary Nat. Tree recursion and dynamically allocated recursive structures remain outside this path. Ordinary CPU Lean can express a much larger range of programs.

Those boundaries are why I find the connection to functional GPU languages useful. Parallelizing a collection of ordered updates is one kind of problem. Scheduling a recursive tree whose branches have different amounts of work is another. The tensor interface gives us a good starting point for the former; it doesn't automatically solve the latter.

The square recurrence grows quickly. Let's try an update with a useful numerical purpose: move part of the remaining distance to a target. If the current value is zero, the target is two, and we move halfway each time, the first three values are one, one and a half, and one and three quarters.

import NN.Kernel import Mathlib.Tactic.Ring

open TorchLean

-- Move a fraction of the remaining distance to the target at each step. def relax {α : Type} [Add α] [Sub α] [Mul α] (rate target x : α) : Nat → α | 0 => x | n + 1 => let previous := relax rate target x n previous + rate * (target - previous)

def initial : Tensor Float32 [3] := [0, 2, 4] def approach (steps : UInt64) (device : NN.Backend.Device := cpu) : IO (Tensor Float32 [3]) := (fun x => relax (0.5 : Float32) 2 x steps.toNat).run initial (device := device)

#eval approach 3

-- The real error is multiplied by the same factor at every step. example (rate target x : ℝ) (steps : Nat) : relax rate target x steps = target + (1 - rate) ^ steps * (x - target) := by induction steps with | zero => simp [relax] | succ steps ih => rw [relax, ih, pow_succ] ring

Lean output[1.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →