Loops by induction on the trip count (Block.sound_loop)
Lean: MojoProof/Sym/Loop.lean. Tests: MojoProofTest/SymLoop.lean,
MojoProofTest/SymLoopAlloca.lean.
Scope. Every program P, function fn, loop path (h, ds, S) :: B (the header h from
position p, after its phis, through the body to the latch) that coversPathWith false accepts
from p, every trip count n, every context of P and every thread whose innermost frame runs
fn at block h's position p.
Block.sound_edge, Block.sound_loop, Round.of_inv and Block.sound_loop_inv take a flag
contract, and so do BackWith.enter, ChainWith, ChainWith.reach, ChainWith.enter,
ChainWith.of_iter, ChainWith.of_rounds, Runs.of_chainWith and Runs.of_chainsWith
(LoopPaths, Runs.of_loop and Runs.of_loops take none). This file states the contract = false
case; with contract = true (blocks with fmul contract) read coversPathWith true,
WalkWith true, Valuation.lastWith true, Valuation.roundWith true, EdgeWith true,
RoundWith true, BackWith true, coversChainWith true and ChainWith true for
coversPathWith false, WalkWith false, Valuation.lastWith false, Valuation.round, Edge,
Round, BackWith false, coversChain and ChainWith false (docs/proofs/contract.md). The proofs
are the same.
All of these but Round.of_inv and the ChainWith.of_ lemmas also take a flag alloca, for
blocks with allocas: the path checker coversPathAt alloca contract (MojoProof/Sym/Path.lean)
and the loop checkers coversChainAt, LoopSeg.coversRoundAt and coversChainsAt, whose cases
with the flag off are coversPathWith, coversChainWith, LoopSeg.coversRoundWith and
coversChainsWith, by definition. With the flag, the frame a theorem reaches has some blocks
bs in front of f's alloca blocks, (bif alloca then bs else []) ++ f.allocas (the blocks
of the paths run, Valuation.allocsWith); with it off that is f.allocas. Block.sound_edge
names the blocks: f'.allocas = (Valuation.entry c t.k m f).allocsWith contract l S ps ++
f.allocas. Valuation.allocsWith_cond turns that into the bif form, allocas_trans composes
two of them, and Runs.of_chainsAt is the kernel form with the flag (Runs.of_chainsWith is its
case with the flag off). Each of them also says what bs is: the memory reached adds exactly
the blocks bif alloca then bs else [] to the start memory m (Mem.Adds m bs m',
MojoProof/Sym/Path.lean: a number is in the list exactly when m has no block there and m'
has one, and every block of m is still there). A block's effects add their alloca blocks
(SEff.run_adds), a path its blocks' (Block.sound_pathAt_ptrs), and Mem.Adds.trans composes
two runs, so the edges, rounds and chains carry it. Runs.of_chainsDead is the caller's form:
for a predicate R that reads only the blocks of m, next and the trace, if the last path
leaves a memory me of Q and R, the thread runs to its end on a memory m' of R whose
block at every number is me's, dead where m has none (Mem.Adds.foldl_setLive). This file
states the case with the flag off.
Statement
Valuation.round h S B V is the valuation at the header after one round from header valuation
V: Valuation.into of the latch from its entry valuation (Valuation.lastWith false).
Round h p ds S B V is the premise of one round: WalkWith false V ((h, ds, S) :: B), the latch's
exit goes to h (Exit.dest), and enters it at position p (Exit.pc). Round is decidable
(Round.dec).
If Round holds at round^[i] (Valuation.entry c t.k m f) for every i < n, the thread's steps
reach a thread t' with memory m' whose innermost frame f' runs fn at block h's position
p above the same frames, with f's alloca blocks and caller's register, and
Valuation.entry c t'.k m' f' = round^[n] (Valuation.entry c t.k m f).
backEdges fn lists the branches (l, d) from a block l to a block d at the same or an earlier
position in fn's block order, as #mojo_info prints them; cutPoints fn the labels of their
targets, the loop headers.
Proof
Block.sound_rounds (the induction on n for every invariant, in the last section) with the
invariant "the entry valuation is the i-th iterate",
fun i W => W = round^[i] (Valuation.entry c t.k m f), which holds at 0 by rfl. One round from
a thread at the header whose entry valuation is the i-th iterate:
- round
i's premises are a path's (WalkWith false), soBlock.sound_pathWith_ptrsruns the path to the latch's end (Ends, fromlastWith false), andlastWith falsekeeps the context and the function (Valuation.lastWith_k); - the latch's exit goes to
h(Exit.dest), soEnds.edgetakes the branch, into a frame offnath's positionExit.pc, whichRoundsays isp; - the entry valuation there is
roundof thei-th iterate, the(i + 1)-th (Function.iterate_succ_apply').
The first two steps are Block.sound_edge; Steps.trans_step composes the steps.
Dependencies
Block.sound_rounds, Block.sound_edge (MojoProof/Sym/Loop.lean);
Block.sound_pathWith_ptrs, Ends.edge, Valuation.lastWith_k (MojoProof/Sym/Path.lean);
Steps.trans_step (MojoProof/Sym/Rel.lean); Function.iterate_succ_apply' (Mathlib); succs
(MojoProof/Sym/Info.lean) for backEdges.
Instances
See the end of this document: the instances are cnt_retL, cnt_run and cnt_run_outC,
through Runs.of_loop and Runs.of_loops.
Loops from an invariant (Round.of_inv, Block.sound_loop_inv, Runs.of_loops)
Lean: MojoProof/Sym/Loop.lean. Tests: MojoProofTest/SymLoop.lean,
MojoProofTest/SymLoopAlloca.lean.
Scope. Every program P, function fn, entry path, loop path and exit path that
coversPathWith false accepts, every trip count n, every invariant I : Nat → Valuation → Prop
(indexed by the round number; an invariant J that does not depend on the round is fun _ => J),
every predicate Q on memories, every context of P, and every thread with one frame of fn.
Statement
Round.of_inv. SupposeI 0 Vholds. Suppose also that for everyi < nand every valuationW,I i Wgives bothRound h p ds S B WandI (i + 1) (Valuation.round h S B W). ThenRoundholds atround^[i] Vfor everyi < n, andI n (round^[n] V)holds. These are the premises of every round for trip countn, from the invariant alone.Block.sound_edgeisBlock.sound_pathWith_ptrsfollowed by the last block's edge. Take a path(l, ds, S) :: psthatcoversPathWith falseaccepts fromp0, and a thread whose innermost framef(aboverest) is at blockl's positionp0. Suppose the path's premises hold (WalkWith false) and the last block's exit goes tod(Exit.dest). Then the thread's steps reach a framef'aboverestwith these properties:- it runs
fnat blockd's positionExit.pc fn d(afterd'sphis forExit.phi); - its
allocablocks and caller's register aref's; - its entry valuation is
Valuation.round l S psoff's. For a path of one block that isValuation.intoof it; for a loop path it is the header's valuation after one round.
- it runs
Block.sound_loop_invisBlock.sound_loopwith its premises from (1). The thread's steps reachh's positionpagain, in a frame likeBlock.sound_loop's. Its entry valuation satisfiesI n.-
Runs.of_loopis the thread-level theorem. A loopL : LoopPathsbundles three paths offn: the entry path(L.l, L.ds, L.S) :: L.Eto the headerL.h, the loop path(L.h, L.dh, L.H) :: L.Band the exit path(L.h, L.dh, L.H) :: L.X, both from the header's positionL.p(after itsphis).L.covers P fn p0sayscoversPathWith falseaccepts the three, the entry path fromp0.Ret W Q pssays a path runs fromWtoretwith a memory ofQ: its premises (WalkWith false), a last exitret, and a memorymeofQthat the last block's effects make.RetL V Q Lis the premise of the whole run fromV:- Entry. The entry path's premises hold from
V(WalkWith false), and its last exit goes toL.h(Exit.dest) at positionL.p(Exit.pc). - Loop. For some invariant
Iand trip countn:I 0holds at the header's entry valuationValuation.round L.l L.S L.E V, and every roundi < nfrom a valuation ofI igoes back to the header withI (i + 1)after it. For a loop with no nested loop (L.inner = []) that is equivalent toRoundof the loop path andI (i + 1)atValuation.round, as in (1). With nested loops the round runs through them (ChainWith false, in the last section). - Exit. For every
W,I n WgivesRet W Qof the exit path.
Take a thread
twith one framefoffnat blockL.l's positionp0, on memorym, withL.covers P fn p0 = trueandRetL (Valuation.entry c t.k m f) Q L. Then∃ me, Runs c t m (f.allocas.foldl (fun m b => m.setLive b false) me) ∧ Q me. That is, the thread runs to its end (Runs, MojoProof/Sym/Sched.lean), leavingmewithf'sallocablocks dead. The memory left ismeitself whenfhas none, as for the frames ofGrid.start(Grid.start_thread). - Entry. The entry path's premises hold from
-
Runs.of_loopsis (4) in the form ofRuns.of_ret(MojoProof/Sym/Kernel.lean), for the threadsGrid.startmakes.coversLoops P fn loopsis a closed Boolean: every loop ofloopsstarts at the label offn's first block andL.covers P fn 0. Take a threadtwith one framefoffnat that label, position 0, with noallocablocks, on memorym. IfcoversLoops P fn loops = trueand someL ∈ loopshasRetL (Valuation.entry c t.k m f) Q L, then∃ m', Runs c t m m' ∧ Q m'. WithQthe predicate after threadk, this is the per-thread premiseSeq.start_sound_invtakes, asRuns.of_retgives it for straight-line paths. Mem.foldl_setLive_blocksandMem.foldl_setLive_load: setting the liveness of the blocks of a listbsin turn (Mem.setLive, the cleanup aretdoes withfalse) keeps every blockb ∉ bs, so a load through a pointer whose block is not inbsgives what it gave before. For every memory, list, liveness, layout, thread, address space, type, pointer and alignment.
Proof
-
Show
I i (round^[i] V)for everyi ≤ n, by induction oni.- For
0it is the hypothesis. - For
i + 1 ≤ nwe havei < n. The induction hypothesis givesI i (round^[i] V), so the preservation hypothesis atigivesI (i + 1) (round (round^[i] V)). This valuation isround^[i + 1] V(Function.iterate_succ_apply').
Round
i < n's premise is then the preservation hypothesis atiandround^[i] V, usingi ≤ n. The last conjunct is the casei = n. - For
-
Block.sound_loopandChainWith.reachuse it for each round and each edge into a header.Block.sound_pathWith_ptrsgivesEndsat the last block's entry valuation (Valuation.lastWith false).Valuation.lastWith_ksays that valuation hasf's context and function.Ends.edgetakes the branch: a step intodat positionExit.pc V.fn d, with entry valuationValuation.into. That isValuation.round l S ps Vby definition.Steps.trans_stepadds the branch step to the path's steps.
- (1) gives
Block.sound_loop's premise. Its conclusion's entry valuation isround^[n]of the first, which (1) says satisfiesI n. Runs.of_loopisRuns.of_chainWithof the one loop (the last section), whose proof composes three parts:Block.sound_edgeon the entry path, withrest = [], reaches a frame ath's positionExit.pc fn h, which isp. Its entry valuation isValuation.round l S Eoff's, soI 0holds there.Block.sound_roundsreachesh's positionpagain, at a valuation ofI n; with no nested loop each round isBlock.sound_edgeof the loop path.- The exit hypothesis there gives
WalkWith falseandret.Block.sound_retWiththen gives the steps to theretand its.donestep on the memory the effects make, which is the memory ofQbecauseExcept.okis injective. - The
allocablocks are stillf's (each part keeps them), andSteps.transcomposes the three runs intoRuns.
Runs.of_loopsisRuns.of_chainsWith(the last section) with the witnessL.chain:coversLoopsiscoversChainsofloops.map LoopPaths.chain(List.mem_map_of_mem).coversChainsgives the chosen chain's start label andcoversChainfrom position 0 (List.all_eq_true); the start label isf.labelbecause both are the label offn's first block.Runs.of_chainWithgives the run, and withf.allocas = []the cleanup is the identity.- Induction on
bs. Fora :: bswithb ∉ a :: bs,b ≠ a;Mem.setLive a veither sets blocka(Mem.set, which changes onlya) or leaves the memory unchanged. The load lemma rewritesMem.load,Mem.check,Mem.blockandMem.addrwith the block lemma.
Each round of Block.sound_loop is Block.sound_edge (the proof in the first section).
Dependencies
Block.sound_rounds,Runs.of_chainWith,Runs.of_chainsWith(MojoProof/Sym/Loop.lean);Block.sound_pathWith_ptrs,Block.sound_retWith,Ends.edge,Valuation.lastWith_k(MojoProof/Sym/Path.lean);Steps.trans,Steps.trans_step(MojoProof/Sym/Rel.lean);Runs(MojoProof/Sym/Sched.lean);Mem.setLive,Mem.set,Mem.load(MojoProof/Sem/);Function.iterate_succ_apply'(Mathlib).
Instances
These are in MojoProofTest/SymLoop.lean. They cover one hand-written function cnt
(for i in [0, n): p[i] = i) from its entry block.
cntL: the loop's paths (the entry block0, the loop path1 → 2, the exit path1 → 3, the header1at position 1).cnt_covers:cntL.covers cntP cnt 0;cnt_loops:coversLoops cntP cnt [cntL]. Both bydecide +kernel.-
cnt_retL: every trip count, as the premiseRetL. Take every contextcofcntP, every boundn ≤ 2 ^ 60, every blockb, step countkand memorymofCells c.who n b 0 m, and every framefofcntwith%n = nand%pat offset 0 ofb.Cells w n b i msays blockbis not the null block, is live, writable, in address space 1, 8-aligned, admitsw, has room forncells ofi64, and cellsj < iholdj. ThenRetL (Valuation.entry c k m f) Q cntL, whereQ mesays celljofmeholdsjfor everyj < n, with the invariantinvN c n b i(the valuation is incandcnt,%i = i,%n = n,%patb, andCells c.who n b i) and trip countn.Its three parts are symbolic proofs for every
n, roundiand valuation of the invariant; nothing is decided by evaluation:invN_entry: the entry block's obligations, its edge to the header at position 1, and the invariant at round 0. Thephioperand is the constant 0 (cnt_enter,Valuation.into_of_enter).invN_step: frominvN c n b i Wwithi < n,RoundatWandinvN c n b (i + 1)after it. The header's comparison isi < nasi64(hdr_vals,slt_ofNat). The body's nodes arei + 1and the address of celli, offset8 i(body_vals). The store to cellisucceeds and givesCells … (i + 1)(Cells.store:Mem.store_of_check,Block.read_put_selffor celli,Block.read_put_apartfor the cellsj < i). Thephitakes%inext(cnt_enter,Valuation.into_of_enter). Only%cchanges at the header (hdr_after).invN_exit: frominvN c n b n W, the exit path's premises (the comparisonn < nis false), itsret, and the loads of the cells (Cells.load,Mem.load_of_check,Layout.scalarOf_leBytes).
The bound
n ≤ 2 ^ 60keeps the offset8 ibelow2 ^ 63:getelementptr's offset is reduced byInt.bmodmodulo2 ^ 64(Int.bmod_eq_of_le). It also keepsnbelow2 ^ 63, so%nis non-negative asi64. -
cnt_run: the thread-level form, for the contexts, bounds, blocks and memories ofcnt_retLand every thread whose one framefis atcnt's entry with%n = n,%pat offset 0 ofb, andb ∉ f.allocas. The thread runs to its end (Runs), and in the memorym'it leaves, the endpoint ofRuns(withf'sallocablocks dead), celljholdsjfor everyj < n. This isRuns.of_loopwithcnt_coversandcnt_retL, thenMem.foldl_setLive_loadwithb ∉ f.allocas(an earliercnt_runproved the loads on the memory before the cleanup; withf.allocas = [b]the return kills the output block and a load from it fails the live-block check). cnt_run_outC:Runs.of_loopswithcnt_loopsandcnt_retLon one memory,outC, with three cells, and the frameframeC n(atcnt's first block, position 0, noallocablocks), for everyn < 4. Its premises arerfl,decideand8 n ≤ 24.- Twin
cnt_inv_twin: the invariant "%i = 0" (with the iterate) holds at entry but is not preserved. Round 0 makes%i = 1, so the preservation part ofRetLfails. cnt_twins: the premises of a fourth round fail with bound 3 (%i = 3is not below%n) and with bound 4 onoutC(the store to cell 3 is outside the three-cell block), and the loop path from the header's position 0 (itsphi) is refused.
Limits
The theorems hold for every program and invariant, and cnt_retL and cnt_run for every trip
count up to 2 ^ 60 and every memory with room for the cells. Four things are not done:
- The kernel theorem:
Kernel.sound_of_paths(MojoProof/Sym/Kernel.lean) takesRetof straight-line paths only; its per-thread premise has to acceptRetLtoo (Runs.of_loops), andmojo_kernelhas to find the loop paths and discharge each round's premises from an invariant. - The instance's steps (
hdr_vals,body_vals,invN_step) are proved forcnt's summaries; another loop needs its own. The general steps areValuation.into_of_enter,Mem.addr_ownandMem.store_of_check(MojoProof/Sym/Loop.lean). - Termination. The trip count is a hypothesis, and the invariant says only which
nit is. - Loops whose body leaves the fragment. The naive matmul kernel's latch
%52has afmul contractwhose product the next statement reads:coversrefuses it, andcoversC, which accepts it, has no loop theorem (docs/proofs/contract.md).
backEdges uses the block order, not dominators. For the reducible loops the compiler emits the
two agree, but this is not proved.
Loops in sequence and nested loops (ChainWith, ChainWith.reach, Runs.of_chainsWith)
Lean: MojoProof/Sym/Loop.lean. Tests: MojoProofTest/SymLoop.lean (cnt2_covers,
cnt2_retLs, cnt2_run, cnt2_twins; nest_covers, nest_rounds, nest_retLs, nest_run,
nest_twins).
Scope. Every program P, function fn, list of loops Ls (each with the loops nested in its
rounds, to any depth), path before them, position p0, and predicate F on the last path (or
Q on memories), such that coversChain accepts the paths; for each loop, every trip count and
invariant; every context of P and every thread whose innermost frame runs fn (with one frame
for Runs.of_chainWith). The instances are two functions written in the test, cnt2 (two loops in
sequence) and nest (two nested loops), each on one bound and one memory.
Statement
Definitions (MojoProof/Sym/Loop.lean).
Edge h p V l ds S E: the premises of the path(l, ds, S) :: EfromVhold (WalkWith false), and its last block's exit goes toh(Exit.dest) at positionp(Exit.pc). It is decided by evaluation (Edge.dec, :240).Round h p ds S B VisEdge h p V h ds S B: the loop path's last edge goes back into its own header (Round.dec, :251).BackWith false h p J V l ds S E:Edge h p V l ds S EandJ (Valuation.round l S E V). This is the end of a round: the last path goes back to the header atp, andJholds at the header's entry valuation after it.-
LoopSeg: one loop, with fieldsh p dh H B X inner:- the header
hand the positionpafter itsphis; - the header's conditions
dhand summaryHfromp; - the rest
Bof the loop path, to the latch or to the first nested loop's header; - the rest
Xof the path out of the loop: to the next loop's header, back to the header of the loop this one is nested in, or to aret; inner, the loops nested in a round, in the order a round runs them.
A round runs the loop path and then the nested loops in order. The loop path's last edge goes to the first nested loop's header, each nested loop's path out to the next one's header, and the last one's back to
h. With no nested loop, the loop path's last edge goes back toh. - the header
-
LoopPathsisLoopSegextended by the entry path'sl ds S E.LoopChainis an entry pathl ds S Eandloops : List LoopSeg.LoopPaths.chainis the chain of the one loop. -
coversChain P fn p0 l ds S E LsandLoopSeg.coversRound P fn Lare defined together (mutual), by structural recursion on the loops:- with no loop,
coversChainiscoversPathWith false P fn p0 ((l, ds, S) :: E); - with
L :: Ls, it is that,L.coversRound P fn, andcoversChain P fn L.p L.h L.dh L.H L.X Ls, so the path out takes the place of the path before for the next loop; L.coversRound P fniscoversChain P fn L.p L.h L.dh L.H L.B L.inner: the loop path from the header's position, and the nested loops after it.
LoopPaths.covers P fn p0 LiscoversChain P fn p0 L.l L.ds L.S L.E [L.toLoopSeg]. These are Booleans that the kernel evaluates (decide +kernel). - with no loop,
-
ChainWith false F Ls V l ds S Eis an inductive predicate.Fis a predicate on a valuation and a path, and it holds of the last path. Its two constructors are these.ChainWith.last:F V l ds S EgivesChainWith false F [] V l ds S E.ChainWith.loop I n, for an invariantI : Nat → Valuation → Propand a trip countn. It givesChainWith false F (L :: Ls) V l ds S Efrom four premises:Edge L.h L.p V l ds S E;I 0 (Valuation.round l S E V);- for every
i < nand everyWwithI i W,ChainWith false (BackWith false L.h L.p (I (i + 1))) L.inner W L.h L.dh L.H L.B, so the round runs the loop path and the nested loops and goes back to the header withI (i + 1); - for every
WwithI n W,ChainWith false F Ls W L.h L.dh L.H L.X.
RetLs Q Ls V l ds S EisRetLsWith false,ChainWith falsewithF V l ds S E := RetWith false V Q ((l, ds, S) :: E)(Ret): the last path runs toretwith a memory ofQ.RetL V Q LisRetLs Q [L.toLoopSeg] V L.l L.ds L.S L.E.coversChains P fn Cs: every chain ofCsstarts at the label offn's first block, andcoversChainaccepts it from position 0.coversLoops P fn loopsiscoversChains P fn (loops.map LoopPaths.chain).
Theorems.
Block.sound_roundsholds for every contextc, functionfn, framesrest, blockh, positionp, invariantIand trip countn. Suppose that for everyi < n, every thread whose innermost framefrunsfnaboverestath's positionp, withI iat its entry valuation, steps to a frame offnaboverestath's positionp, withf'sallocablocks and caller's register and withI (i + 1)at its entry valuation. Then every such thread withI 0steps to such a frame withI n. A round is one loop path inBlock.sound_loop, and it runs the nested loops inChainWith.reach.ChainWith.reach. TakehP : c.prog = P,ChainWith false F Ls V l ds S EandcoversChain P fn p0 l ds S E Ls = true. Take a threadton memorymwitht.frames = f :: rest,f.fn = fn,f.label = l,f.pc = p0andValuation.entry c t.k m f = V. Thent's steps reach a threadt'on memorym'and a last path(l', ds', S') :: E', such that:t'.frames = f' :: rest, withf'.fn = fn,f'.label = l'andf'.pc = p';f'.allocas = f.allocasandf'.dest = f.dest;coversPathWith false P fn p' ((l', ds', S') :: E') = true;F (Valuation.entry c t'.k m' f') l' ds' S' E'.
Runs.of_chainWith. TakehP, a listLs, andcoversChain P fn p0 l ds S E Ls = true. Take a threadtwitht.frames = [f],f.fn = fn,f.label = l,f.pc = p0andRetLs Q Ls (Valuation.entry c t.k m f) l ds S E. Then∃ bs me, Runs c t m (((bif alloca then bs else []) ++ f.allocas).foldl (fun m b => m.setLive b false) me) ∧ Q me ∧ m.Adds (bif alloca then bs else []) me, withalloca = falsehere.Runs.of_loopisRuns.of_chainWith hP [L.toLoopSeg]without the flags.Runs.of_chainsAttakesRuns.of_loops's premises, withcoversChainsAt alloca false P fn Cs = trueand∃ C ∈ Cs, RetLs Q C.loops (Valuation.entry c t.k m f) C.l C.ds C.S C.Ein place of theirs. It concludes∃ bs me, Runs c t m ((bif alloca then bs else []).foldl (fun m b => m.setLive b false) me) ∧ Q me ∧ m.Adds (bif alloca then bs else []) me.Runs.of_chainsWithis its case with the flag off, concluding∃ m', Runs c t m m' ∧ Q m', andRuns.of_loopsisRuns.of_chainsWithwith the witnessL.chain.-
ChainWith.of_iterholds for everyF, loopL, loopsLs, path(l, ds, S) :: E, valuationV, functiongon valuations and trip countn. WriteV₀ = Valuation.round l S E Vfor the header's entry valuation. Suppose these hold:Edge L.h L.p V l ds S E;ChainWith false (BackWith false L.h L.p (· = g (g^[i] V₀))) L.inner (g^[i] V₀) L.h L.dh L.H L.Bfor everyi < n;ChainWith false F Ls (g^[n] V₀) L.h L.dh L.H L.X.
Then
ChainWith false F (L :: Ls) V l ds S Eholds. The invariant is "Wis thei-th iterate ofg". With nested loops the round functiongis notValuation.roundof the loop path. -
ChainWith.of_roundsis for a loop with no nested loop (L.inner = []). Suppose thatEdge L.h L.p V l ds S Eholds and that, for everyi < n,Round L.h L.p L.dh L.H L.Bholds at(Valuation.round L.h L.H L.B)^[i] (Valuation.round l S E V). Suppose also thatChainWith false F Lsholds at then-th iterate afterL's path out. ThenChainWith false F (L :: Ls) V l ds S E. On a concrete valuation andn, the first two premises are closed and decidable (EdgeWith.dec,RoundWith.dec). BackWith.enter: takehP,coversPathAt alloca false P fn p0 ((l, ds, S) :: E) = trueand a threadton memorymwitht.frames = f :: rest,f.fn = fn,f.label = l,f.pc = p0andBackWith false d q J (Valuation.entry c t.k m f) l ds S E. Thent's steps reach a framef'offnaboverestat blockd's positionq, withf'.allocas = (bif alloca then bs else []) ++ f.allocasandm.Adds (bif alloca then bs else []) m'for somebs,f'.dest = f.destandJ (Valuation.entry c t'.k m' f').ChainWith.enterconcludes the same fromcoversChainAt alloca false P fn p0 l ds S E Ls = trueandChainWith false (BackWith false d q J) Ls (Valuation.entry c t.k m f) l ds S E: a chain whose last path out stops after its last edge, intodatq, with no second chain relation. A continuation from that frame joins it (RunsVia.of_chain, MojoProof/Sym/OblSeg.lean); the instance is gemv_kernel's chain into%78(bfly_at, MojoProofTest/SymGemvTail.lean).
Proof
- Induction on
n. For0there is no step. Forn + 1, the induction hypothesis (with the premises fori < n) reaches the header withI n. The premise atnthen reaches it again withI (n + 1).Steps.transcomposes the steps, and each part keeps theallocablocks and the caller's register. -
Induction on
ChainWith, for every position, thread, memory and frame.ChainWith.last: there is no step.coversChainof no loop iscoversPathWith falseof the path.-
ChainWith.loop:coversChainsplits into the path,L.coversRoundand the rest.L.coversRoundiscoversChainof the round's paths, by cases onL.Block.sound_edgeentersL's header atL.p, withI 0.Block.sound_roundsruns thenrounds. Each round is the induction hypothesis on the round'sChainWith false, which reaches its last path. ThereBackWith falsegives that path's premises, its edge toL.hatL.pandI (i + 1), andBackWith.entertakes that edge.- The induction hypothesis on the path out, at a valuation of
I n, reaches the last path.
Steps.transcomposes the runs.
-
ChainWith.reachreaches the last path, whereRetgivesWalkWith falseandret.Block.sound_retWithgives the steps and the.donestep.Except.ok.injmatches the memory, and theallocablocks aref's. coversChainsgives the chosen chain's start label andcoversChainfrom 0 (List.all_eq_true). The start label isf.label, because both are the label offn's first block. Withf.allocas = []the cleanup is the identity. ForRuns.of_loops,coversLoopsiscoversChainsof the map, andList.mem_map_of_memgives the witness.ChainWith.loopwithI i W := W = g^[i] V₀.I 0isrfl. A round from thei-th iterate ends with the(i + 1)-th (Function.iterate_succ_apply').I n WisW = g^[n] V₀.ChainWith.of_iterwithg := Valuation.round L.h L.H L.B. With no nested loop, a round'sChainWith falseisChainWith.lastofBackWith false: theRoundpremise andrfl.BackWith.enterisBlock.sound_edgeatBackWith'sEdgeWith, the position byEdgeWith's last conjunct and the blocks byValuation.allocsWith_cond.ChainWith.enterisChainWith.reachto the last path, thenBackWith.enter, the blocks composed byallocas_trans.Block.sound_loop's rounds areBackWith.enterwithJ"the next iterate".
Dependencies
Block.sound_edge, Block.sound_retWith, Steps.trans, Ret, Valuation.round,
Function.iterate_succ_apply', List.all_eq_true, List.mem_map_of_mem.
Instances
In MojoProofTest/SymLoop.lean. Each instance is for one program, one bound and one memory, by evaluation.
Two loops in sequence:
cnt2is two counting loops in sequence. Its blocks:- the entry
0branches to header1; - header
1counts%i, with body2storing%ito cell%iat%p; - the first loop's exit
3branches to header4; - header
4counts%j, with body5storing%jto cell%jat%s; - the exit
6returns.
- the entry
loop1andloop2have no nested loop.cnt2Cis the chain of both after block0, whose summary iscntE, thebrofcnt's entry block into the first header.cnt2_coverscheckscoversChains cnt2P cnt2 [cnt2C] = truebydecide +kernel.cnt2_retLsisRetLsof the two loops atframe2's entry valuation, with%n = 2and%pand%sat the two 16-byte blocks ofout3. It usesChainWith.of_roundswith trip count 2 twice, thenChainWith.last. Its premises are checked bydecide +kernel, and so are the effects of the last block, which leave cells 0 and 1 of both blocks holding 0 and 1 (run_ok, :651).cnt2_runisRuns.of_chainsWithwith those two. The thread⟨[frame2], 0⟩runs onout3's memory to its end, and in the memory it leaves cells 0 and 1 of both blocks hold 0 and 1.cnt2_twinshas two parts.- The first loop alone,
RetLs Q [loop1] V 0 cntE.obls cntE [], fails for everyQandV. The invariant holds at the trip count (by induction on the rounds, eachChainWith.last). ThereRetneeds the path out1 → 3to end inret, but block3's exit goes to header4. coversChainsrefuses the chain whose second loop starts at its header's position 0 (thephi).
- The first loop alone,
Two nested loops:
nestisfor i in [0, n): for j in [0, n): p[j] = i. Its blocks:- the entry
0branches to the outer header1; - header
1(aphifor%i) branches into the inner header2or to the exit5; - header
2(aphifor%j) branches to the body3or to the latch4; - the body
3stores%ito cell%jat%pand branches back to2; - the latch
4increments%iand branches back to1; - the exit
5returns.
- the entry
loopJis the inner loop: header2at position 1, loop path2 → 3, path out2 → 4.loopIis the outer loop: header1at position 1, the loop path the header alone (B = []),inner = [loopJ], and the path out1 → 5.nestCis the chain ofloopIafter block0.nest_coverscheckscoversChains nestP nest [nestC] = truebydecide +kernel.hdrTis the outer header's entry valuation, andouterTis one outer round: the header, two inner rounds and the inner path out.nest_roundschecks, for each outer roundi < 2fromouterT^[i] hdrT, the header's edge into2at position 1, the inner loop's two rounds, and the inner path out's edge into1at position 1, bydecide +kernel.nest_retLsisRetLsof[loopI]atframeT's entry valuation (%n = 2,%patout2's block), whereQsays that cells 0 and 1 hold 1. It is proved in three parts:- the outer loop by
ChainWith.of_iter, withouterTand trip count 2; - each outer round by
ChainWith.of_roundsonloopJ, with trip count 2 (nest_rounds); - the outer path out to
ret, with the memory's cells, bydecide +kernel.
- the outer loop by
nest_runisRuns.of_chainsWithwithnest_coversandnest_retLs. The thread⟨[frameT], 0⟩runs onout2's memory to its end, and in the memory it leaves cells 0 and 1 hold 1, the outer counter's last value.nest_twinshas two parts.- Without its nested loop (
inner := []), the outer loop does not run toretfromframeT's entry valuation, for everyQ. With trip count 0 the outer path out fails at%i = 0 < 2. Otherwise the first round's path, the header alone, does not go back to the header. coversChainsrefuses the chain whose nested loop starts at its header's position 0 (thephi), because it checks the nested loop's paths.
- Without its nested loop (
The one-loop instances cnt_covers, cnt_loops, cnt_retL, cnt_run and cnt_run_outC go
through Runs.of_loop and Runs.of_loops, which are corollaries of the theorems above.
With the flag alloca (MojoProofTest/SymLoopAlloca.lean), on one hand-built kernel @k with
gemv_kernel's header and data layout: a counting loop from 0 to 2 whose body %4 allocates an
i32 each round, its locals numbered as the parser numbers them; its printed text imports back
to the same module (Mutate.admission).
loopK_covers:coversChainsAt true falseaccepts the entry block, the loop path from the header's position 1 and the path out; the body's summary has thealloca's effect, andcoversChainsWith falserefuses the loop.loopK_mutant: with the flag, the checker refuses the body summary without itsallocaeffect and the loop entered at the header's position 0, itsphi.loopK_retLsandloopK_run: for the contextctx0with the program, the thread whose one frame is at@k's first block and the memorymemK(one launch block at number 1 holding thei327, so the fresh numbers start at 2),ChainWith.of_roundswith trip count 2 andRuns.of_chainsDead (alloca := true): the thread runs to its end on a memory whose two rounds' blocks 18 and 83 are dead (4 bytes each) and whose load of block 1 ismemK's, 7.loopK_inUse: onmemKwith a block already at 18 (memX), the kernel decides that the rounds' premises fail: the first round'sallocafaults on the number in use.
The theorems cover every program and every chain of loops, in sequence and nested, that the
checker accepts. The first part of each twin covers every predicate, and for cnt2_twins every
valuation.
Limits
cnt2_retLsandnest_retLsare forn = 2on one memory, by evaluation. A proof for every bound needs each loop's invariant steps, asinvN_stepgives them forcnt.Kernel.sound_of_pathsandmojo_kernel(MojoProof/Sym/Kernel.lean) still take loop-free paths.
The naive kernel's thread through its loop (thread_run, thread_skip, thread0)
Lean: MojoProofTest/NaiveThread.lean, with Valuation.roundWith_k in
MojoProof/Sym/Loop.lean. The kernel is the naive matmul (naive,
MojoProofTest/SymPhi.lean); the plan of its kernel theorem is in docs/proofs/kernel.md, and this
section is that plan's run of one thread of S (its step 4).
Scope. Valuation.roundWith_k: every flag, header label, summary, path, valuation and number
of rounds. steps and thread_run: every valuation of naive's function (so every thread of
every launch, at any step count), every list of factor pairs (the trip count K is its length),
and every predicate on the head's valuations and on the memory at the return. thread_skip:
every valuation and predicate on the memory at the return. thread0, thread0_twin and
skip_threads are tests: one launch, one memory, one address choice, one oracle.
Statement
Valuation.roundWith_k.irounds (Valuation.roundWith contract'si-th iterate) keep the context and the function and addi * (pathLen S B + 1)to the step count.steps. For the naive kernel's chainchainN(the path%6 → %45into%46's position 2, then the loopnaiveL, accepted bycoversChainsWith true:chainN_covers): the path adds 39 steps, a round adds 18, and the latch%52is entered 3 steps after the head. Itsfmul(statement 12) andfadd(statement 13) in roundjare thus the stepsk0 + 54 + 18 jandk0 + 55 + 18 jof a thread whose entry valuation has step countk0, and their oracle numbers areoN c k0 j, the context's oracle at those steps, lane 0. The positions are proved from the step count, not read off a run.Inv o ps j W:%47 = jand%48holdsdotLoop true o +0 (ps.take j).-
thread_run. For a valuationVwithV.fn = naive.fn_0, pairspsand predicatesG(on head valuations) andQ(on memories), suppose:hE: the entry block%6's obligations hold atVand its branch goes to%45(the thread is in bounds);h0:Inv (oN V.ctx V.k) ps 0andGat the head after%6 → %45;hR: for everyj < ps.lengthand every head valuationWwithV's context and step countV.k + 39 + 18 jwhereInvandGhold: the round's premises (RoundWith true),Gafter it,%47 = j + 1after it, and%48after it is thefadd contractof%48before it and thefmul contractof pairj, at the oracle numbers of the latch's statements 12 and 13;hX: at the head afterps.lengthrounds whereInvandGhold, the path out%46 → %51 → %67 → %69returns with a memory ofQ(RetWith true).
Then
∃ C ∈ [chainN], RetLsWith true Q C.loops V C.l C.ds C.S C.E. WithV = Valuation.entry (c k) 0 m' fthis is the second disjunct of the per-thread premise of the kernel theorem withfmul contractforchains = [chainN]. -
thread_skip. For a valuationVand a predicateQon memories: if%6's obligations hold atV, its branch goes to%44(the thread is out of bounds), andQholds of the memory that%6's effects give (its three loads, which add trace entries), thenRetWith true V Q skipN, whereskipNis the path%6 → %44 → %69, accepted bycoversPathWith true(skipN_covers): the first disjunct of that premise, forpaths = [skipN]. No store runs on the path.
The premises are the obligations the checker does not decide, each at a symbolic W: the
bounds %47 < %16 with %16 = smax(K, 0), the address arithmetic of the latch's loads (they
read pair j) and of the store, and the in-bounds test of %6. The oracle positions are not
premises.
Proof
steps is Valuation.roundWith_k at the path (one round of %6 → %45, whose pathLen is 38)
and at naiveL (pathLen 17), and Valuation.lastWith_k with the latch's length 14, the
lengths by decide +kernel. thread_run applies Round.of_inv with the invariant
W.ctx = V.ctx ∧ W.k = V.k + 39 + 18 j ∧ Inv … j W ∧ G W. In a round, hR gives the
registers after it; steps turns the latch's oracle steps into oN's, floatBin_dotStep
turns the fmul and fadd into dotStep true, and dotLoop of ps.take (j + 1) is
dotStep of dotLoop of ps.take j. The rounds then give ChainWith.of_rounds, the edge
%45 → %46 is SymNaive.pre_edge (every valuation), and hX closes the chain with
ChainWith.last. thread_skip unfolds RetWith: %44 and %69 have no effect and the one
obligation .mem [], %44 is a br, and the memory at %69's entry is that of %6's effects
(Valuation.intoWith keeps Valuation.after's memory).
Instances
thread0_chain,thread0: the startstartNofnaiveon one block of 2 × 2 threads withm = n = 1andK = 2(argsN), the memorymemN(C one cell, A and B row 0 of MojoProofTest/NaiveRun.lean's matrices), the address choice 0 and the oracleωN, which gives 2 (fuse thefadd) at step 73. All ofthread_run's premises at thread 0, the one in bounds, are closed bydecide +kernel, withGthe three head valuations.Runs.of_chainsWith truethen runs thread 0 fromGrid.start's frame to its end, and cell(0, 0)holdsdotLoop true (oN (cN 0) 0) +0 psN, the word0xa8800000(-2 ^ -46). The oracle numbers used are those of steps 54, 55, 72 and 73 (0, 0, 0 and 2).thread0_twin: underoN (cN 0) 1, the numbers one step later (55, 56, 73, 74), round 1'sfadddoes not fuse,dotLoopgives+0, andInvfails at the head after two rounds.skip_threads: at the same start, threads 1 to 3 (out of bounds) run to their end bythread_skipandRuns.of_retWith, with the memory of their three loads, the premises closed bydecide +kernel; thread 0's branch goes to%45, sothread_skip's premise fails there. Withthread0, every thread of the launch runs to its end.
Limits
startN's launch hasm = n = 1and blocks of one and two floats, so it does not meetNaiveSpec.At. MojoProofTest/NaiveStart.lean has an evaluated start that does (m = 1,n = 2,Cof50257 * 4bytes,AandBread-only, everyA,B,K ≤ 768and oracle), withNaiveIn.runInandNaiveOut.runOutat each of its four threads (NaiveStart.runs12).thread0,thread0_twinandskip_threadsare aboutmemNandωN(a concrete cell value, a failing invariant, the memory of the loads), so they are not corollaries of it.- The kernel theorem for
naivestill needs the premises ofthread_runandthread_skipdischarged at a symbolic thread (the obligation prover), the start facts for the threebyvalstructs, and theElembookkeeping of the plan's steps 2, 3 and 5 (among it, that an out-of-bounds thread's loads keep the cells).
Facts at a loop's heads (LoopSeg.kept, LoopSeg.loadsFrom, LoopSeg.stepAt)
Lean: MojoProof/Sym/LoopFacts.lean. Tests: MojoProofTest/LoopFacts.lean.
Scope. Every program, function and loop (LoopSeg), every flag contract, valuation and
round count. The checks are Booleans and lists over the summaries, which the kernel computes on a
concrete loop; the lemmas hold for every loop the checks accept. A round here is the loop path's
(Valuation.roundWith c L.h L.H L.B); a round of a loop with nested loops also runs theirs, and
the lemmas then hold for its loop path alone, not for the whole round.
Statement
Registers the loop keeps. Summary.reads S lists the registers a block reads: the SVal.reg
operands of its nodes, register updates, effects, obligations and exit (SVal.reads,
SNode.reads, SEff.reads, Cond.reads, Exit.reads). Func.keeps F Ss r holds when no phi
of F and no summary of Ss sets r. LoopSeg.kept F L lists, once each and in the order of
their first read, the registers the loop path and the path out read (L.H, L.B, L.X) that
the loop path L.H :: L.B keeps. LoopSeg.kept_round: a register of LoopSeg.kept F L that is
v at a valuation of F is v after every number of rounds. It is Valuation.iterate_regs_keep
(MojoProof/Sym/Inv.lean), the register lemma over Valuation.roundWith, with its two premises
read off the list.
Memory facts. Summary.loadsIn rs S holds when every effect of S is a load whose pointer has
its base in the registers rs (SVal.baseIn, MojoProof/Sym/Payload.lean: a register of rs, or
a getelementptr node based at one). LoopSeg.loadsFrom F L rs holds when the loop path keeps
each register of rs (Func.keeps) and each of its blocks passes Summary.loadsIn rs.
Valuation.iterate_loads: take a set of blocks Q and a property P of memories that logging a
read of a block of Q that is not an atomicrmw's keeps (an access with a.write = false,
a.atomic = none and Q a.ptr.block; a load logs such an access). If the loop
passes LoopSeg.loadsFrom F L rs, the registers rs have values at V that name only blocks of
Q, and P holds at V's memory, then P holds after every number of rounds. Instances:
Valuation.iterate_blocks(Qevery block): the memory's blocks and next block number stay (only the trace grows). SoMem.Buffer,Mem.FitsandMem.Holdsstay (theirof_block, withMem.blocks_keep).Valuation.iterate_elemandValuation.iterate_only(Q = (· ≠ o)):Elem … o …stays (Elem.log_read), and so doesElem.Only o T(Elem.Only.log_other).
Oracle positions. pathOff S ps i is the number of steps from the entry of the path S :: ps
to the entry of its block i. Valuation.lastWith_off: block i's entry valuation, the last
block of the path's first i + 1 blocks, has the path's step count plus pathOff S ps i.
LoopSeg.stepAt L S E k j i is the step count at block i of round j of L (block 0 is the
header), for a thread whose entry path S :: E starts at step count k: `k + (pathLen S E + 1)
- j * (pathLen L.H L.B + 1) + pathOff L.H L.B i
.LoopSeg.stepAt_ksays that this is the step count of that block's entry valuation. A float node at offsetnof its block reads the oracle at that step count plusn(SNode.fbin's step field).LoopSeg.steps_kgives the step counts of the entry path, ofjrounds and of the loop path's last block from the entry path's length, the round's and the last block's offset, each a premise thatdecide` proves on a concrete loop.
Proof
LoopSeg.kept_round: a listed register passes Func.keeps for the loop path's summaries
(List.mem_filter), which are Valuation.iterate_regs_keep's premises.
Valuation.iterate_loads: by induction on the round count, and within a round by induction on
the loop path. A block's memory is its effects' run (SEff.apply folded over the effects), or
the block's entry memory when they fault. Each load logs a read through its pointer's value,
whose block is one the base register names (SVal.eval_baseIn), so a block of Q. An edge keeps
the memory (Valuation.intoWith). The registers rs keep their values into the next block and
the next round (Valuation.iterate_regs_keep, with Func.keeps from LoopSeg.loadsFrom).
Valuation.lastWith_off: by induction on the path, with Valuation.intoWith_k.
LoopSeg.stepAt_k: Valuation.roundWith_k for the entry path and the rounds, then
Valuation.lastWith_off on the first i edges of the loop path. LoopSeg.steps_k:
Valuation.roundWith_k and Valuation.lastWith_off at L.B.length.
Instances
MojoProofTest/LoopFacts.lean, on the naive kernel's chainN (naiveL after the entry path
%6 → %45):
naive_kept:LoopSeg.kept naive.fn_0 naiveLis%16,%26,%11,%37,%12,%40. These are the boundsmax(K, 0), the row offset, the pointer toA, the column offset, the pointer toBand the cell's address (the registersNaiveSound.naive.keptstates);naive_kept_roundisLoopSeg.kept_roundat them.naive_loads: the loop passesLoopSeg.loadsFromwith%11and%12. So at a head whose%11and%12point outside blocko, the rounds keepElemato(naive_elem) andElem.Only o(naive_only).naive_blocks: at a head whose%11and%12are pointers, the rounds keep the memory's blocks and next block number (Valuation.iterate_blocks), the premise of the buffers'of_block.naive_steps: the head of roundjis atk + 39 + 18 * jand block 2 (the latch) atk + 42 + 18 * j(LoopSeg.stepAt_kwith the entry path's length 38, the round's 17 and the latch's offset 3, each bydecide). The latch'sfmulandfadd(offsets 12 and 13) are atk + 54 + 18 * jandk + 55 + 18 * j, the steps whose oracle numbersNaiveThread.oNreads.
And on cnt2's two loops (MojoProofTest/SymLoop.lean), which store: cnt2_kept (the bound %10
and the pointers %11 and %16; the counters, set by phis, are not kept), cnt2_stores
(LoopSeg.loadsFrom is false for the loop that stores) and cnt2_steps (LoopSeg.steps_k: 1
step for the entry block, 6 a round, 2 to the body).
Design: the loop clause for a matmul thread (partly implemented)
This section is a design. Of its order of work, steps 2 and 3 are in the Lean sources ("Facts at a
loop's heads" above); steps 1 and 4 are not, and no statement of theirs is proved. It says what the
loop clause of mojo_kernel (docs/kernel.md, "The loop clause") must carry so that, with mat, the
command computes a matmul thread's chain from the loop's header and proves the thread's run, in
place of the chain and the run the user gives today, and which statements change.
Today
mat paths chains(docs/proofs/kernel.md, "The 2-D clause") takes the chains as a term ([chainN], written by hand in MojoProofTest/NaiveThread.lean) and leaves the runHinof a thread in bounds to the user.mat paths chains inv(docs/proofs/kernel.md, "Hinfrom an invariant" and "The heads of the rounds") also generatesn.runInv, the run of a thread in bounds from its entry facts,Elem,Elem.OnlyandLoopIterWith(an invariant's three facts at the heads of the rounds, whereMat.Headholds) throughRetLsWith.of_iter, with the edge bymojo_oblandMat.Headat every head by mojo_inv andMat.Head.iterate;n.kept, each register the loop keeps (LoopSeg.kept) at every head with its value at the loop head (LoopSeg.kept_round); andn.sound_inv, whose one premise isLoopIterWithat each thread'sMat.Thread.Mat.Thread(Sym/KernelMat.lean) is the structure of a thread's facts that step 1 below namesMat.ThreadandMat.Facts: one structure has both the thread's parameters and its facts. For the naive kernel,NaiveIn.runInisnaive.runInvathead_in,round_inandexit_in(8 lines), the last two bymojo_obl(naive_rounds,naive_exit) withMat.Headand the registers the loop keeps (naive.kept) at the loop's heads;thread_runis then not used by it.- The loop clause
loop h := pre inv trips postcomputes the chain from the header and provesn.entry,n.init,n.stepandn.exitat every valuationVofpre. Its four terms are closed terms over a valuation (pre : Valuation → Prop,inv : Valuation → Nat → Valuation → Prop,trips : Valuation → Nat,post : Valuation → Mem → Prop), and its default tactic evaluates one concrete launch.
The two do not combine, for three reasons.
Hin's premises and its postcondition mention the binders ofKernel.sound_mat: the launchL, the threadk, the sizesm,n,K, the blockso,a,b, the strides, the tensorsxandy, the memorym₀, the cell widthwand the bytesbs. A closedpreorpostcannot name them.- The bytes
bsare a binder ofKernel.sound_mat, so no run can show that a thread storesbs k. The clause must fix them as a function of the inputs, asNaiveSpec.bytesdoes. - The obligations hold only under facts that
Kernel.sound_matdoes not state: the strides and the element type the IR's address arithmetic and loads assume (naive's IR multiplies by 768 and 50257 and loadsfloat),Kat most the input stride, and thei32products of the address arithmetic below2 ^ 31(NaiveSpec.At.dims).
What the clause must carry
The thread's parameters as one record. A structure Mat.Thread with the launch, the thread,
the sizes, the blocks, the strides, the element type with its encoder and alignment, the
tensors, the memory m₀, the cell width and the oracle family. The clause's terms take it:
pre : Mat.Thread → Propin place ofValuation → Prop: the strides, the element type,Kand thei32ranges;inv : Mat.Thread → Nat → Valuation → Propin place ofValuation → Nat → Valuation → Prop: the loop-carried registers only (below);trips : Mat.Thread → Natin place ofValuation → Nat(max K 0for naive);bytes : Mat.Thread → Nat → Option (List MemByte)in place ofpost: the postcondition isHin's,Elemafterk + 1threads andElem.Only, at those bytes.
The entry facts as one predicate. Mat.Facts θ c m' f: the premises of Hin from
c.prog = prog to Elem.Only, with the thread's entry valuation Valuation.entry c 0 m' f.
n.entry and n.init are stated at every θ of pre, every c, m', f of
Mat.Facts θ, at that valuation.
The 2-D index facts. On a 1-D launch the index of thread k is k (Launch.index_oneDim),
so the index needs no name of its own. On a 2-D launch the row and the column are
L.index k .x and L.index k .y, which no tactic simplifies, so the facts must name them as two
numbers r and col with:
r < mandcol < n(the thread is in the matrix:Hin's window);ctaid.d * ntid.d + tid.dofL.env kequal torford = .xand tocolford = .y(the definition ofLaunch.index), each special register below its bound and the sums below2 ^ 42(Launch.sreg_lt,Launch.index_lt), so the IR'szext,sext,mulandaddof them give the words of the natural numbers (Launch.index_ops);- side 1 in
z(hz), so that nozregister enters the index.
These are the hypotheses OblMatmul.naive_entry takes, and mojo_obl proves the entry path's
obligations from them at every launch.
The heads' facts, computed. Besides the loop-carried registers, the facts at the loop's heads
are mostly facts the checker computes ("Facts at a loop's heads" above). The mat … inv clause
now proves the first two kinds below at every head: the registers the loop keeps
(naive.kept, by LoopSeg.kept_round) and the memory facts with the function (Mat.Head, by
Mat.Head.iterate at LoopSeg.bases; docs/proofs/kernel.md, "The heads of the rounds"):
- registers the loop keeps:
LoopSeg.keptandLoopSeg.kept_round. For naive these are%11,%12(the input pointers),%16(smax(K, 0)),%26,%37(row and column times the stride) and%40(the cell's address); - the memory facts:
LoopSeg.loadsFromandValuation.iterate_loads, withValuation.iterate_elemandValuation.iterate_onlyforElemandElem.OnlyatoandValuation.iterate_blocksforBuffer,FitsandHolds. For naive the bases are%11and%12, ataandb; - the oracle positions:
LoopSeg.stepAtandLoopSeg.stepAt_k. The oracle numbers of each round'sfmulandfadd(NaiveThread.oN) areLoopSeg.stepAtof the latch plus the nodes' offsets 12 and 13.NaiveThread.stepsis an instance ofLoopSeg.steps_k.
The generated invariant at round j is then the user's inv θ j W together with these three,
and the user writes only the loop-carried registers (for naive, NaiveThread.Inv: %47 = j and
%48 the dotLoop of the first j pairs).
Which statements change
Kernel.sound_mat,LoopChain,coversChainsWith,RetLsWith,NaiveThread.thread_run,thread_skip,NaiveSpec.Atandnaive_soundkeep their statements. The new run is an instance ofHin's shape, soKernel.sound_mattakes it as it is.- The loop clause without
matkeeps its four terms and its obligations. - New with
matand a loop clause:n.chainsandn.coversChains(as for the loop clause; for naive a test thatn.chains = [chainN]), the obligationsn.entry,n.init,n.stepandn.exitoverθandMat.Facts θ, andn.loop, the run of a thread in bounds at everyθofpre:Hin's body withbs := bytes θ. - New theorem
n.sound_matLoop:n.sound_matwithoutHin, with the premisepre θand the bytes fixed tobytes θ.n.sound_matstays, so a kernel whose run the clause does not prove keeps the hand proof, and no generated statement changes. - For naive,
NaiveIn's four theorems would be the instances ofn.entry,n.init,n.stepandn.exit, andNaiveIn.runIna corollary ofn.loop;Mat.Headandnaive.kept, which themat … invclause now generates, would be the generated part of the invariant, withNaiveThread.Inv.
What the tactic must still do
The default tactic must be mojo_obl, which proves OblMatmul's obligations at every launch,
not decide +kernel, which evaluates one. The accumulator's step (floatBin_dotStep and
dotLoop of ps.take (j + 1), NaiveIn's round_in) and the stored bytes at the exit stay
kernel-specific and are the clause's tactic.
Order of the work
Mat.ThreadandMat.Facts, andKernel.sound_mat's premiseHinover them, as a corollary ofKernel.sound_mat.- Done: the register list and lemma (
LoopSeg.kept,LoopSeg.kept_round), and the load-only check with the memory lemma (LoopSeg.loadsFrom,Valuation.iterate_loads). - Done: the oracle positions (
pathOff,Valuation.lastWith_off,LoopSeg.stepAt,LoopSeg.stepAt_k,LoopSeg.steps_k). - The clause in
elabMat, and naive as its instance with the twins of the loop clause's tests (a tactic that leaves an obligation, a wrong header).