Docs

The block checker and its automation

The block checker proves facts about a compiled kernel's steps by kernel reflection. Untrusted code computes a summary of a block (sym_summary); the Lean kernel evaluates a Boolean checker on it (decide +kernel); and one theorem, proved once for every program, turns an accepted summary into facts about the semantics' steps. sym_summary is not trusted: the kernel evaluates the checker on its output, so a wrong summary is refused and nothing about it enters a proof. The checker itself is proved sound.

file contents
MojoProof/Sym/Term.lean symbolic values: the node table (SVal, SNode), their values (vals), memory effects (SEff), obligations (Cond)
MojoProof/Sym/Checker.lean the checker: summarize, Summary, covers, coversTo
MojoProof/Sym/Rel.lean the relation Rel of the checker's state to a frame and a memory, its lemmas, the terminator's step (SState.exitAt_sound) and the pointer facts' definitions
MojoProof/Sym/Block.lean its soundness: SState.stmt_sound, Block.sound, Block.soundC, the pointer facts
MojoProof/Sym/Exec.lean the statements exec runs (exec_bin to exec_minmax) and the shape of the memory the effects make (SEff.run_shape)
MojoProof/Sym/Segment.lean segments that end at a barrier or a warp shuffle: summarizeTo, SegSummary, Seg.sound, Seg.through; or at a lifetime marker: summarizeLife, Seg.lifetime, Seg.lifetime_ptr
MojoProof/Sym/Path.lean along a path: coversPathWith, WalkWith, edges into blocks with phis, returns
MojoProof/Sym/Loop.lean loops: Block.sound_loop, invariants, sequences of loops and nested loops
MojoProof/Sym/PtrMem.lean the memory premises of a path from a labelling's memory hypothesis
MojoProofTest/Sym.lean, SymRun.lean, SymPhi.lean, SymLoop.lean tests
scripts/SymBench.lean the benchmark (not part of the build)

The commands sym_summary and #mojo_info are described in docs/tactics.md. The kernel theorem built on top of the checker, Kernel.sound_of_paths, and the command mojo_kernel are described in docs/kernel.md. The informal proofs are in docs/proofs/ (edge.md, phi.md, back.md, ptrs.md, loop.md).

What the checker checks

Symbolic values

A block's symbolic values form a DAG stored as a node table. There is one node (SNode) per statement that defines a value, in the statements' order. A node's operands (SVal) are atoms or earlier nodes:

The nodes are:

A value used twice is one node referred to twice, so the table has as many nodes as the block has value-defining statements (and one more per getelementptr, load or store on a global), whatever the sharing. A node whose instruction carries a type (getelementptr's source type, load's type, a cast's types) or a name (a global's) names its statement by block label and position and reads the type or the name there. As a result SNode holds no Ty, whose derived equality the kernel does not reduce, and no String.

SNode.eval V vs nd is the value of node nd under a valuation V, given the values vs of the nodes before it. The valuation holds the context, the function, the step count at the entry, the entry memory, the entry registers and the fmul contract operands. The value is computed by the semantics' own operations (intBin, icmpV, intCast, castV, extractV, gep, Mem.load, floatBin, withAttrs), faults included. So eval agrees with the semantics' exec by construction, not by a separate proof per operation. vals V ns, the values of table ns, is a fold that evaluates each node once, on the values before it.

One block: summarize and covers

summarize P fn lbl p0 runs block lbl of function fn of program P symbolically from position p0. Each statement that defines a value appends one node, sets its register to that node, and adds the obligation Cond.ok (node j) that the node evaluates without a fault. A load and a store add their memory effect (SEff). The terminator gives the exit:

The summary (Summary) holds the table, the registers' entries, the effects, the obligations, the exit and the number of statements. Its obligations are the exit's, then Cond.mem effs (the effects run without a fault), then the statements', latest first.

covers P fn lbl p0 ds S holds when summarize P fn lbl p0 is a summary equal to S (by the derived equality) and S's obligations are the first conditions of ds (List.isPrefixOf, a check by position). sym_summary writes S as a Lean term. The kernel then evaluates covers again, so a wrong summary from sym_summary is refused rather than trusted.

The fragment the checker accepts:

Everything else makes summarize give none, so covers is false:

coversTo P fn lbl p0 d₀ is covers with only the obligations of the edge into block d₀, for a br i1 into blocks with phis. An operand of the untaken edge that is outside the fragment or faults then does not refuse the block.

