Provably Safe and Fast GPU Kernels in Rust
Specify and verify safety properties on your Rust kernels, and emit fast PTX with zero runtime checks.
We have been working on something ambitious for the past couple of months, and we are finally ready to share it.
With cuda-oxide, we can now write provably safe and fast GPU kernels completely in Rust, backed by compile-time Lean 4 proofs. That means no unsafe blocks for shared memory or barriers, and no bounds-check tax inside hot GPU loops.
cuda-oxide/oxide-proofs-preview/). We are opening it up early so the Rust, GPU, and formal-verification communities can jump in with us. Expect rough edges, missing instructions, bugs, and probably soundness corners we have not thought of yet. Please try to break it!
First: What Do We Mean by "Safe"?
On a CPU, Safe Rust means zero undefined behavior: no out-of-bounds memory accesses, no data races, and no dangling pointers. Notice what it does not mean. It does not prove functional correctness. If you write a[i] - b[i] when you meant a[i] + b[i], your math is wrong, and Safe Rust will happily compile it.
On the GPU, if we want that same contract (memory safety and barrier safety), we don't need to prove functional correctness.
At the host launch boundary, rustc already gives us a strong foundation. Device buffers are guaranteed live and aligned, and the borrow checker ensures &a, &b, and &mut c never alias each other.
What rustc does not provide is multi-thread reasoning inside the kernel body. rustc type-checks a kernel function as if a single thread called it, while the GPU runs thousands of threads through that function at the same time:
Three GPU Bugs Single-Thread Checking Does Not Catch
t3 walks past buf.len() and corrupts adjacent memory.
t1 writes while t2 reads TILE[1] in the same step without a barrier.
t3 returns early inside an if, leaving the block deadlocked or desynced.
Until now, the moment your kernel staged tiles in shared memory, synchronized across warps, or needed bounds checks stripped out of a hot inner loop, you had to reach for unsafe or --unchecked-indexing.
How It Works
The core idea is specify and verify. You write a small specification on your Rust kernel stating what safety properties hold, and the compiler takes a quick detour during compilation to verify them before generating PTX:
- 1. Specify on the kernel: You attach attributes like
no_oob_idx,no_data_race, oruniform_barriersto state what is safe, along with any host launch preconditions (such asa.len() >= c.len()). - 2. Take a compiler detour: Halfway through compiling the kernel (right after stack variables become SSA registers, and before loops are unrolled), the compiler pauses in memory. At this point, loops are still compact basic blocks and every slice or shared-array access still has its explicit bounds check sitting right in front of it.
- 3. Verify against the spec: The compiler collects those instructions and barriers, translates them line by line into Lean 4, and proves your specification holds across every active GPU thread (ignoring floating-point math, since float values never change which memory slot a thread touches).
- 4. Erase proven checks: Once the proof passes, the compiler deletes the proven bounds checks in memory and continues lowering to PTX. If a property fails, compilation stops right there.
The Proof Detour: Collect, Verify, and Erase Checks
requires = (
a.len >= c.len
)
)]
#[verify(
no_oob_idx(a, b, c)
)]
mir.assert(idx < a.len) v1 = mir.load(a[idx])
mir.assert(idx < b.len) v2 = mir.load(b[idx])
mir.store(c[idx], v1+v2)
theorem verify_no_oob :
MirNoOobGlobal ... :=
by mir_vc mirFunc
✓ 0 sorryAx (QED)
ld.global.f32 %f2, [b];
add.f32 %f3, %f1, %f2;
st.global.f32 [c], %f3;
// 0 trap branches
mir.assert checks before PTX emission.
Once Lean 4 verifies every safety theorem with zero sorryAx axioms, the compiler deletes the proven mir.assert bounds checks in memory and resumes normal lowering through LLVM to emitted PTX.
What It Looks Like in Practice
Here is a complete vector-add kernel using a plain mutable Rust slice c: &mut [f32], zero wrapper types, and zero unsafe:
#[launch_contract(
domain = 1,
block = (256, 1, 1),
requires = (a.len() >= c.len(), b.len() >= c.len()),
)]
#[verify(no_oob_idx(a, b, c), disjoint_writes(c), writes_all_elems(c))]
#[kernel]
pub fn vecadd(a: &[f32], b: &[f32], c: &mut [f32]) {
let idx = (thread::blockIdx_x() as usize) * (thread::blockDim_x() as usize)
+ (thread::threadIdx_x() as usize);
if idx < c.len() {
c[idx] = a[idx] + b[idx];
}
}
Notice c: &mut [f32] in the signature. Normally cuda-oxide rejects a plain mutable slice because two GPU threads could overwrite the same slot, so #[verify] unlocks it once exclusivity is proved. Here is what happens at each stage:
- At compile time:
#[verify]proves in Lean 4 that every thread writes to a uniqueidx(disjoint_writes(c)) and thatidx < c.len()keeps all three slice accesses in bounds (no_oob_idx). - At launch time:
#[launch_contract]checksa.len() >= c.len()andb.len() >= c.len()once on the CPU before the kernel runs. - On the GPU: All three bounds checks are erased, so threads run with zero check overhead.
And if you sneak in an off-by-one bug like a[idx + 1]? Compilation halts before PTX is ever emitted, and Lean's integer solver hands back a concrete counterexample. Try toggling the bug live below:
Inside MirFunc (Click Any Line, or Break It!)
mir.cond_br v8 ^bb1, ^exit
v11 = mir.load(&a[v6])
(.condBr 8 1 [] 2 [])
(.assign 11 (.load 10))
idx < c.len ∧ c.len ≤ a.len → idx < a.len via Lean's integer solverbx₁*256 + tx₁ = bx₂*256 + tx₂ → t₁ = t₂ (MirDisjointWrites)mir.assert ops in memory; proceeding to LLVM/PTX.Scaling Up: 2.118 PFLOP/s on NVIDIA B200
Proving vector addition is a nice sanity check, so we pushed the exact same line-by-line engine all the way up to a full speed-of-light 2-CTA persistent BF16 GEMM on Blackwell (safe_gemm_sol_final, 338 MIR basic blocks).
Because MirFunc and ControlFlowCfg verify individual instructions rather than hardcoded indexing shapes, the same proof library verifies a warp-specialized 2-block cluster pipeline:
- Warp 4 (Producer + Work-Stealing) streams A and B tiles into a 7-stage,
224 KiBshared-memory ring via 2-CTA multicast TMA while pulling next-tile coordinates from hardware Cluster Launch Control (CLC). - Warp 5 (2-CTA Tensor Cores) issues cooperative 5th-gen
tcgen05.mmainstructions into two alternating 256-column halves of 512-column Tensor Memory (TMEM). - Warps 0..3 (Epilogue) unload 32-lane
TMEMwindows into registers and write out BF16 results.
Verified 2-CTA Blackwell GEMM: Zero Safety Overhead at 2.12 PFLOP/s
[0..256]
[256..512]
0..32
32..64
64..96
96..128
Trust Boundary and Summary
We want to be clear about what is proved and what sits in our Trusted Computing Base (TCB) today:
- Proved in Lean 4 (
0 sorryAx): Slice, shared-memory, andTMEMbounds, race freedom across barrier phases andmbarrierhandoffs, disjoint writes, and uniform barriers on thePostMem2RegMIR model. - Trusted Computing Base (not proved today):
- Rust to SSA MIR (
mir-importer,mem2reg): Lowering Rust into in-memoryPostMem2RegIR. - The 1-to-1 transcriber (
lean-exporter): Copying MIR blocks and barriers into Lean 4 (failing closed on unsupported ops). - Downstream PTX lowering (
mir-lower, LLVM,ptxas): Lowering the IR to emitted PTX after proven bounds checks are erased. - Host launch checks & CUDA runtime: Checking grid dimensions and
requireslength rules on the CPU before launch.
- Rust to SSA MIR (
What #[verify] Gives You
- Declarative safety contracts: Six small clauses (
no_oob_idx,no_data_race,disjoint_writes,writes_all_elems,uniform_barriers,tmem_lifecycle) in normal Rust, with zero inline loop invariants or ghost code. - Deterministic, reusable proofs: Soundness theorems for our MIR and barrier analyzers are proved once in Lean 4 (
0 sorryAx) and applied automatically per kernel. - Safe SIMT without
unsafe: Unlocks&mut [T],SharedArray, barriers, 2-CTA clusters, and Blackwelltcgen05/TMEMin safe Rust. - Zero GPU bounds-check tax: Proven
mir.assertchecks are erased in memory before PTX lowering (2.118 PFLOP/son B200).
What to Watch Out For
- Longer compile times: Running Lean 4 during
cargo oxide buildadds build time that grows with kernel size and the number of preconditions and#[verify]clauses. - Fail-closed MIR subset: Instructions or control-flow shapes not yet modeled in
MirFuncfail closed at compile time rather than falling back silently. - Raw solver diagnostics: Failed bounds proofs currently print raw integer-solver inequalities (
cargo oxide lean-exporthelps inspect them, and friendlier error mapping is still ahead). - Early-preview sharp edges: Attribute syntax will evolve, and there are likely bugs or soundness corners in the transcriber that we want help uncovering.
You can inspect the live MIR and generated Lean 4 theorems on any verified kernel with one command:
cargo oxide lean-export safe_vecadd
Help Us Stress-Test the Preview
This is our first public preview of compile-time Lean 4 kernel verification in cuda-oxide (PR #1851). Unsupported MIR patterns fail closed at compile time, syntax will evolve, and there are almost certainly bugs and soundness edge cases waiting to be found. If you enjoy Rust, GPU kernels, compilers, or Lean 4, take it for a spin, try to break the verifier, and open an issue with whatever you hit!