Formal Verification of GPU Kernels: PTX Semantics in Lean, TensorLean, and Why Fast Attention Kernels Hide Bugs
A FlashAttention-4 data race passed 17,760 test runs before a proof caught it. That figure comes from the TensorLean project, a Columbia University and CertiK effort announced on 20 November 2026. It is the sharpest argument yet that formal verification of GPU kernels has moved from academic curiosity to production necessity. The team reports checking 149 compiled kernel instances from FlashAttention, DeepGEMM and other libraries. It proved 83 of them correct and found 38 previously unknown bugs in the rest.
This matters now because attention and GEMM kernels sit under every frontier model, and AI agents are starting to write new kernels faster than humans can review them. A kernel that silently corrupts a KV cache produces no crash, only wrong tokens.
You will leave with a working mental model of why GPU kernel correctness is so hard to test. You will also see what a Lean formalisation of PTX actually proves, what it trusts, and a practical testing baseline you can run today.
What this covers: the TensorLean results, the PTX memory model, existing tools, the proof-versus-testing cost trade-off, a buggy CUDA example and a differential-testing harness in Python.
Context and Background
GPU kernels are small programs with enormous blast radius. A single fused attention kernel runs billions of times a day across training clusters and inference fleets. If you need a refresher on how those kernels are scheduled onto hardware, our walkthrough of CUDA kernel execution and data starvation covers the execution model this post assumes.
The industry has historically trusted these kernels through three mechanisms. First, unit tests compare outputs against a slow PyTorch reference with torch.allclose. Second, dynamic tools such as NVIDIA’s Compute Sanitizer catch out-of-bounds accesses and shared-memory hazards at runtime. Third, mass deployment acts as an informal test: if millions of users run a kernel, surely someone would notice a bug.
Each mechanism has a blind spot. Unit tests only check the shapes someone thought to write down. Sanitizers only observe the schedules that actually happened during one run. Mass deployment detects crashes and obvious garbage, but not a 0.3% numerical skew on sequences of length 4,097 with a non-interleaved rotary embedding.
Formal methods for GPU code are not new. GPUVerify, published at OOPSLA 2012 by Betts, Chong, Donaldson, Qadeer and Thomson, statically checked OpenCL and CUDA kernels for data races and barrier divergence. It evaluated 163 kernels using a semantics called synchronous, delayed visibility that reduces verification to analysis of a sequential program. On the memory-model side, Lustig, Sahasrabuddhe and Giroux formalised the NVIDIA PTX memory consistency model at ASPLOS 2019, using Alloy for testing and Coq for a machine-checked proof that a scoped C++ model maps soundly onto PTX (NVIDIA Research).
What changed in 2026 is scale and target. Earlier tools reasoned about source code or small kernels. TensorLean reasons about the compiled PTX of production kernels from FlashAttention-2, -3 and -4, DeepSeek’s DeepGEMM, Liger Kernel, Triton’s kernel library and TileOPs, according to the project page. A separate November 2026 paper from SF Tensor, Formalizing PTX in Lean to Prove GPU Kernel Correctness (arXiv 2611.04447), shows the same direction from a different angle with hand-written PTX and fully manual proofs.
How Formal Verification of GPU Kernels Works in TensorLean
Formal verification of GPU kernels means proving, with a machine-checked argument, that a compiled kernel produces the specified tensor output for every legal input and every thread schedule. TensorLean does this at the PTX level in Lean, checking data-race freedom, termination and functional correctness within an explicit floating-point tolerance.
That definition has three load-bearing phrases. “Every legal input” means the proof quantifies over all tensors satisfying a precondition, not over sampled values. “Every thread schedule” means all interleavings permitted by the PTX memory model, not the handful observed on one GPU. “Within tolerance” means the proof bounds round-off error rather than pretending floats are real numbers.