Paths

A path is a list of entries (l, ds, S): a block's label, its conditions and its summary.

What it proves

Every theorem below is proved once, for every program, function, block, position, conditions and summary (or path) that the checker accepts. Those about a block or a path are about one thread's steps, and their premises are that the conditions hold under the thread's entry valuation (hds, WalkWith). The checker's run is a per-kernel computation (covers … = true by decide +kernel). The premises are per thread: a test that proves them by decide +kernel covers the contexts, memories and frames it names. A proof for every thread needs them proved symbolically.

Block.sound (MojoProof/Sym/Block.lean)

Take covers P fn lbl p0 ds S = true, a context c with c.prog = P, a thread t with frames f :: rest (f.fn = fn, f.label = lbl, f.pc = p0) and a memory m. Let V := Valuation.entry c t.k m f and vs := vals V S.nodes. If every condition of ds holds under V and vs, then Ends c t m f rest (V, lbl, S) holds. That is, there are a frame fe and a memory me such that, for k' := t.k + S.len:

The proof is in the module docstring of MojoProof/Sym/Block.lean. In short, the relation Rel (MojoProof/Sym/Rel.lean) says a symbolic state describes a frame and a memory. SState.stmt_sound shows each statement of the fragment keeps it, SState.run_sound extends that to the statement list, and SState.exitAt_sound (MojoProof/Sym/Rel.lean) covers the terminator.

Block.sound_ptrs concludes Ends and the pointer facts Ptrs as well: the thread's steps reach the statement of each load node and each store effect, and there the statement's pointer operand, evaluated in the thread's scope, is the summary term's pointer value (docs/proofs/ptrs.md). Block.sound_withAt is Block.sound for any exit function whose exit is the terminator's step when its obligations hold, and for either value of the flags alloca and contract (concluding EndsAt contract, which is EndsWith contract with the flag alloca off, by EndsAt.ends, and Ends without either flag). Block.sound_to is Block.sound for coversTo, when the exit goes to d₀.

coversC is covers with fmul contract in the fragment: a float operator's node records the fmul contract operand terms its operands carry (SNode.fbinP), and Block.soundC concludes EndsC, which is Ends with the frame's products at the block's end given by the table (regProdIn: for a register the block sets, the values of its node's operand terms). Ends.edgeC is Ends.edge from EndsC, entering the next block at Valuation.intoC (Valuation.into with the table's products). Block.sound_pathC takes a path that coversPathWith false accepts, then one block that coversC accepts. The path and loop checkers take the same flag (coversPathWith, WalkWith, RoundWith, ChainWith, coversChainsWith), and the path and loop theorems are proved once for both values (docs/proofs/contract.md).

Segments that end at a collective (MojoProof/Sym/Segment.lean)

A thread's step at a barrier or a warp shuffle is a .wait, which the grid completes, so summarize (which ends at the terminator) does not pass one. summarizeTo P fn lbl p0 p1 is the summary (SegSummary) of the statements p0 to p1 - 1 by the same statement case, ending at the collective call at p1 (SState.waitAt: the barrier or a shuffle, Coll, with no fast-math flags or attributes) with its argument terms; its obligations add that each argument term evaluates. Seg.sound, for every program: from the entry valuation of a frame at p0 that meets the obligations, the thread's steps reach p1 with the summary's registers and memory, and the step there is the .wait of the collective on the arguments' values (Waits). The resumed thread is at p1 + 1 with the same function and block (Thread.resume_at; Seg.resume, from the summary's collective and length, the steps to the .wait and the resumed frame), and has at every register but the call's result the summary's value (Thread.resume_regs, Seg.resume_regs), where the next segment starts (summarizeTo again, or summarize and Block.sound for the last one). summarizeSegs P fn lbl p0 ps gives the summaries of all of a block's segments, with the collective calls at the positions ps, and the summary of the rest; Seg.through, for every program, runs them in a row on one thread (Seg.Through), each wait followed by the resume with the value and memory w i that the i-th collective delivers, a parameter. The schedule that fires the collectives and supplies those values is not proved.

A segment also ends at a call of llvm.lifetime.start or llvm.lifetime.end (SState.lifeAt, summarizeLife P fn lbl p0 p1, with the pointer's term), since the effects a summary replays are its loads and stores and the marker's Mem.setLive is neither. Seg.lifetime, for every program: from the entry valuation of a frame at p0 that meets the obligations (the pointer's term evaluates, the effects run, and the statements'), the thread's steps reach p1 on the memory the effects make, and when intrinsic gives memory m' on the pointer's value (the block's Mem.setLive, intrinsic_lifetime_ptr, or the same memory on poison) the step there moves on m' to p1 + 1, where the next segment starts; Seg.lifetime_ptr states it for a pointer into a block the thread owns and for poison. The marker's parameter may carry captures(none) (withAttrs_args).

Along a path

To the kernel theorem

Runs.of_ret (MojoProof/Sym/Kernel.lean) turns a path that coversPathWith false accepts and that is a Ret to Q (its premises hold, its last block returns, its effects run to a memory of Q) into the thread's run to its end (Runs). Kernel.sound_of_paths takes a list of paths that coversEntry accepts (each from the kernel's first block) and an invariant on the memory, indexed by the number of threads done. Each thread must take one of the paths as a Ret from the invariant at k threads to the invariant at k + 1. From these and the premises it states, it concludes Kernel.Sound for every launch, arguments, memory, admission and observation. Kernel.sound_of_chains is the same with, for each thread, a path or a sequence of loops (RetLs, through Runs.of_chainsWith), and Kernel.sound_of_paths is its case without loops. mojo_kernel enumerates a kernel's paths, and with one loop clause per loop its sequence of loops, and generates these theorems (docs/kernel.md).

Loops: what is automated and what is not

A loop is a path (h, ds, S) :: B from its header h, entered at position p (after its phis), through the body to the latch, whose exit goes back to h. Valuation.round is the header's valuation after one round. Round is the decidable premise of one round: the loop path's WalkWith false, and its last exit goes to h at position p. The theorems (MojoProof/Sym/Loop.lean) are proved once, for every program, function, path, list of loops, nesting, trip count and invariant, and for blocks with and without fmul contract: each takes a flag contract, and with contract = true reads coversPathWith true, RoundWith true, Valuation.roundWith true and ChainWith true for the names below (docs/proofs/contract.md).

What is automated:

What is not automated:

Running the checker on a new kernel

  1. Compile the kernel to LLVM IR with the Mojo version that tests/corpus/MANIFEST.tsv records (its mojo column): mojo build --emit llvm --target-accelerator sm_80 -o <file>.ll <file>.mojo writes one .nvptx.ll file per kernel. Add the file to tests/corpus/<family>/ with scripts/corpus.py add <family> <src.mojo> <modular-path> <flags> <file.nvptx.ll>, which records its digest, kernel, target, Mojo version, flags and source in the manifest (with another compiler than the recorded one, pass its version as --mojo <version>). mojo_import refuses a file that has no row in the manifest or whose digest differs from its row.
  2. In a Lean module that imports MojoProof.Sym.Command (and MojoProof.Sym.Info for #mojo_info), import the program and look at it:

    mojo_import "<family>/<file>.nvptx.ll" as k
    #mojo_info k.prog
    

    #mojo_info prints, per function, its calls, back edges and float operators, and per block its size, phis, successors and the checker's verdict (in the fragment, or the first statement it refuses). It is a report, not a proof. k.fn_<i> is function i, and k.fn_<i>.b_<j> is its block j.

  3. Summarize a block and check it:

    sym_summary s := k.prog k.fn_0 k.fn_0.b_1.label 0
    theorem s_covers : covers k.prog k.fn_0 k.fn_0.b_1.label 0 s.obls s = true := by
      decide +kernel
    

    sym_summary reports a block outside the fragment as an error that names it. For a block with phis, start from the position after them (phiCount).

  4. Apply Block.sound s_covers hP ht hfn hl hp hds. hds says that the summary's obligations hold under the thread's entry valuation. On a concrete context, memory and frame, decide +kernel proves it (vadd21_hds, MojoProofTest/SymRun.lean). For every thread it needs a symbolic proof.

  5. For a path, list its entries, check them with coversPathWith false by decide +kernel, and apply Block.sound_pathWith_ptrs or Block.sound_retWith with WalkWith false (vadd_paths and vadd_ret in MojoProofTest/Sym.lean).
  6. For a loop-free kernel, mojo_kernel summarizes every block, enumerates and checks the paths from the entry, and adds Kernel.sound_of_paths at them with the premises that remain. With the clause map2, for a binary elementwise kernel, it also proves the kernel theorem for every valid one-dimensional launch and every caller's memory of the precondition Map2.Pre (MojoProof/Kernels/Vadd.lean, docs/kernel.md). For a kernel with loops in sequence, one loop clause per loop gives the thread's run and the kernel theorem through the loops; see the previous section.

Tests

Each test covers the program, contexts, memories and frames it names. The theorems it instantiates hold for every program, block and path the checkers accept.

Cost

The summary is linear in the block's size. There is one node of constant size per value-defining statement, and one obligation per node. sym_summary's quotation, the comparison decide (S' = S) and the prefix check of the obligations are linear too. With operands as trees instead of node indices, a block whose statement i uses statement i - 1's value twice (twice n below) would have a last value with 2 ^ (n + 1) - 1 nodes. The table has n.

The kernel's evaluation of covers still grows about quadratically. SState.def appends each node at the end of the table (σ.nodes ++ [nd]) and takes its length. An operand's lookup in the registers' entries (SState.get, an association list) scans the list for an entry register. On a concrete valuation, vals appends one value at a time and SVal.eval looks a node up by position. A table built by cons with its length carried, and an indexed register table, would make these linear. Neither is done.

Benchmark

scripts/SymBench.lean runs the cases below, from the repository root after lake build MojoProof MojoProofKernels:

lake env lean scripts/SymBench.lean

The script's docstring describes each case. "Kernel ms" is the time of addDecl on the theorem with the proof decide +kernel builds (of_decide_eq_true (Eq.refl true)): the kernel's evaluation alone, with Elab.async off. The numbers are from one run on 8 cores of a machine whose other cores ran other builds, with a peak RSS of 4.46 GB (3.14 GB after the imports); the timed commands take 44 s in all. Times vary by up to about 2x with the machine's load, so compare cases measured one after the other, and ratios rather than single times.

case statements obligations in ds kernel ms
vadd %21 9 9 66
vadd %30, %31 0 1 8, 7
vadd %21, one obligation dropped (false) 9 8 68
wide 10 / 25 / 50 10 / 25 / 50 n + 1 45 / 148 / 436
wide 100 / 200 100 / 200 n + 1 1562 / 5995
chain 25 / 50 / 100 25 / 50 / 100 n + 1 136 / 367 / 1107
twice 25 / 50 / 100 / 200 25 / 50 / 100 / 200 n + 1 136 / 375 / 1090 / 3686
et 25 / 50 / 100 / 200 (obligations evaluated) 25 / 50 / 100 / 200 146 / 402 / 1587 / 5872
loads 50, !invariant.load / none 50 51 553 / 568
wide 50, 100 / 1000 extra conditions after 50 151 / 1051 533 / 554
mm67 191 192 10833
tiled_matmul %67 itself (summarize is none) 208 91
sels 50 (a chain of selects, later run) 50 51 255
naive matmul %6 (llvm.smax, select; later run) 37 39 469
mm67c: mm67 with its fmul contracts, by coversC (third run) 191 192 8354
naive matmul %52 (fmul contract, fadd contract), by coversC (third run) 14 17 73

sym_summary computes the summary of %21 in 17 ms and that of mm67 in 239 ms (elaboration and kernel).

The rows marked "later run" are from a later run of the same script, on a less loaded machine: there chain 50 took 249 ms, wide 50 334 ms and mm67 7885 ms. The rows marked "third run" are from a third run: there chain 50 took 252 ms, wide 50 332 ms and mm67 8429 ms. Their summaries are definitions the kernel unfolds (summarizeC), so their times include computing the summary once more.

What the numbers show:

Names (String comparison in the kernel)

covers compares no function names, only metadata keys (checkMd, "noundef", "invariant.load"), and those cost nothing measurable (loads 50 above). The semantics compares names in three places:

Measured in the kernel with #ktime on vector_addition's program (4 functions), in the run above:

So a name costs about 0.05 ms per comparison over a Nat, and a call about 0.8 ms over an index. This does not matter for the block checker. A grid-level certificate that evaluated exec in the kernel on every thread would pay 0.8 ms per evaluated call: about 0.6 s for 768 calls (256 threads, 3 calls each), small against the block checks above. Interning (resolving callee names to indices once, when the program is built) is not done.