Figure 1: The TensorLean pipeline. A compiled PTX instance and a tensor-level specification meet in Lean, where concurrency is reduced to a sequential view and remaining goals go to SMT solvers.
The figure reads top to bottom. Kernel source in CUDA C++, CuTe, Triton or TileLang compiles to one PTX entry point per configuration. A parser turns that PTX into terms over a Lean model of PTX semantics. In parallel, the human-written specification is lowered from tensor operations down to byte-level postconditions on GPU memory. The two meet as proof goals, which are discharged either by Lean directly or by the Z3 and cvc5 SMT solvers. A closed proof certifies the instance. A failed goal points at a concrete configuration and input where the kernel diverges.
Specifications are written at the tensor level, not the thread level
The key usability decision is where the specification lives. Writing a thread-level spec for a FlashAttention-3 kernel would mean describing what each of thousands of threads does with each register. Nobody can review that. TensorLean instead lets developers write specs with PyTorch-like operators built on Lean’s Mathlib.
Each specification has five parts according to the project page. spec_math states the mathematical result, such as softmax of scaled Q times K-transpose, times V. spec_mut describes in-place updates. spec_layout maps logical tensors onto physical memory, covering strides, paging and swizzles. spec_tol gives the error budget epsilon. requires states preconditions such as aligned head dimensions. Tensors are classified as input, output or state, where state covers things like a KV cache the kernel updates.
Separating math from layout is the clever part. The math spec for attention is short and reviewable. The layout spec is where real kernels get complicated, and it is exactly where TensorLean found the largest class of bugs. The project reports 10,278 lines of specification covering 151,285 lines of kernel source, roughly a 15-to-1 ratio. For FlashAttention alone, 6,242 spec lines cover 55,910 source lines across 37 kernels.
Concurrency is reduced to a happens-before graph
GPU concurrency is what makes kernels hard to reason about. TensorLean builds a symbolic happens-before graph across all thread blocks (CTAs), threads and loop iterations. Edges come from CTA barriers, mbarriers (the transaction-counting barriers introduced with Hopper) and asynchronous copies such as TMA loads.
If every pair of conflicting memory accesses is ordered by that graph, the kernel is race-free. A race-free kernel can then be analysed as if it executed sequentially, because no observable result depends on interleaving. This is the same intellectual move GPUVerify made in 2012, extended to Hopper and Blackwell synchronisation primitives and applied to compiled code rather than source.
One stated limitation matters here. The project page says TensorLean derives ordering from barriers, mbarriers and async copies, but does not yet model orders that come from acquire/release operations. Kernels that synchronise through atomic flags, which include multi-GPU communication kernels such as NCCL and DeepEP, are out of scope.
Loops and floating point get special treatment
Attention kernels are loops over tiles of keys and values. Proving them correct requires loop invariants, the statements that remain true after every iteration. TensorLean automatically infers invariants for loops that compute over semirings with tiled, accumulative, data-independent control flow. Online softmax is the flagship example. The tool derives closed forms for the running maximum, running sum and partial output, which are exactly the quantities FlashAttention rescales at each step.
Floating point is handled in two stages. First, the tool proves that the kernel, interpreted over real numbers, equals spec_math exactly, with zero algebraic error. Second, it bounds the round-off error of the actual floating-point computation. The triangle inequality combines both into a single “output within epsilon of the spec” theorem. That split keeps the hard algebraic reasoning out of the messy rounding reasoning.
Developers can also insert tensorlean_assert statements as proof hints. Each is proved once and then assumed in later goals. The team reports writing 298 assertions in total across its evaluation, which gives a rough sense of the human guidance still required.
Why Fast Attention Kernels Hide Bugs
The headline numbers are worth restating precisely, because early press coverage disagreed. The project page and the AI Weekly summary of MarkTechPost’s 21 November article both report 149 instances checked, 83 proved correct and 66 instances exhibiting bugs, which together contain 38 distinct bugs. FlashAttention accounted for 102 instances covering all 37 kernels of FlashAttention-2 through -4, with 56 proved and 46 buggy, and 23 bugs. DeepGEMM contributed 2 bugs. HackerNoon’s 20 November article reported “25 bugs”, which matches the FlashAttention plus DeepGEMM subtotal; the remaining 13 sit in the other libraries (our inference from the published numbers, not a breakdown the team has published).

Figure 2: The configuration explosion. One kernel template becomes many distinct compiled programs, and CI typically touches only the common corners.
Figure 2 explains the most important single fact in the results. According to the project page, 19 of the 23 FlashAttention bugs appear only in specific configurations, which checkers that unroll one concrete configuration at a time miss. A “kernel” in a modern library is really a template instantiated across head dimensions, causal and local masking, paged or contiguous KV caches, rotary modes, data types and GPU architectures. Each instantiation compiles to a different PTX program. A bug in one instance tells you nothing about its siblings.
The bug taxonomy
TensorLean’s figure of bug classes is the most useful artefact for practitioners, because it tells you where to point your own tests. Bugs can fall into several categories, so the counts below sum to more than 38.
| Bug class | Count | What it looks like |
|---|---|---|
| Memory access errors | 19 | Wrong layout assumption or missing bounds check |
| Numerical bugs | 13 | Insufficient precision or range, overflow, NaN, integer wraparound |
| Data races | 7 | Unordered conflicting accesses between threads or warps |
| Uninitialized memory | 5 | Reading shared memory before it is written, or leaving outputs unwritten |
| Undefined behaviour | 5 | Division by zero, signed overflow, re-initialising an mbarrier |
| Incorrect algorithm | 3 | Wrong formula or condition, unhandled special case |
| Miscompilation | 2 | Correct source compiled into an incorrect executable |
| Deadlock | 1 | Cyclic or unmatched waits, such as from barrier divergence |
Source: TensorLean project page, Figure 8, retrieved 23 November 2026.
Memory access errors dominate. That is consistent with the layout argument above: the arithmetic in attention is well understood, but mapping it onto paged caches, swizzled shared memory and TMA descriptors is where humans slip. The example the team highlighted is “a memory access error causing silent data corruption of KV cache in flash_attn_with_kvcache with non-interleaved rotary”, a routine that sits in the decoding loop of many inference stacks. The team had not published which deployed stacks were affected or whether patches had shipped as of this writing.
The two miscompilations deserve attention too. They are cases where the source was correct and the compiler produced wrong PTX. Source-level verification cannot catch those by construction, which is the strongest argument for verifying the compiled artefact.
Why testing misses these specific classes
Each bug class defeats testing for a mechanical reason.
Data races depend on warp timing. A missing barrier between a producer warp writing a shared-memory tile and a consumer warp reading it only produces wrong output when the consumer runs ahead. On a lightly loaded GPU with a regular schedule, it may never run ahead. Change the clock, the occupancy or the neighbouring kernel and the same code fails. The FlashAttention-4 race that dropped blocks with unmasked keys (upstream issue #3195, per the project page) survived 17,760 test runs.
Tail tiles are the classic shape bug. A kernel tiled in blocks of 128 behaves differently when sequence length is 4,096 versus 4,097. The last tile is partial, so every load and store needs a mask. Tests that use powers of two never exercise that path.
Masking interactions compound tail tiles. Causal masking plus a partial last tile plus paged KV blocks of a different size creates corner cases at the intersection of three independent boundary conditions.
Numerical edge cases hide below tolerance. A bug that introduces a constant 1e-4 bias passes an allclose with atol=1e-3. Overflow in an fp16 accumulator only appears with large-magnitude inputs, and torch.randn rarely produces those.
Uninitialized shared memory often reads zero on a freshly launched kernel, because the previous occupant happened to leave zeros. The bug appears only when a different kernel ran on that SM first.
Undefined behaviour such as re-initialising an mbarrier may work on today’s driver and silicon. The PTX ISA does not promise it will keep working.

Figure 3: The shape of a typical intra-block race. The consumer reads a tile before the producer’s write is ordered before it, so the output depends on warp timing.
Figure 3 is the pattern behind most of the seven races. Nothing crashes. The consumer simply reads stale data from the previous tile, and the output is wrong by an amount that depends on how different consecutive tiles are. For attention, consecutive key tiles are often similar, so the error can be small enough to pass loose tolerances.
The PTX memory model is weaker than most engineers assume
Underneath all of this sits the PTX memory consistency model. Lustig and colleagues describe it as weakly ordered, with scoped synchronisation. Scopes such as CTA, cluster, GPU and system determine which threads a fence or atomic actually synchronises with. Their ASPLOS 2019 paper notes that, unlike some GPU models, PTX does not require programs to be data-race-free to have defined semantics. Racy programs have behaviour, but it is weak and surprising.
Hopper added another wrinkle: proxies. TMA and other asynchronous units access memory through an “async proxy” that is not automatically ordered with ordinary loads and stores through the generic proxy. Getting cross-proxy ordering right requires specific fences. The SF Tensor paper models generic, async and tensormap proxies explicitly, building on Lustig’s model and a later mixed-proxy extension.
The practical consequence is that “I put a __syncthreads() there” is not always sufficient reasoning on Hopper and Blackwell. A TMA write completing into shared memory is tracked by an mbarrier transaction count, not by a CTA barrier. A kernel that mixes the two incorrectly can look synchronised in source and still race. That is exactly the territory where human review, sanitizers and testing are weakest.
Walk-through: The Testing Baseline Before You Reach for Proofs
Proofs are expensive, so the honest starting point is to ask how far conventional tooling gets you. The answer is: further than most teams go, but not all the way. This section builds the baseline every kernel team should already have, then shows exactly where it runs out.
A classic tail and synchronisation bug in CUDA
The kernel below is a deliberately buggy row-wise sum over a shared-memory tile. It contains two of the bug classes from the taxonomy: a missing bounds check on the tail tile and a missing barrier in the reduction loop. It compiles cleanly and passes a naive test.
// Row-wise sum: out[row] = sum_j x[row, j]. One block per row.
// BUGGY on purpose: (1) tail tile not masked, (2) missing barrier in tree reduction.
#define TILE 256
__global__ void row_sum_buggy(const float* x, float* out, int ncols) {
__shared__ float smem[TILE];
const int row = blockIdx.x;
const int tid = threadIdx.x;
float acc = 0.0f;
for (int base = 0; base < ncols; base += TILE) {
// BUG 1: no check that base + tid < ncols.
// When ncols % TILE != 0 the last tile reads past the row,
// into the next row (or past the allocation for the last row).
acc += x[row * ncols + base + tid];
}
smem[tid] = acc;
__syncthreads();
for (int stride = TILE / 2; stride > 0; stride >>= 1) {
if (tid < stride) {
smem[tid] += smem[tid + stride];
}
// BUG 2: missing __syncthreads() here.
// Within one warp the order often works out on today's hardware;
// across warps (stride >= 32) a thread may read smem[tid + stride]
// before another warp has finished writing it.
}
if (tid == 0) out[row] = smem[0];
}
// Fixed version of the two lines:
// if (base + tid < ncols) acc += x[row * ncols + base + tid];
// ... and add __syncthreads(); at the end of each reduction step.
Run this with ncols = 4096 and TILE = 256 and bug 1 never triggers, because 4,096 divides evenly. Bug 2 may also stay silent on a given GPU, because warp scheduling happens to finish writes before reads. A test suite built on round shapes reports green.
Now run the same binary under compute-sanitizer --tool memcheck with ncols = 4100. Memcheck flags the out-of-bounds read on the last row, because it sits past the allocation. On every other row the bad read lands inside the next row’s valid memory. Memcheck cannot know that is semantically wrong, so it stays quiet. Only the final row’s overrun is a “memory error”; the others are silent logic errors.
compute-sanitizer --tool racecheck is better suited to bug 2. Racecheck reports read-after-write, write-after-read and write-after-write hazards on shared memory. NVIDIA’s documentation is explicit that it “only supports detecting accesses to on-chip shared memory” (Compute Sanitizer docs). A race on global memory, or one mediated by TMA writes and mbarriers, is outside its view. Racecheck also reports only hazards on the schedules and inputs exercised in that run.
The other two sanitizer tools round out the set. Initcheck reports reads of uninitialised global memory, and shared memory with --initcheck-address-space shared. Synccheck reports invalid use of __syncthreads(), __syncwarp() and their Cooperative Groups equivalents, including divergence. Synccheck’s own documentation notes it does not detect threads named in a __syncwarp() mask failing to reach the call.
A differential-testing harness that actually hunts corners
The second layer is differential testing: run the kernel and a trusted reference on the same inputs and compare. Most teams already do this badly, with one shape, one dtype and a hand-picked tolerance. The harness below fixes the four weaknesses that the Correctness Illusion paper (arXiv 2606.20128) identified in kernel benchmarks: fixed shapes, fixed dtypes, loose tolerances and too few samples.
import itertools, math, torch
def reference(x: torch.Tensor) -> torch.Tensor:
# Trusted reference in float64 on CPU: slow, simple, obviously correct.
return x.double().cpu().sum(dim=-1)
def boundary_sizes(tile: int, max_mult: int = 4):
# Hit every tile boundary: below, at and just above each multiple.
sizes = {1, 2, tile - 1, tile, tile + 1}
for m in range(2, max_mult + 1):
sizes |= {m * tile - 1, m * tile, m * tile + 1}
return sorted(sizes)
def adversarial_inputs(shape, dtype, device, seed):
g = torch.Generator(device="cpu").manual_seed(seed)
base = torch.randn(shape, generator=g, dtype=torch.float64)
finfo = torch.finfo(dtype)
yield "randn", base
yield "large", base * (finfo.max ** 0.5) # provoke overflow in fp16 paths
yield "tiny", base * finfo.tiny * 4 # subnormal territory
yield "constant", torch.full(shape, 1.0, dtype=torch.float64)
signed_zero = base.clone(); signed_zero[..., ::2] = -0.0
yield "neg_zero", signed_zero
with_nan = base.clone(); with_nan.view(-1)[0] = float("nan")
yield "nan", with_nan # must propagate, not vanish
def tolerance(dtype, n):
# Error budget grows roughly with sqrt(n) for random-sign sums.
# This is a heuristic bound, not a proof: tighten it to your kernel's
# measured error and justify any loosening in code review.
eps = torch.finfo(dtype).eps
return 4.0 * eps * math.sqrt(n)
def check(kernel, tile=256, rows=7, dtypes=(torch.float32, torch.float16, torch.bfloat16),
repeats=5, seeds=range(3), device="cuda"):
failures = []
for dtype, ncols, seed in itertools.product(dtypes, boundary_sizes(tile), seeds):
for name, x64 in adversarial_inputs((rows, ncols), dtype, device, seed):
x = x64.to(dtype).to(device)
ref = reference(x)
outs = [kernel(x).double().cpu() for _ in range(repeats)]
# Nondeterminism across identical launches hints at a race.
if any(not torch.equal(outs[0], o) for o in outs[1:]):
failures.append((dtype, ncols, seed, name, "nondeterministic"))
continue
out = outs[0]
if not torch.equal(torch.isnan(out), torch.isnan(ref)):
failures.append((dtype, ncols, seed, name, "nan mismatch"))
continue
finite = ~torch.isnan(ref)
scale = ref[finite].abs().clamp_min(1.0)
err = ((out[finite] - ref[finite]).abs() / scale).max().item() if finite.any() else 0.0
if err > tolerance(dtype, ncols):
failures.append((dtype, ncols, seed, name, f"rel err {err:.3e}"))
return failures
if __name__ == "__main__":
# Swap in your own launcher; torch.sum stands in so the harness runs anywhere.
fails = check(lambda x: x.float().sum(dim=-1), device="cuda" if torch.cuda.is_available() else "cpu")
print(f"{len(fails)} failing cases")
for f in fails[:20]:
print(f)
Three design choices in this harness matter more than the code itself. Shapes are chosen at tile boundaries rather than randomly, because that is where masking bugs live. Inputs include large, tiny, signed-zero and NaN cases, because numerical bugs hide in exactly those regions. Repeated launches with identical inputs flag nondeterminism, which is the cheapest race detector available. It is not a proof of race freedom, since a race can be deterministic on one GPU, but a mismatch is a strong signal.
The Correctness Illusion author shows why this matters with a seeded experiment. A deliberately buggy Triton softmax failed 13 of 30 randomly sampled cases and 6 of 10 boundary-only cases, yet 0 of 10 regular-shape cases. A team that only tests regular shapes would ship it.
Where Triton’s interpreter fits
If you write kernels in Triton, TRITON_INTERPRET=1 runs them on the CPU using NumPy equivalents of Triton operations, one program instance at a time (Triton debugging guide). You can drop into pdb mid-kernel and inspect tiles. The interpreter is excellent for logic and masking bugs. By construction, though, it cannot surface races, because it executes program instances sequentially. It also lacks bfloat16 and indirect memory access support, according to the same guide. Our Triton GPU kernel programming tutorial covers the block-level masking idioms that the interpreter helps debug.
The tooling ladder, and where each rung stops
Put together, the conventional toolchain looks like this:
| Tool | Finds | Misses | Cost |
|---|---|---|---|
Fixed-shape allclose tests |
Gross algorithm errors | Tail tiles, masks, dtype edges, races | Seconds |
| Boundary differential testing | Most shape and numeric bugs on tested configs | Untested configs, rare schedules | Minutes per config |
| Compute Sanitizer memcheck, initcheck | OOB past allocations, uninitialised reads | In-bounds logical errors, other schedules | 10x to 100x slowdown (varies) |
| Compute Sanitizer racecheck, synccheck | Shared-memory hazards, barrier misuse observed in run | Global and async-proxy races, unobserved schedules | Large slowdown (varies) |
| Triton interpreter | Logic and masking bugs, step-through | Races, bf16, indirect access | Slow CPU execution |
| GPUVerify-style static checking | Races and barrier divergence on source | Functional correctness, compiled code | Minutes, needs annotations |
| PTX-level proof, as in TensorLean | Races, termination, functional correctness within eps, miscompilations | Anything outside the trusted base and model | About 10 min median per instance plus spec writing |
Sanitizer slowdowns are illustrative ranges from general practice, not measured figures for any specific kernel.
The bottom row is the only one that quantifies over all inputs and all schedules. It is also the only one that inspects what the compiler actually produced.
What a Lean Formalisation of PTX Proves, and What It Does Not
A proof is only as strong as the statement it proves and the base it trusts. This is where engineering teams need to read the fine print, not the press release.

Figure 4: Three layers of assurance. Properties in the top layer are proved; the middle layer is trusted; the bottom layer is outside the model entirely.
What is proved
For a closed TensorLean proof, four properties hold for that compiled PTX instance: data-race freedom under the modelled orderings, termination, functional correctness against the specification, and output within the stated tolerance. These hold for every input satisfying requires and every schedule the model permits. That is categorically stronger than any amount of testing.
What is trusted
The project page lists the trusted computing base explicitly, which is to its credit. It includes the following components.
- The specification itself. If
spec_mathsays the wrong thing, the proof certifies the wrong thing. A 15-to-1 compression ratio helps reviewability, but specs still need review. - The PTX model and its 1.8K-line parser. The proof is about TensorLean’s interpretation of PTX. If that interpretation diverges from NVIDIA’s, the proof may not transfer.
- The tensor-core rounding model. The PTX ISA does not specify how tensor cores round intermediate results. TensorLean models it; that model is an assumption.
- NVIDIA’s PTX ISA and ptxas. PTX is a virtual ISA. ptxas lowers it to SASS, the native machine code, which NVIDIA does not fully document.
- Lean’s kernel plus Z3 and cvc5. This is a notable difference from a “pure” Lean development. Proof goals discharged by external SMT solvers are trusted unless the solver’s result is reconstructed and rechecked in Lean.
The SF Tensor paper makes a different trade on that last point. Its proofs are checked in Lean v4.35.0 with Mathlib, with no sorry and no axiom declarations beyond Lean’s standard axioms, confirmed by #print axioms. The cost is effort: 34,034 proof lines for 454 PTX instructions, about 75 lines of proof per instruction, for seven hand-written kernels. Its Hopper WGMMA matmul alone needed 16,973 proof lines for 98 instructions.
What sits outside the model
Neither approach says anything about SASS, silicon or the host. A proof at the PTX level does not cover a ptxas bug. It does not cover silent data corruption from faulty hardware, a real and measured problem in large training fleets. It does not cover the host code that computes launch parameters, allocates buffers or chooses which kernel instance to dispatch.
There are also scoped exclusions in the model itself. TensorLean cannot yet express kernels that sample randomly, such as dropout or top-p sampling, and does not handle atomic-flag synchronisation. The SF Tensor model excludes Blackwell’s tcgen05 instructions, distributed shared memory, non-coherent loads and multi-GPU kernels. It proves partial correctness only, assumes freedom from undefined behaviour rather than proving it, and models floats as exact real numbers.
That last difference is significant. TensorLean bounds round-off and proves termination. The SF Tensor model proves semantic correctness over reals and leaves numerical accuracy and termination out of scope. “Formally verified” therefore means different things in two papers published the same month. Always ask which properties, over which number model.
Spec fidelity is the residual risk
The hardest question is whether the spec matches intent. Consider the cases the Imperial College and Logos Research team documented in Proving LLM-Generated GPU Kernels Correct and Safe (arXiv 2610.24548). Their checker rejected a ReLU kernel that returned -0.0 where the PyTorch reference returns +0.0. It also rejected a softmax using fmaxf, which drops NaNs, where the reference propagates them. Whether those are bugs depends entirely on what the spec says about signed zeros and NaNs. A spec written carelessly over reals would have accepted both.
The Cost of Proof Versus the Cost of Testing
Engineering leaders will ask the obvious question: is this worth it? The answer depends on the arithmetic of blast radius.
TensorLean reports about 10 minutes median verification time per instance on a 16-core workstation. The largest case, FlashAttention-3’s forward kernel on Hopper, generated 31,402 proof goals and took about 50 minutes. Those are machine costs, and they are small. Checking all 149 instances at a 10-minute median is on the order of 25 CPU-hours, a rough estimate since the distribution is skewed. That is less than many GPU CI pipelines burn in a day.
The real cost is human. Someone has to write the 10,278 lines of spec and the 298 proof-hint assertions, and has to understand the failures. That is specialist work, and today it requires people fluent in both Lean and GPU microarchitecture.
Set that against the value side, using a worked illustration rather than real data. Suppose a decoding kernel bug corrupts the KV cache on 0.1% of requests in a fleet serving 100 million requests a day. That is 100,000 subtly wrong responses daily, with no crash and no alert. Discovery might take weeks. The cost includes engineer time to bisect, user trust and possibly a retraining run if the kernel was also used in training. Even at conservative values, one such incident can exceed the cost of a verification engineer for a year. These figures are illustrative, not drawn from any reported incident.
The economics also shift with reuse. FlashAttention and DeepGEMM are upstream dependencies of hundreds of projects. A proof done once upstream protects every downstream user, the same way a verified cryptography library protects every TLS stack that links it.
How This Fits AI-Generated Kernels
The strongest driver for formal verification of GPU kernels is not human-written code. It is agent-written code. Teams increasingly use LLM agents to generate and autotune kernels, and benchmarks like KernelBench measure speedups alongside a correctness check that is usually a fixed-shape comparison.
The Correctness Illusion paper argues that check is far too weak. In its seeded experiments, a stronger oracle caught 9 of 9 buggy kernels that a fixed-shape allclose-style check had passed, with no false positives on 15 correct controls. The paper is explicit that these are seeded bugs modelled on documented LLM patterns, not measured LLM failure rates. Still, the pattern is clear: magnitude-uniform bugs slip under loose tolerances and shape-dependent bugs slip past fixed shapes.
The Imperial and Logos Research paper shows the other half of the loop: agents writing proofs. Across 30 KernelBench problems, an Opus-5-fast pipeline passed both a Lean semantic check and a VerCors thread-safety check on 22 of 30 problems, versus 11 of 30 for GPT-5-fast. The authors stress this was one campaign per model with no variance estimate, so it is not a controlled comparison. It also covers a limited CUDA fragment with transcendental functions treated as opaque symbols.
Put those together and a credible architecture emerges. An agent proposes a kernel. A differential-testing harness rejects obvious failures cheaply. A verifier then attempts a proof against a human-reviewed spec. A failed proof returns a counterexample configuration, which goes back to the agent. The spec, not the kernel, becomes the artefact humans review. The TensorLean team describes the same direction, expecting verification to keep pace with kernel development “with both experts and agents involved.”
This is also where the low-precision trend bites. Formats such as NVFP4 and MXFP4, covered in our NVFP4 vs MXFP4 microscaling explainer, add per-block scale factors and rounding modes that a spec must state precisely. Every new format multiplies the configuration space in Figure 2, and every multiplication weakens sampling-based testing further.
Trade-offs, Gotchas, and What Goes Wrong
Formal verification is not a silver bullet, and the TensorLean results themselves show the failure modes.
Incompleteness is real. The project page says the tool is sound but may fail on correct kernels. Causes include missing input constraints in the spec, overly conservative round-off bounds and SMT timeouts. Some of the 66 non-proved instances could, in principle, be false alarms of this kind. The team says those 66 instances contained 38 real bugs, but an engineer triaging a failed proof must still decide whether the kernel or the proof attempt is wrong.
Proofs are per instance. Each compiled configuration is a separate PTX program. A proof for head dimension 128 on Hopper says nothing about head dimension 96 on Blackwell. Libraries with combinatorial template expansion will need either proof reuse across instances or a policy that ships only verified instances.
Proofs go stale. Every kernel change, compiler upgrade or PTX ISA revision can invalidate a proof. Verification has to run in CI like any other check, which means the 50-minute worst case and the spec maintenance burden become ongoing costs, not one-time ones.
Rounding models are assumptions. The tolerance proof is only as good as the tensor-core rounding model, which NVIDIA does not specify in the PTX ISA. If a future GPU rounds differently, the bound may not hold, even though the proof still checks.
Fast paths escape scope. Exactly the kernels with the most aggressive synchronisation, such as atomic-flag communication kernels for multi-GPU expert parallelism, are currently out of scope. Teams should not let a “verified” badge on attention lull them into assuming the whole inference stack is covered.
Spec review is the new code review. A wrong spec yields a proof of the wrong property. Specs need the same scrutiny as security policies, with explicit decisions about NaN propagation, signed zeros, masked-out positions and empty sequences.
Press numbers drift. Within three days of the announcement, coverage reported both “25 bugs” and “38 bugs”. Both are traceable to the same data, but only if you read the primary source. As of 23 November 2026 the full paper had not been posted, and the repository at github.com/TensorLean/TensorLean was described as the future home of the semantics, specs and proofs. Treat the numbers as author-reported until peer review and maintainer confirmation.
Practical Recommendations
Most teams will not write Lean specs next quarter, and they do not need to in order to benefit. The TensorLean bug taxonomy is a free test plan. Memory access errors, numerical edge cases and races account for most findings, so point your testing budget there first.
Start by treating the configuration matrix as the unit of testing. Enumerate every template instantiation you actually ship, then generate boundary shapes for each. Run sanitizers in CI on a representative subset, accepting the slowdown for nightly rather than per-commit jobs. Pin your tolerance to measured error, not convenience.
If you depend on upstream attention or GEMM kernels, track which instances you actually dispatch. When verification results and bug lists are published, you will need that inventory to know whether you are exposed. Our deep dive on FlashAttention-2, -3 and -4 internals explains the tiling and pipelining that create those instance variants.
If you generate kernels with agents, make verification the gate rather than benchmark speedup. Require the agent to pass a boundary differential harness before any performance measurement counts. Pilot formal specs on one small, high-value kernel, such as a fused norm or a decode-time KV-cache update, before attempting attention.
- [ ] Inventory every compiled kernel instance your stack dispatches, per GPU architecture.
- [ ] Add tile-boundary shapes (tile minus one, tile, tile plus one) to every kernel test.
- [ ] Test fp16, bf16 and your low-precision formats, not just fp32.
- [ ] Include large, subnormal, signed-zero and NaN inputs; assert NaN propagation explicitly.
- [ ] Run repeated identical launches and fail on nondeterminism.
- [ ] Run memcheck, initcheck, racecheck and synccheck nightly.
- [ ] Write down tolerance budgets and justify each in review.
- [ ] Pilot a tensor-level spec on one critical kernel and track proof time in CI.
Frequently Asked Questions
What is formal verification of GPU kernels?
Formal verification of GPU kernels is the use of mathematical proof, checked by a tool such as the Lean theorem prover, to show that a kernel computes its specified output for every valid input and every legal thread schedule. Unlike testing, which samples a few inputs and runs, a proof covers all of them. Modern approaches such as TensorLean verify compiled PTX code rather than source, so they also catch compiler bugs. They prove properties like data-race freedom, termination and numerical accuracy within a stated tolerance.
What is TensorLean?
TensorLean is a framework from Columbia University and CertiK, announced in November 2026, for formally verifying production GPU kernels at the PTX level in Lean. Developers write tensor-level specifications using PyTorch-like operators, and the tool proves that compiled kernels match them. The team reports checking 149 kernel instances from FlashAttention, DeepGEMM and other libraries, proving 83 correct and finding 38 bugs. As of late November 2026 the full paper had not yet been released, so these figures are author-reported.
Why do FlashAttention kernels have bugs if they are so widely used?
Wide use exercises common configurations, not rare ones. A FlashAttention release compiles into many distinct kernel instances across head dimensions, masks, KV cache layouts, rotary modes, data types and GPU generations. TensorLean reports that 19 of 23 FlashAttention bugs it found appear only in specific configurations. Many such bugs, like races or tail-tile errors, produce slightly wrong numbers rather than crashes. Without a crash or obvious garbage output, nobody files a bug report, so the defect survives despite heavy deployment.
What is PTX and why verify at that level?
PTX (Parallel Thread Execution) is NVIDIA’s virtual instruction set, the intermediate code that CUDA, Triton and other compilers emit before NVIDIA’s ptxas assembler turns it into native SASS machine code. Verifying PTX means the proof covers what the compiler actually produced, including compiler-introduced bugs. TensorLean found two miscompilations this way. PTX also has a published formal memory model, from Lustig et al. at ASPLOS 2019, while SASS is not fully documented, which makes PTX the most practical layer for proofs today.
Can compute-sanitizer find data races in CUDA kernels?
Partly. The racecheck tool in NVIDIA Compute Sanitizer detects read-after-write, write-after-read and write-after-write hazards, but its documentation states it only supports on-chip shared memory. It does not detect global-memory races or reason about schedules it did not observe. It also adds substantial runtime overhead. Racecheck is valuable in nightly CI, alongside memcheck, initcheck and synccheck, but it cannot prove race freedom. Only static or formal methods quantify over all schedules.
Will formal verification replace testing for GPU kernels?
No, and it should not. Proofs depend on a trusted base that includes the specification, the PTX model, a tensor-core rounding model and, in TensorLean’s case, SMT solvers. Testing on real hardware checks everything below that base, including ptxas, SASS and silicon. The realistic future is layered: differential testing and sanitizers catch cheap bugs fast, and proofs certify the critical kernels that everything else depends on. Testing also validates that the specification itself matches what users expect.
Further Reading
- Triton GPU kernel programming tutorial: block-level tiling and fused kernels vs CUDA and CUTLASS for the masking and tiling idioms behind most tail-tile bugs.
- GPU kernel engineering: CUDA kernel execution and data starvation for the execution model that makes kernels fast and fragile.
- NVFP4 vs MXFP4: 4-bit floating point and microscaling on Blackwell for the low-precision formats that specs must now describe.
- GPU parallelism anatomy: SM, block, warp and thread hierarchy for background on the warps and blocks whose synchronisation proofs reason about.
- Fact-check: did AI prove the Riemann Hypothesis with a Lean-verified proof? for how to read “verified in Lean” claims critically.
- TensorLean project page with the bug taxonomy, trusted computing base and limitations.
- Lustig, Sahasrabuddhe and Giroux, A Formal Analysis of the NVIDIA PTX Memory Consistency Model (ASPLOS 2019).
- GPUVerify: a Verifier for GPU Kernels (OOPSLA 2012).
By Riju — about
